linesmith-core 0.1.3

Internal core engine for linesmith. No SemVer guarantee for direct dependents — depend on the `linesmith` binary or accept breakage between minor versions.
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
//! OAuth credential resolution for the OAuth `/api/oauth/usage`
//! endpoint. Reads the access token from macOS Keychain (primary +
//! multi-account fallback) or from a file cascade
//! (`$CLAUDE_CONFIG_DIR`, XDG, `~/.claude/`).
//!
//! Canonical spec: `docs/specs/credentials.md`.
//!
//! **Sensitivity contract.** The token never appears in [`Debug`] or
//! [`Display`] output anywhere in this module. [`Credentials`] wraps
//! the token in [`secrecy::SecretString`] with manual `Debug` that
//! redacts it. [`CredentialError::ParseError`] carries a
//! `serde_json::Error` whose Display would include a snippet of the
//! source bytes — our Display impl prints only the path and line /
//! column, never the cause's Display. [`std::error::Error::source`]
//! still chains to the raw cause so callers who opt in (with caution)
//! can inspect it.

use std::fmt;
use std::fs;
use std::io::{self, Read};
use std::path::{Path, PathBuf};

use secrecy::{ExposeSecret, SecretString};

/// Maximum credentials-file size we'll read. Claude Code writes
/// small files (typically <2 KB); cap at 1 MB per
/// `docs/specs/credentials.md` §Edge cases ("Huge credentials file")
/// to defend against pathological inputs.
const MAX_FILE_SIZE: u64 = 1_000_000;

#[cfg(target_os = "macos")]
const KEYCHAIN_SERVICE: &str = "Claude Code-credentials";

// --- Types --------------------------------------------------------------

/// Resolved OAuth credentials. Clone-on-Arc across segments; the
/// underlying [`SecretString`] is cheap to clone.
#[derive(Clone)]
pub struct Credentials {
    token: SecretString,
    scopes: Vec<String>,
    source: CredentialSource,
}

impl Credentials {
    /// Access the raw bearer token. Consumers must not log or
    /// serialize the returned string.
    #[must_use]
    pub fn token(&self) -> &str {
        self.token.expose_secret()
    }

    /// OAuth scopes granted to this token.
    #[must_use]
    pub fn scopes(&self) -> &[String] {
        &self.scopes
    }

    /// Which cascade step yielded the token (informational, for
    /// `linesmith doctor`).
    #[must_use]
    pub fn source(&self) -> &CredentialSource {
        &self.source
    }
}

impl fmt::Debug for Credentials {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Credentials")
            .field("token", &"<redacted>")
            .field("scopes", &self.scopes)
            .field("source", &self.source)
            .finish()
    }
}

#[cfg(test)]
impl Credentials {
    /// Test-only constructor. Lets other modules in the crate
    /// fabricate a `Credentials` without running the cascade.
    /// Rejects empty tokens so tests can't fabricate a state the
    /// production resolver would reject as `EmptyToken`.
    pub(crate) fn for_testing(token: impl Into<String>) -> Self {
        let token: String = token.into();
        debug_assert!(
            !token.is_empty(),
            "Credentials::for_testing requires a non-empty token",
        );
        Self {
            token: SecretString::from(token),
            scopes: Vec::new(),
            source: CredentialSource::ClaudeLegacy {
                path: PathBuf::from("/test"),
            },
        }
    }
}

/// Where [`resolve_credentials`] found the token.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum CredentialSource {
    /// `security find-generic-password -s "Claude Code-credentials"`.
    MacosKeychainPrimary,
    /// `security dump-keychain` scan for
    /// `Claude Code-credentials<suffix>` entries; newest `mdat` wins.
    MacosKeychainMultiAccount {
        service: String,
        mdat: Option<String>,
    },
    /// `$CLAUDE_CONFIG_DIR/.credentials.json`.
    EnvDir { path: PathBuf },
    /// `$XDG_CONFIG_HOME/claude/.credentials.json` (fallback to
    /// `~/.config/claude/.credentials.json`).
    XdgConfig { path: PathBuf },
    /// `~/.claude/.credentials.json` (Claude Code's legacy path).
    ClaudeLegacy { path: PathBuf },
}

/// Failure modes for [`resolve_credentials`]. `Debug` and `Display`
/// deliberately avoid forwarding `serde_json::Error`'s Display because
/// its context snippet may include token bytes; the raw cause is still
/// reachable via [`std::error::Error::source`] for callers who need it.
#[non_exhaustive]
pub enum CredentialError {
    /// No token found in any cascade path.
    NoCredentials,
    /// `security` subprocess failed to launch or exited non-zero for
    /// non-"not-found" reasons (Keychain locked, permission denied,
    /// binary missing).
    SubprocessFailed(io::Error),
    /// Credentials file exists but could not be opened / read
    /// (permission denied, truncated read, filesystem error).
    IoError { path: PathBuf, cause: io::Error },
    /// Credentials file is not valid JSON. Inner cause preserved for
    /// [`std::error::Error::source`]; neither Display nor Debug
    /// forwards its text.
    ParseError {
        path: PathBuf,
        cause: serde_json::Error,
    },
    /// Credentials file parsed but the `claudeAiOauth` section is
    /// absent entirely. Typically indicates a stale Claude Code
    /// writer or a different tool sharing the path.
    MissingField { path: PathBuf },
    /// `claudeAiOauth` is present but `accessToken` is missing,
    /// `null`, or an empty string — the token slot exists but can't
    /// be used.
    EmptyToken { path: PathBuf },
}

impl CredentialError {
    /// Short plugin-facing error tag per `docs/specs/plugin-api.md`
    /// §ctx shape exposed to rhai. `MissingField` and `EmptyToken`
    /// aren't in plugin-api.md's enumerated list yet; spec will add
    /// them in a v0.2 rev.
    #[must_use]
    pub fn code(&self) -> &'static str {
        match self {
            Self::NoCredentials => "NoCredentials",
            Self::SubprocessFailed(_) => "SubprocessFailed",
            Self::IoError { .. } => "IoError",
            Self::ParseError { .. } => "ParseError",
            Self::MissingField { .. } => "MissingField",
            Self::EmptyToken { .. } => "EmptyToken",
        }
    }
}

/// Lossy `Clone`: `io::Error` and `serde_json::Error` don't implement
/// `Clone`, so variants carrying them reconstruct near-equivalents
/// (same `kind()` + textual message; `raw_os_error` and serde line
/// numbers are lost). The variant tag — which is what [`Self::code`]
/// and segment renderers key off per `rate-limit-segments.md`
/// §Error message table — round-trips exactly. The crate's
/// `unsafe_code = "forbid"` lint forecloses a transmute-based shallow
/// clone, so this is the cheapest way to preserve variant-level
/// detail across `Arc<Result<_, Self>>` boundaries like the cascade.
impl Clone for CredentialError {
    fn clone(&self) -> Self {
        match self {
            Self::NoCredentials => Self::NoCredentials,
            Self::SubprocessFailed(e) => {
                Self::SubprocessFailed(io::Error::new(e.kind(), e.to_string()))
            }
            Self::IoError { path, cause } => Self::IoError {
                path: path.clone(),
                cause: io::Error::new(cause.kind(), cause.to_string()),
            },
            Self::ParseError { path, cause } => Self::ParseError {
                path: path.clone(),
                cause: serde_json::Error::io(io::Error::other(cause.to_string())),
            },
            Self::MissingField { path } => Self::MissingField { path: path.clone() },
            Self::EmptyToken { path } => Self::EmptyToken { path: path.clone() },
        }
    }
}

impl fmt::Debug for CredentialError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NoCredentials => f.write_str("NoCredentials"),
            Self::SubprocessFailed(e) => {
                f.debug_tuple("SubprocessFailed").field(&e.kind()).finish()
            }
            Self::IoError { path, cause } => f
                .debug_struct("IoError")
                .field("path", path)
                .field("cause_kind", &cause.kind())
                .finish(),
            Self::ParseError { path, cause } => f
                .debug_struct("ParseError")
                .field("path", path)
                .field("line", &cause.line())
                .field("column", &cause.column())
                .finish(),
            Self::MissingField { path } => {
                f.debug_struct("MissingField").field("path", path).finish()
            }
            Self::EmptyToken { path } => f.debug_struct("EmptyToken").field("path", path).finish(),
        }
    }
}

impl fmt::Display for CredentialError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NoCredentials => f.write_str("no OAuth credentials found"),
            Self::SubprocessFailed(e) => {
                write!(f, "security subprocess failed ({kind})", kind = e.kind())
            }
            Self::IoError { path, cause } => write!(
                f,
                "failed to read credentials file {}: {kind}",
                path.display(),
                kind = cause.kind()
            ),
            Self::ParseError { path, cause } => write!(
                f,
                "credentials file {} failed to parse at line {}, column {}",
                path.display(),
                cause.line(),
                cause.column()
            ),
            Self::MissingField { path } => write!(
                f,
                "credentials file {} missing claudeAiOauth.accessToken",
                path.display()
            ),
            Self::EmptyToken { path } => write!(
                f,
                "credentials file {} has empty accessToken",
                path.display()
            ),
        }
    }
}

impl std::error::Error for CredentialError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::SubprocessFailed(e) => Some(e),
            Self::IoError { cause, .. } => Some(cause),
            Self::ParseError { cause, .. } => Some(cause),
            _ => None,
        }
    }
}

// --- Serde shapes -------------------------------------------------------

#[derive(serde::Deserialize)]
struct CredentialsFile {
    #[serde(rename = "claudeAiOauth")]
    claude_ai_oauth: Option<ClaudeAiOauth>,
}

#[derive(serde::Deserialize)]
struct ClaudeAiOauth {
    /// Double-wrapped `Option` so we can tell "key absent" from
    /// "key present and null" — serde's default `Option<String>`
    /// collapses both into `None`. With [`deserialize_explicit`]:
    ///   * key absent       → `None`             → `MissingField`
    ///   * explicit `null`  → `Some(None)`       → `EmptyToken`
    ///   * empty string     → `Some(Some(""))`   → `EmptyToken`
    ///   * non-empty string → `Some(Some(_))`    → token
    ///   * any other type   → serde fails parse  → `ParseError`
    #[serde(
        default,
        rename = "accessToken",
        deserialize_with = "deserialize_explicit"
    )]
    access_token: Option<Option<String>>,
    #[serde(default)]
    scopes: Vec<String>,
}

/// Deserialize helper that preserves the distinction between an
/// absent JSON key and one explicitly set to `null`. Invoked only
/// when the key is present (`#[serde(default)]` handles absence).
fn deserialize_explicit<'de, D>(de: D) -> Result<Option<Option<String>>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::Deserialize;
    Option::<String>::deserialize(de).map(Some)
}

// --- Public entry point -------------------------------------------------

/// Resolve the OAuth access token via the cascade in
/// `docs/specs/credentials.md` §Resolution cascade: macOS Keychain
/// (primary + multi-account) on macOS, then file-based cascade on all
/// platforms. Memoization for process-lifetime reuse is the caller's
/// responsibility; each invocation re-runs the full cascade.
pub fn resolve_credentials() -> Result<Credentials, CredentialError> {
    resolve_credentials_with(&FileCascadeEnv::from_process_env())
}

/// Same cascade as [`resolve_credentials`] but with an explicit
/// [`FileCascadeEnv`]. Lets doctor and tests pin the file-cascade
/// inputs without mutating process env, which is racy under Rust's
/// default parallel test execution.
///
/// macOS Keychain probes don't depend on the file-cascade env vars
/// in `FileCascadeEnv`; they shell out to `security` (which reads
/// `$USER` independently to scope the lookup).
pub fn resolve_credentials_with(env: &FileCascadeEnv) -> Result<Credentials, CredentialError> {
    // Hold the first "fall-through" subprocess error so if every
    // later cascade step also yields nothing, we surface the real
    // reason (e.g., Keychain locked) instead of a generic
    // `NoCredentials`. Per credentials.md §Resolution cascade step 1.
    #[cfg_attr(not(target_os = "macos"), allow(unused_mut))]
    let mut first_subprocess_err: Option<CredentialError> = None;

    #[cfg(target_os = "macos")]
    {
        match macos::try_keychain_primary() {
            Ok(Some(creds)) => return Ok(creds),
            Ok(None) => {}
            Err(e) => first_subprocess_err = Some(e),
        }
        match macos::try_keychain_multi_account() {
            Ok(Some(creds)) => return Ok(creds),
            Ok(None) => {}
            Err(e) => {
                if first_subprocess_err.is_none() {
                    first_subprocess_err = Some(e);
                }
            }
        }
    }

    match try_file_cascade_with(env) {
        Ok(creds) => Ok(creds),
        Err(CredentialError::NoCredentials) => {
            // Prefer a recorded subprocess failure over the generic
            // "nothing found" terminal.
            Err(first_subprocess_err.unwrap_or(CredentialError::NoCredentials))
        }
        Err(e) => Err(e),
    }
}

// --- File cascade -------------------------------------------------------

/// Environmental inputs for the file-cascade portion of credential
/// resolution. macOS Keychain probes shell out to `security` and
/// don't depend on these fields, so only the file-cascade env vars
/// live here. Treats empty string as unset per `credentials.md`
/// §Edge cases.
///
/// Built once at the call boundary — `driver.rs` and `lib.rs::run_*`
/// pull from process env via [`Self::from_process_env`]; doctor
/// builds via the same factory; tests construct directly. The
/// cascade itself never touches `std::env`.
///
/// **Construction safety**: prefer [`Self::new`] or
/// [`Self::from_process_env`] over struct-literal construction. Both
/// constructors enforce the empty-string-as-unset invariant; direct
/// field assignment trusts the caller. An empty `PathBuf` (`""`)
/// passed in via direct construction would make the cascade walk
/// `"".join(".credentials.json")` = `".credentials.json"` (a
/// CWD-relative path), which `try_file_cascade_with` would then
/// stat against whatever directory the binary happened to launch
/// in. That's a security-relevant footgun for a credential
/// resolver — use the constructors.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct FileCascadeEnv {
    /// `$CLAUDE_CONFIG_DIR`.
    pub claude_config_dir: Option<PathBuf>,
    /// `$XDG_CONFIG_HOME`.
    pub xdg_config_home: Option<PathBuf>,
    /// `$HOME`.
    pub home: Option<PathBuf>,
}

impl FileCascadeEnv {
    /// Build a [`FileCascadeEnv`] with empty-string-as-unset
    /// normalization. Pass `None` for "unset"; pass `Some(path)` for
    /// "set to this value." Empty-string `OsString` values collapse
    /// to `None` per `credentials.md` §Edge cases.
    #[must_use]
    pub fn new(
        claude_config_dir: Option<std::ffi::OsString>,
        xdg_config_home: Option<std::ffi::OsString>,
        home: Option<std::ffi::OsString>,
    ) -> Self {
        fn nonempty(v: Option<std::ffi::OsString>) -> Option<PathBuf> {
            v.filter(|s| !s.is_empty()).map(PathBuf::from)
        }
        Self {
            claude_config_dir: nonempty(claude_config_dir),
            xdg_config_home: nonempty(xdg_config_home),
            home: nonempty(home),
        }
    }

    /// Snapshot the three relevant env vars from the process via
    /// `var_os` so non-UTF-8 values (Unix byte-string paths) survive
    /// through to the cascade. Empty strings collapse to `None`.
    /// Used by the bare [`resolve_credentials`] wrapper; explicit-env
    /// callers go through [`Self::new`].
    #[must_use]
    pub fn from_process_env() -> Self {
        Self::new(
            std::env::var_os("CLAUDE_CONFIG_DIR"),
            std::env::var_os("XDG_CONFIG_HOME"),
            std::env::var_os("HOME"),
        )
    }
}

/// Candidate (path, source) pairs for the file cascade, in order.
/// Returned as `Vec` rather than an iterator so tests can assert the
/// full list.
fn file_cascade_candidates(env: &FileCascadeEnv) -> Vec<(PathBuf, CredentialSource)> {
    let mut out = Vec::with_capacity(3);

    if let Some(dir) = &env.claude_config_dir {
        let path = dir.join(".credentials.json");
        out.push((path.clone(), CredentialSource::EnvDir { path }));
    }

    // XDG candidate is emitted whenever an XDG root is derivable —
    // either from `$XDG_CONFIG_HOME` directly, or from `$HOME` via the
    // default `~/.config`. A HOME-less CI/service environment with
    // only `$XDG_CONFIG_HOME` set still gets its XDG path probed.
    let xdg_root = env
        .xdg_config_home
        .clone()
        .or_else(|| env.home.as_ref().map(|h| h.join(".config")));
    if let Some(xdg_root) = xdg_root {
        let xdg_path = xdg_root.join("claude").join(".credentials.json");
        out.push((
            xdg_path.clone(),
            CredentialSource::XdgConfig { path: xdg_path },
        ));
    }

    // Legacy `~/.claude/` only makes sense when `$HOME` is available.
    if let Some(home) = &env.home {
        let legacy_path = home.join(".claude").join(".credentials.json");
        out.push((
            legacy_path.clone(),
            CredentialSource::ClaudeLegacy { path: legacy_path },
        ));
    }

    out
}

fn try_file_cascade_with(env: &FileCascadeEnv) -> Result<Credentials, CredentialError> {
    // Advance past `NotFound` and `PermissionDenied` — the spec's
    // "first readable+parseable file wins" (`credentials.md`
    // §Resolution cascade) means an unreadable path shouldn't shadow
    // a later path the user can actually open. Other IO errors are
    // terminal per credentials.md §Edge cases.
    for (path, source) in file_cascade_candidates(env) {
        match fs::metadata(&path) {
            Ok(_) => return read_and_parse_file(&path, source),
            Err(e)
                if e.kind() == io::ErrorKind::NotFound
                    || e.kind() == io::ErrorKind::PermissionDenied =>
            {
                continue
            }
            Err(cause) => return Err(CredentialError::IoError { path, cause }),
        }
    }
    Err(CredentialError::NoCredentials)
}

fn read_and_parse_file(
    path: &Path,
    source: CredentialSource,
) -> Result<Credentials, CredentialError> {
    let file = fs::File::open(path).map_err(|cause| CredentialError::IoError {
        path: path.to_path_buf(),
        cause,
    })?;
    let mut buf = String::new();
    // Read up to MAX_FILE_SIZE + 1 so we can detect oversized files
    // via buffer length. Rejecting oversized files explicitly (rather
    // than letting serde parse the prefix + padding) avoids a panic
    // on pathological inputs where the first bytes form a complete
    // valid JSON followed by trailing whitespace.
    file.take(MAX_FILE_SIZE + 1)
        .read_to_string(&mut buf)
        .map_err(|cause| CredentialError::IoError {
            path: path.to_path_buf(),
            cause,
        })?;
    if buf.len() as u64 > MAX_FILE_SIZE {
        return Err(CredentialError::IoError {
            path: path.to_path_buf(),
            cause: io::Error::new(
                io::ErrorKind::InvalidData,
                format!("credentials file exceeds {MAX_FILE_SIZE} byte limit"),
            ),
        });
    }
    parse_credentials_bytes(&buf, path, source)
}

fn parse_credentials_bytes(
    bytes: &str,
    path: &Path,
    source: CredentialSource,
) -> Result<Credentials, CredentialError> {
    let file: CredentialsFile =
        serde_json::from_str(bytes).map_err(|cause| CredentialError::ParseError {
            path: path.to_path_buf(),
            cause,
        })?;
    let oauth = file
        .claude_ai_oauth
        .ok_or_else(|| CredentialError::MissingField {
            path: path.to_path_buf(),
        })?;
    // Spec-driven taxonomy (credentials.md §Interface):
    //   key absent        → MissingField (shape problem)
    //   null or "" value  → EmptyToken   (slot present, unusable)
    //   non-string value  → ParseError   (surfaces earlier during
    //                       `serde_json::from_str` via the typed
    //                       `Option<Option<String>>` field)
    //   non-empty string  → success
    match oauth.access_token {
        None => Err(CredentialError::MissingField {
            path: path.to_path_buf(),
        }),
        Some(None) => Err(CredentialError::EmptyToken {
            path: path.to_path_buf(),
        }),
        Some(Some(s)) if s.is_empty() => Err(CredentialError::EmptyToken {
            path: path.to_path_buf(),
        }),
        Some(Some(s)) => Ok(Credentials {
            token: SecretString::from(s),
            scopes: oauth.scopes,
            source,
        }),
    }
}

// --- macOS Keychain -----------------------------------------------------

#[cfg(target_os = "macos")]
mod macos {
    use super::*;
    use std::io::Read;
    use std::os::unix::process::ExitStatusExt;
    use std::process::{Command, ExitStatus, Stdio};
    use std::time::{Duration, Instant};

    /// `security` subprocess budget. Matches the 2s OAuth endpoint
    /// budget from ADR-0011 §Endpoint contract; a wedged `security`
    /// process, locked Keychain that doesn't prompt, or pathological
    /// dump must not hang the statusline.
    const SECURITY_TIMEOUT: Duration = Duration::from_secs(2);
    const POLL_INTERVAL: Duration = Duration::from_millis(50);
    /// Grace period after `kill()` for the kernel to reap the child.
    /// If the child isn't reaped within this window we detach the
    /// reader threads instead of blocking — bounded timeout beats
    /// perfect cleanup.
    const KILL_GRACE: Duration = Duration::from_millis(500);
    /// Maximum stderr bytes embedded in a `Failed` error message.
    /// `dump-keychain` failures can emit multi-KB diagnostics; we
    /// cap to keep log payloads bounded.
    const MAX_STDERR_IN_ERROR: usize = 512;

    /// Exit code `security` uses when the requested item isn't in the
    /// keychain (macOS `errSecItemNotFound`). Any other non-zero exit
    /// indicates a real failure (locked keychain, permission denied,
    /// binary missing) that we must preserve for diagnostics.
    const ERR_SEC_ITEM_NOT_FOUND: i32 = 44;

    pub(super) fn try_keychain_primary() -> Result<Option<Credentials>, CredentialError> {
        let user = std::env::var("USER").unwrap_or_default();
        let mut args: Vec<&str> = vec!["find-generic-password"];
        if !user.is_empty() {
            args.extend(["-a", &user]);
        }
        args.extend(["-w", "-s", KEYCHAIN_SERVICE]);

        let run = run_security(&args).map_err(CredentialError::SubprocessFailed)?;
        match classify_security_exit(&run) {
            SecurityResult::ItemNotFound => return Ok(None),
            SecurityResult::Failed(e) => return Err(CredentialError::SubprocessFailed(e)),
            SecurityResult::Success => {}
        }
        let stdout = String::from_utf8_lossy(&run.stdout);
        let stdout = stdout.trim();
        if stdout.is_empty() {
            return Ok(None);
        }
        match parse_credentials_bytes(
            stdout,
            Path::new("keychain:Claude Code-credentials"),
            CredentialSource::MacosKeychainPrimary,
        ) {
            Ok(creds) => Ok(Some(creds)),
            Err(CredentialError::MissingField { .. } | CredentialError::EmptyToken { .. }) => {
                Ok(None)
            }
            Err(e) => Err(e),
        }
    }

    pub(super) fn try_keychain_multi_account() -> Result<Option<Credentials>, CredentialError> {
        let dump = run_security(&["dump-keychain"]).map_err(CredentialError::SubprocessFailed)?;
        match classify_security_exit(&dump) {
            SecurityResult::ItemNotFound => return Ok(None),
            SecurityResult::Failed(e) => return Err(CredentialError::SubprocessFailed(e)),
            SecurityResult::Success => {}
        }
        let dump_text = String::from_utf8_lossy(&dump.stdout);
        let mut candidates = parse_dump_for_services(&dump_text);
        // Newest mdat first; entries without mdat sort last (stable by
        // dump order).
        candidates.sort_by(|a, b| match (&a.mdat, &b.mdat) {
            (Some(am), Some(bm)) => bm.cmp(am),
            (Some(_), None) => std::cmp::Ordering::Less,
            (None, Some(_)) => std::cmp::Ordering::Greater,
            (None, None) => std::cmp::Ordering::Equal,
        });

        // A per-candidate failure (spawn error, timeout, locked-
        // keychain exit) shouldn't abort the whole multi-account
        // probe — later candidates may succeed. Capture the first
        // error and surface it only if every candidate misses.
        let mut first_err: Option<io::Error> = None;
        for candidate in candidates {
            let run = match run_security(&["find-generic-password", "-w", "-s", &candidate.service])
            {
                Ok(r) => r,
                Err(e) => {
                    if first_err.is_none() {
                        first_err = Some(e);
                    }
                    continue;
                }
            };
            match classify_security_exit(&run) {
                SecurityResult::ItemNotFound => continue,
                SecurityResult::Failed(e) => {
                    if first_err.is_none() {
                        first_err = Some(e);
                    }
                    continue;
                }
                SecurityResult::Success => {}
            }
            let stdout = String::from_utf8_lossy(&run.stdout);
            let stdout = stdout.trim();
            if stdout.is_empty() {
                continue;
            }
            match parse_credentials_bytes(
                stdout,
                Path::new("keychain"),
                CredentialSource::MacosKeychainMultiAccount {
                    service: candidate.service.clone(),
                    mdat: candidate.mdat.clone(),
                },
            ) {
                Ok(creds) => return Ok(Some(creds)),
                Err(CredentialError::MissingField { .. } | CredentialError::EmptyToken { .. }) => {
                    continue
                }
                Err(e) => return Err(e),
            }
        }
        match first_err {
            Some(e) => Err(CredentialError::SubprocessFailed(e)),
            None => Ok(None),
        }
    }

    pub(super) struct SecurityRun {
        pub status: ExitStatus,
        pub stdout: Vec<u8>,
        pub stderr: Vec<u8>,
    }

    pub(super) enum SecurityResult {
        /// Process exited with status 0.
        Success,
        /// Process exited with `errSecItemNotFound` — expected miss;
        /// the cascade should advance to the next step.
        ItemNotFound,
        /// Any other non-zero exit. Preserved so the cascade in
        /// `resolve_credentials` can surface the real reason if no
        /// later step yields credentials.
        Failed(io::Error),
    }

    /// Spawn `security` with stdout/stderr piped, drain both in reader
    /// threads so the child can't block on pipe-full, and enforce
    /// [`SECURITY_TIMEOUT`] by polling `try_wait` + killing on
    /// deadline.
    ///
    /// Happy path: child exits, pipes close, readers hit EOF, handles
    /// join to return accumulated bytes.
    ///
    /// Timeout path: `kill`, poll `try_wait` for up to [`KILL_GRACE`]
    /// so the kernel can reap the child and close the pipes. If reap
    /// doesn't happen in that window the reader handles are detached
    /// — they finish on their own once the kernel eventually reaps.
    /// Total budget is bounded at `SECURITY_TIMEOUT + KILL_GRACE`.
    pub(super) fn run_security(args: &[&str]) -> io::Result<SecurityRun> {
        let mut child = Command::new("security")
            .args(args)
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()?;

        let stdout = child.stdout.take().expect("stdout piped");
        let stderr = child.stderr.take().expect("stderr piped");
        let stdout_handle = std::thread::spawn(move || drain(stdout));
        let stderr_handle = std::thread::spawn(move || drain(stderr));

        let deadline = Instant::now() + SECURITY_TIMEOUT;
        let status = loop {
            match child.try_wait()? {
                Some(status) => break status,
                None => {
                    if Instant::now() >= deadline {
                        let _ = child.kill();
                        // Bounded try_wait loop; never `wait()` which
                        // could block past budget if reap stalls.
                        let grace_deadline = Instant::now() + KILL_GRACE;
                        while Instant::now() < grace_deadline {
                            if let Ok(Some(_)) = child.try_wait() {
                                break;
                            }
                            std::thread::sleep(POLL_INTERVAL);
                        }
                        // Detach reader handles; they exit once the
                        // kernel eventually closes the pipes.
                        drop(stdout_handle);
                        drop(stderr_handle);
                        return Err(io::Error::new(
                            io::ErrorKind::TimedOut,
                            format!("security timed out after {}s", SECURITY_TIMEOUT.as_secs()),
                        ));
                    }
                    std::thread::sleep(POLL_INTERVAL);
                }
            }
        };

        // Propagate reader panics as io::Error rather than silently
        // dropping output — a panicked drain would otherwise look
        // like clean empty stdout/stderr and mask a real failure.
        let stdout = stdout_handle
            .join()
            .map_err(|_| io::Error::other("security stdout reader thread panicked"))?;
        let stderr = stderr_handle
            .join()
            .map_err(|_| io::Error::other("security stderr reader thread panicked"))?;
        Ok(SecurityRun {
            status,
            stdout,
            stderr,
        })
    }

    fn drain<R: Read>(mut reader: R) -> Vec<u8> {
        let mut buf = Vec::new();
        let _ = reader.read_to_end(&mut buf);
        buf
    }

    pub(super) fn classify_security_exit(run: &SecurityRun) -> SecurityResult {
        if run.status.success() {
            return SecurityResult::Success;
        }
        if run.status.code() == Some(ERR_SEC_ITEM_NOT_FOUND) {
            return SecurityResult::ItemNotFound;
        }
        let stderr = String::from_utf8_lossy(&run.stderr);
        let stderr = truncate_for_error(stderr.trim());
        let msg = match (run.status.code(), run.status.signal()) {
            (Some(code), _) if stderr.is_empty() => {
                format!("security exited with status {code}")
            }
            (Some(code), _) => format!("security exited with status {code}: {stderr}"),
            (None, Some(sig)) if stderr.is_empty() => {
                format!("security terminated by signal {sig}")
            }
            (None, Some(sig)) => format!("security terminated by signal {sig}: {stderr}"),
            (None, None) if stderr.is_empty() => String::from("security terminated abnormally"),
            (None, None) => format!("security terminated abnormally: {stderr}"),
        };
        SecurityResult::Failed(io::Error::other(msg))
    }

    /// Cap stderr content embedded in error messages. `dump-keychain`
    /// failures can emit multi-KB diagnostics; an unbounded stderr
    /// could balloon log payloads.
    fn truncate_for_error(s: &str) -> String {
        if s.len() <= MAX_STDERR_IN_ERROR {
            return s.to_string();
        }
        let mut end = MAX_STDERR_IN_ERROR;
        while end > 0 && !s.is_char_boundary(end) {
            end -= 1;
        }
        format!("{}... (truncated)", &s[..end])
    }

    struct Candidate {
        service: String,
        mdat: Option<String>,
    }

    /// Scan `security dump-keychain` output for generic-password
    /// entries whose `svce` begins with the Claude Code service prefix.
    /// Pulls optional `mdat` blobs for sort-by-modification-time.
    fn parse_dump_for_services(dump: &str) -> Vec<Candidate> {
        let mut out = Vec::new();
        let mut current_svce: Option<String> = None;
        let mut current_mdat: Option<String> = None;
        for line in dump.lines() {
            let line = line.trim();
            if line.starts_with("keychain:") {
                // New entry boundary. Emit the prior if it matches.
                if let Some(svce) = current_svce.take() {
                    if svce.starts_with(KEYCHAIN_SERVICE) {
                        out.push(Candidate {
                            service: svce,
                            mdat: current_mdat.take(),
                        });
                    } else {
                        current_mdat = None;
                    }
                }
                continue;
            }
            if let Some(val) = extract_quoted_after(line, "\"svce\"") {
                current_svce = Some(val);
            } else if let Some(val) = extract_quoted_after(line, "\"mdat\"") {
                current_mdat = Some(val);
            }
        }
        // Tail entry.
        if let Some(svce) = current_svce {
            if svce.starts_with(KEYCHAIN_SERVICE) {
                out.push(Candidate {
                    service: svce,
                    mdat: current_mdat,
                });
            }
        }
        out
    }

    /// Pull the first `"<content>"` occurrence on a line prefixed by
    /// `key`. Tolerates the `security` dump's `<blob>="<value>"` and
    /// `<blob>=0x...  "<value>"` forms.
    fn extract_quoted_after(line: &str, key: &str) -> Option<String> {
        let after_key = line.strip_prefix(key)?;
        let first_quote = after_key.find('"')?;
        let rest = &after_key[first_quote + 1..];
        let close_quote = rest.find('"')?;
        Some(rest[..close_quote].to_string())
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use std::os::unix::process::ExitStatusExt;

        fn run_with(raw_status: i32, stderr: &[u8]) -> SecurityRun {
            SecurityRun {
                status: ExitStatus::from_raw(raw_status),
                stdout: Vec::new(),
                stderr: stderr.to_vec(),
            }
        }

        #[test]
        fn classify_success_on_zero_exit() {
            // Raw status 0 = exit code 0 = success.
            let run = run_with(0, b"");
            assert!(matches!(
                classify_security_exit(&run),
                SecurityResult::Success
            ));
        }

        #[test]
        fn classify_item_not_found_on_exit_44() {
            // Unix wait status: exit code is in the high byte.
            let run = run_with(ERR_SEC_ITEM_NOT_FOUND << 8, b"");
            assert!(matches!(
                classify_security_exit(&run),
                SecurityResult::ItemNotFound,
            ));
        }

        #[test]
        fn classify_other_non_zero_exit_is_failed_with_stderr() {
            let run = run_with(25 << 8, b"keychain locked");
            let SecurityResult::Failed(e) = classify_security_exit(&run) else {
                panic!("expected Failed variant for non-zero exit with stderr");
            };
            let msg = e.to_string();
            // Anchor on the format-string contract, not loose substrings.
            assert!(msg.contains("status 25"), "msg={msg}");
            assert!(msg.contains(": keychain locked"), "msg={msg}");
        }

        #[test]
        fn classify_signal_termination_includes_signal_number() {
            // Raw wait status 9 = terminated by SIGKILL, no exit code.
            let run = run_with(9, b"");
            let SecurityResult::Failed(e) = classify_security_exit(&run) else {
                panic!("expected Failed variant for signal termination");
            };
            let msg = e.to_string();
            assert!(msg.contains("terminated by signal 9"), "msg={msg}",);
        }

        #[test]
        fn classify_signal_termination_includes_stderr() {
            // SIGSEGV = 11; pair with diagnostic stderr to match the
            // "terminated by signal N: <stderr>" format arm.
            let run = run_with(11, b"segfault diag");
            let SecurityResult::Failed(e) = classify_security_exit(&run) else {
                panic!("expected Failed variant");
            };
            let msg = e.to_string();
            assert!(msg.contains("terminated by signal 11"), "msg={msg}");
            assert!(msg.contains(": segfault diag"), "msg={msg}");
        }

        #[test]
        fn classify_failed_truncates_long_stderr() {
            let long_stderr = "x".repeat(MAX_STDERR_IN_ERROR * 2);
            let run = run_with(25 << 8, long_stderr.as_bytes());
            let SecurityResult::Failed(e) = classify_security_exit(&run) else {
                panic!("expected Failed variant");
            };
            let msg = e.to_string();
            assert!(msg.contains("(truncated)"), "msg={msg}");
            // Embedded stderr bytes capped at MAX_STDERR_IN_ERROR.
            assert!(
                msg.len() < long_stderr.len(),
                "expected truncation, got msg.len()={}",
                msg.len()
            );
        }

        #[test]
        fn parses_dump_with_single_matching_service() {
            let dump = r#"keychain: "/Users/alice/Library/Keychains/login.keychain-db"
    "svce"<blob>="Claude Code-credentials"
    "acct"<blob>="alice"
    "mdat"<timedate>=0x30303030  "20260418105500Z"
"#;
            let candidates = parse_dump_for_services(dump);
            assert_eq!(candidates.len(), 1);
            assert_eq!(candidates[0].service, "Claude Code-credentials");
            assert_eq!(candidates[0].mdat.as_deref(), Some("20260418105500Z"));
        }

        #[test]
        fn skips_non_matching_services() {
            let dump = r#"keychain: "/path/to/login.keychain"
    "svce"<blob>="some.other.app"
    "mdat"<timedate>=0x00 "20260101000000Z"
keychain: "/path/to/login.keychain"
    "svce"<blob>="Claude Code-credentials-acct2"
    "mdat"<timedate>=0x00 "20260420000000Z"
"#;
            let candidates = parse_dump_for_services(dump);
            assert_eq!(candidates.len(), 1);
            assert_eq!(candidates[0].service, "Claude Code-credentials-acct2");
        }
    }
}

#[cfg(test)]
mod tests;