clauth 0.4.0

Simple Claude Code account switcher and usage monitor
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
//! Per-profile persistent `CLAUDE_CONFIG_DIR` used by `clauth start`.
//!
//! All `clauth start <profile>` sessions for the same profile share a
//! runtime tree at `~/.clauth/profiles/<profile>/runtime/`. Its
//! `.credentials.json` mirrors the profile's canonical creds so concurrent
//! sessions observe a single chain of refresh tokens. A watchdog thread in
//! each parent process keeps the runtime tree and canonical state in sync.
//!
//! Two transport modes, picked per profile at acquire time:
//!
//! - **Real symlinks** (Unix, plus Windows with developer mode or admin):
//!   the runtime tree is a forest of symlinks into `~/.claude/`, and
//!   `.credentials.json` is a symlink into the profile's canonical creds.
//!   The watchdog only repairs the `.credentials.json` link when Claude
//!   Code's `unlink + write` re-login replaces it with a regular file.
//!
//! - **Fake symlinks** (Windows without symlink privilege): the runtime
//!   tree is built by recursive copy, and `.credentials.json` is a regular
//!   file. The watchdog walks both sides every tick and reconciles by
//!   "latest mtime wins" so a re-login on either side propagates to the
//!   other before another session can pick up a stale refresh token.
//!
//! Reference counting lives in a sibling `sessions/` directory: each
//! session creates `sessions/<pid>` and holds an exclusive `flock(2)` on it
//! for its lifetime. New sessions prune entries whose lock is free
//! (previous holder died) and tear the runtime tree down when no live
//! sessions remain.

use std::collections::HashSet;
use std::fs::{File, OpenOptions};
use std::mem::ManuallyDrop;
use std::path::{Path, PathBuf};
use std::sync::mpsc::{RecvTimeoutError, Sender, channel};
use std::thread::{self, JoinHandle};
use std::time::{Duration, SystemTime};

use anyhow::{Context, Result};

use crate::claude::{build_claude_settings_json, create_symlink};
use crate::lock::with_state_lock;
use crate::profile::{ClaudeCredentials, Profile, atomic_write, home_dir, profile_dir};

/// Watchdog tick. 1s instead of a longer interval because fake-symlink mode
/// needs a tight upper bound on how long a session can read stale credentials
/// after a sibling refreshes — every additional second is another window in
/// which a 401 could revoke an already-rotated refresh token chain.
const WATCHDOG_INTERVAL: Duration = Duration::from_secs(1);

/// `.claude.json` cross-profile sync cadence. Tighter than the credential
/// watchdog because Claude Code rewrites `.claude.json` constantly; 100ms keeps
/// the window in which one profile observes another's stale shared state small.
/// Also bounds watchdog-thread shutdown latency to one tick of this interval.
const CJSON_INTERVAL: Duration = Duration::from_millis(100);

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LinkMode {
    /// OS-level symlinks. Used on Unix unconditionally and on Windows when
    /// the process can create symlinks (developer mode or admin).
    Real,
    /// Bidirectional mtime-based mirror. Used on Windows when the OS denies
    /// symlink creation.
    Fake,
}

fn runtime_dir(name: &str) -> Result<PathBuf> {
    Ok(profile_dir(name)?.join("runtime"))
}

fn sessions_dir(name: &str) -> Result<PathBuf> {
    Ok(profile_dir(name)?.join("sessions"))
}

/// True iff the profile currently has at least one live `clauth start` session.
///
/// Reads the sessions dir and tests each entry with `is_session_alive`. A
/// missing or unreadable sessions dir returns false — the profile is idle.
pub(crate) fn has_live_session(name: &str) -> bool {
    let Ok(dir) = sessions_dir(name) else {
        return false;
    };
    let Ok(entries) = std::fs::read_dir(&dir) else {
        return false;
    };
    entries.flatten().any(|e| is_session_alive(&e.path()))
}

fn canonical_credentials(name: &str) -> Result<PathBuf> {
    Ok(profile_dir(name)?.join("credentials.json"))
}

/// Open or create a PID file without truncating — used for session liveness
/// tracking via flock. `O_CREAT` without truncate preserves any existing lock
/// held by a sibling that raced us to create the file.
pub(crate) fn open_pid_file(path: &Path) -> std::io::Result<File> {
    OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(path)
}

/// Live-session guard. On drop: stops the watchdog, runs a final sync
/// (errors surface to stderr), drops the PID file, and tears the runtime
/// down when this was the last session for the profile.
pub(crate) struct ProfileRuntime {
    runtime: PathBuf,
    pid_file: PathBuf,
    claude_home: PathBuf,
    canonical: PathBuf,
    sessions: PathBuf,
    mode: LinkMode,
    /// Held for the lifetime of the session so a sibling process's
    /// `try_lock` reveals we're still alive.
    _pid_lock: File,
    /// Wrapped in ManuallyDrop so Drop can explicitly drop it before joining
    /// the watchdog, signalling the thread to exit.
    watchdog_signal: ManuallyDrop<Sender<()>>,
    watchdog_handle: Option<JoinHandle<()>>,
}

impl ProfileRuntime {
    pub(crate) fn acquire(profile: &Profile) -> Result<Self> {
        let name = &profile.name;
        let claude_home = home_dir()?.join(".claude");
        if !claude_home.exists() {
            anyhow::bail!("~/.claude not found; install Claude Code first");
        }
        let runtime = runtime_dir(name)?;
        let sessions = sessions_dir(name)?;
        let pid_file = sessions.join(std::process::id().to_string());
        let canonical = canonical_credentials(name)?;

        let (pid_lock, mode) = with_state_lock(|| {
            std::fs::create_dir_all(&sessions)
                .with_context(|| format!("failed to create {}", sessions.display()))?;
            let active = prune_stale_sessions(&sessions)?;
            // No live siblings — rebuild the tree from scratch so stale
            // symlinks/copies to entries that have since vanished from
            // ~/.claude/ don't carry over.
            if active == 0 && runtime.symlink_metadata().is_ok() {
                std::fs::remove_dir_all(&runtime)
                    .with_context(|| format!("failed to clear {}", runtime.display()))?;
            }
            std::fs::create_dir_all(&runtime)
                .with_context(|| format!("failed to create {}", runtime.display()))?;
            let mode = detect_link_mode(&runtime)?;
            build_runtime_dir(&runtime, &claude_home, profile, &canonical, mode)?;
            let file = open_pid_file(&pid_file)
                .with_context(|| format!("failed to open {}", pid_file.display()))?;
            file.lock()
                .with_context(|| format!("failed to lock {}", pid_file.display()))?;
            Ok::<_, anyhow::Error>((file, mode))
        })?;

        let (tx, rx) = channel::<()>();
        let watchdog_runtime = runtime.clone();
        let watchdog_canonical = canonical.clone();
        let watchdog_claude_home = claude_home.clone();
        let watchdog_handle = thread::spawn(move || {
            // One thread, two cadences: `.claude.json` reconciles every
            // CJSON_INTERVAL; credentials reconcile every ~WATCHDOG_INTERVAL,
            // counted in cjson ticks. Loop exits on Disconnected (sender dropped
            // in Drop) or Ok(()).
            let cred_every = (WATCHDOG_INTERVAL.as_millis() / CJSON_INTERVAL.as_millis()).max(1);
            let mut until_cred = cred_every;
            while let Err(RecvTimeoutError::Timeout) = rx.recv_timeout(CJSON_INTERVAL) {
                if let Err(e) = crate::claude_json::sync_once() {
                    eprintln!("clauth: .claude.json sync failed: {e}");
                }
                until_cred -= 1;
                if until_cred == 0 {
                    until_cred = cred_every;
                    if let Err(e) = tick(
                        mode,
                        &watchdog_runtime,
                        &watchdog_claude_home,
                        &watchdog_canonical,
                    ) {
                        eprintln!("clauth: watchdog tick failed: {e}");
                    }
                }
            }
        });

        Ok(Self {
            runtime,
            pid_file,
            claude_home,
            canonical,
            sessions,
            mode,
            _pid_lock: pid_lock,
            watchdog_signal: ManuallyDrop::new(tx),
            watchdog_handle: Some(watchdog_handle),
        })
    }

    pub(crate) fn config_dir(&self) -> &Path {
        &self.runtime
    }
}

impl Drop for ProfileRuntime {
    fn drop(&mut self) {
        // Drop the sender first to signal the watchdog, then join.
        // SAFETY: field is never used after this point.
        unsafe { ManuallyDrop::drop(&mut self.watchdog_signal) };
        if let Some(h) = self.watchdog_handle.take() {
            let _ = h.join();
        }

        if let Err(e) = tick(self.mode, &self.runtime, &self.claude_home, &self.canonical) {
            eprintln!("clauth: final sync failed: {e}");
        }

        // Flush this session's last `.claude.json` changes to the global file
        // and siblings before a possible teardown removes this runtime copy.
        if let Err(e) = crate::claude_json::sync_once() {
            eprintln!("clauth: final .claude.json sync failed: {e}");
        }

        if let Err(e) = with_state_lock(|| {
            if let Err(e) = std::fs::remove_file(&self.pid_file)
                && e.kind() != std::io::ErrorKind::NotFound
            {
                eprintln!("clauth: remove pid file failed: {e}");
            }
            let still_active = prune_stale_sessions(&self.sessions).unwrap_or(1);
            if still_active == 0 {
                let _ = std::fs::remove_dir_all(&self.runtime);
                let _ = std::fs::remove_dir(&self.sessions);
            }
            Ok::<_, anyhow::Error>(())
        }) {
            eprintln!("clauth: drop cleanup failed: {e}");
        }
    }
}

/// Probe the OS by attempting a real symlink in the runtime root. Anything
/// other than success — privilege denial, unsupported filesystem, the
/// `cfg(not(any(unix, windows)))` fallback — drops to fake-symlink mode.
fn detect_link_mode(runtime: &Path) -> Result<LinkMode> {
    let probe_target = runtime.join(".clauth-probe-target");
    let probe_link = runtime.join(".clauth-probe-link");
    let _ = std::fs::remove_file(&probe_target);
    let _ = std::fs::remove_file(&probe_link);
    std::fs::write(&probe_target, b"")
        .with_context(|| format!("failed to write {}", probe_target.display()))?;
    let mode = match try_real_symlink(&probe_target, &probe_link) {
        Ok(()) => LinkMode::Real,
        Err(_) => LinkMode::Fake,
    };
    let _ = std::fs::remove_file(&probe_link);
    let _ = std::fs::remove_file(&probe_target);
    Ok(mode)
}

#[cfg(unix)]
fn try_real_symlink(target: &Path, link: &Path) -> std::io::Result<()> {
    std::os::unix::fs::symlink(target, link)
}

#[cfg(windows)]
fn try_real_symlink(target: &Path, link: &Path) -> std::io::Result<()> {
    std::os::windows::fs::symlink_file(target, link)
}

#[cfg(not(any(unix, windows)))]
fn try_real_symlink(_target: &Path, _link: &Path) -> std::io::Result<()> {
    Err(std::io::Error::new(
        std::io::ErrorKind::Unsupported,
        "no symlink support",
    ))
}

/// Walk `sessions/`, drop entries whose owner has died, return the live
/// count. Caller holds the cross-process state lock so two simultaneous
/// starts can't both conclude "no other sessions" and tear down the
/// runtime under each other.
fn prune_stale_sessions(sessions: &Path) -> Result<usize> {
    let entries = match std::fs::read_dir(sessions) {
        Ok(e) => e,
        Err(_) => return Ok(0),
    };
    let mut alive = 0;
    for entry in entries.flatten() {
        let path = entry.path();
        if is_session_alive(&path) {
            alive += 1;
        } else {
            let _ = std::fs::remove_file(&path);
        }
    }
    Ok(alive)
}

fn is_session_alive(pid_file: &Path) -> bool {
    // Open without O_CREAT: creating the file would race with another session
    // that just created it but hasn't locked it yet, producing a false
    // "unlocked = dead" reading. try_lock succeeds iff no other open fd holds
    // an exclusive flock, i.e. the previous owner has exited.
    let Ok(file) = OpenOptions::new().read(true).write(true).open(pid_file) else {
        return false;
    };
    // Any I/O error: treat as alive so we don't race a live session.
    file.try_lock().is_err()
}

/// Build or incrementally update the runtime tree.
///
/// Called on every `acquire`, including when `active > 0` (live siblings
/// already built the tree). The walk always runs; entries whose runtime
/// counterpart already exists are skipped, so new `~/.claude/` additions
/// after the first session's build are picked up without disturbing the rest.
///
/// Shared vs. per-profile layout:
/// - **Shared via symlink/copy across all profiles:** every top-level entry
///   in `~/.claude/` except `settings.json` and `.credentials.json` —
///   this includes `projects/`, `todos/`, `statsig/`, `sessions/`, `cache/`,
///   `commands/`, `plugins/`, `tasks/`, `teams/`, `hooks/`, `history.jsonl`,
///   and similar. Claude Code treats these as user-global state so sharing is
///   intentional; per-profile isolation would hide project history and
///   installed commands.
/// - **Per-profile:** `settings.json` (merged with profile overrides),
///   `.credentials.json` (the profile's own OAuth token chain), and
///   `.claude.json` (a copy seeded from `~/.claude.json`). Settings are
///   rewritten when changed; credentials are reconciled without using the
///   shared `~/.claude/.credentials.json` copy; `.claude.json` is reconciled
///   across all profiles by `crate::claude_json`, which propagates every field
///   except the account-specific ones (`oauthAccount` + billing caches).
fn build_runtime_dir(
    runtime: &Path,
    claude_home: &Path,
    profile: &Profile,
    canonical: &Path,
    mode: LinkMode,
) -> Result<()> {
    // Re-walk on every acquire so entries added to ~/.claude/ after the
    // first session's build are picked up. Existing entries stay as-is.
    let mut pending: Vec<(PathBuf, PathBuf)> = Vec::new();
    for entry in std::fs::read_dir(claude_home)
        .with_context(|| format!("failed to read {}", claude_home.display()))?
    {
        let entry = entry?;
        let file_name = entry.file_name();
        if file_name == "settings.json" || file_name == ".credentials.json" {
            continue;
        }
        let dst = runtime.join(&file_name);
        if dst.symlink_metadata().is_ok() {
            continue;
        }
        pending.push((entry.path(), dst));
    }
    materialize_entries(pending, mode)?;

    let settings_src = claude_home.join("settings.json");
    let merged = build_claude_settings_json(&settings_src, profile, &[])?;
    let settings_dst = runtime.join("settings.json");
    // Only write when absent or content differs — concurrent sessions on the
    // same profile each compute the same merge, so a byte-identical result
    // doesn't need to win a last-writer race and stomp a sibling's write.
    let needs_write = std::fs::read(&settings_dst)
        .map(|existing| existing != merged.as_bytes())
        .unwrap_or(true);
    if needs_write {
        atomic_write(&settings_dst, merged).context("failed to write runtime settings.json")?;
    }

    let creds_link = runtime.join(".credentials.json");
    reconcile_credentials(&creds_link, canonical, mode)?;

    // Per-profile copy of `~/.claude.json`. Claude Code's big config file
    // embeds an account-specific `oauthAccount` block (plus billing caches)
    // that must NOT be shared across profiles — CC trusts the cached identity
    // and won't re-derive it from the token on a normal startup, so a shared
    // symlink leaks one account's identity into another. The background syncer
    // (`crate::claude_json`) keeps the non-per-profile fields converged across
    // all copies (latest write wins). A freshly seeded copy inherits the global
    // file's `oauthAccount`; that profile's next OAuth login overwrites it with
    // the correct identity, which the syncer then preserves.
    if let Some(home) = claude_home.parent() {
        let global = home.join(".claude.json");
        let dst = runtime.join(".claude.json");
        // Seed from the global file when this profile has no real copy yet, or
        // migrate the old shared symlink (pre-per-profile behavior) to a copy.
        // `atomic_write` renames over the path, replacing a symlink in one step
        // — no window where a sibling session sees the file missing. Existing
        // real copies keep their own identity and synced shared fields.
        let is_symlink = dst
            .symlink_metadata()
            .is_ok_and(|m| m.file_type().is_symlink());
        if (is_symlink || !dst.exists())
            && let Ok(bytes) = std::fs::read(&global)
        {
            atomic_write(&dst, &bytes)
                .with_context(|| format!("failed to seed {}", dst.display()))?;
        }
    }

    Ok(())
}

fn materialize_entry(src: &Path, dst: &Path, mode: LinkMode) -> Result<()> {
    match mode {
        LinkMode::Real => link_entry(src, dst),
        LinkMode::Fake => copy_tree(src, dst),
    }
}

/// Materialize the pending top-level entries into the runtime tree.
///
/// Real mode creates symlinks (near-free) serially. Fake mode is a recursive
/// byte copy, so the independent top-level subtrees are fanned across a
/// bounded worker pool to cut acquire wall-time on a large `~/.claude/`. This
/// stays inside the single `with_state_lock` hold the caller already owns —
/// the lock is never released; threads only parallelize the copy. Each
/// subtree is disjoint, so the per-entry contract (no shared dst) is intact;
/// credential reconciliation still runs serially after this returns.
fn materialize_entries(pending: Vec<(PathBuf, PathBuf)>, mode: LinkMode) -> Result<()> {
    if mode == LinkMode::Real || pending.len() < 2 {
        for (src, dst) in &pending {
            materialize_entry(src, dst, mode)?;
        }
        return Ok(());
    }

    let workers = std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(1)
        .min(pending.len());
    if workers < 2 {
        for (src, dst) in &pending {
            materialize_entry(src, dst, mode)?;
        }
        return Ok(());
    }

    let next = std::sync::atomic::AtomicUsize::new(0);
    let first_err = std::sync::Mutex::new(None::<anyhow::Error>);
    std::thread::scope(|scope| {
        for _ in 0..workers {
            scope.spawn(|| {
                loop {
                    let idx = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                    let Some((src, dst)) = pending.get(idx) else {
                        break;
                    };
                    if let Err(e) = materialize_entry(src, dst, mode) {
                        let mut slot = first_err.lock().unwrap_or_else(|p| p.into_inner());
                        if slot.is_none() {
                            *slot = Some(e);
                        }
                        break;
                    }
                }
            });
        }
    });

    match first_err.into_inner().unwrap_or_else(|p| p.into_inner()) {
        Some(e) => Err(e),
        None => Ok(()),
    }
}

fn reconcile_credentials(runtime_path: &Path, canonical: &Path, mode: LinkMode) -> Result<()> {
    match mode {
        LinkMode::Real => {
            sync_credentials_unlocked(runtime_path, canonical)?;
            let meta = runtime_path.symlink_metadata().ok();
            if meta.as_ref().is_some_and(|m| m.file_type().is_symlink())
                || meta.as_ref().is_some_and(|m| m.is_file())
            {
                return Ok(());
            }
            if canonical.exists() {
                create_symlink(canonical, runtime_path)?;
            }
        }
        LinkMode::Fake => {
            mirror_credentials(runtime_path, canonical)?;
        }
    }
    Ok(())
}

/// Recursive `std::fs::copy`. Directories are created at the destination
/// and walked; files are copied byte-for-byte. Used in fake-symlink mode
/// when the OS won't grant the process symlink creation rights.
fn copy_tree(src: &Path, dst: &Path) -> Result<()> {
    let meta = src
        .symlink_metadata()
        .with_context(|| format!("failed to stat {}", src.display()))?;
    if meta.file_type().is_dir() {
        std::fs::create_dir_all(dst)
            .with_context(|| format!("failed to create {}", dst.display()))?;
        for entry in
            std::fs::read_dir(src).with_context(|| format!("failed to read {}", src.display()))?
        {
            let entry = entry?;
            copy_tree(&entry.path(), &dst.join(entry.file_name()))?;
        }
        Ok(())
    } else {
        std::fs::copy(src, dst)
            .map(|_| ())
            .with_context(|| format!("failed to copy {} -> {}", src.display(), dst.display()))
    }
}

/// One watchdog iteration. Real mode only repairs `.credentials.json`
/// (the rest of the runtime is symlinks that need no maintenance). Fake
/// mode reconciles every tree file by mtime and the credentials file too.
fn tick(mode: LinkMode, runtime: &Path, claude_home: &Path, canonical: &Path) -> Result<()> {
    match mode {
        LinkMode::Real => {
            let _ = sync_credentials(runtime, canonical)?;
            Ok(())
        }
        LinkMode::Fake => {
            // The bulk tree walk + copies run WITHOUT the state lock. On a
            // large ~/.claude/ tree holding the lock across the whole walk
            // stalled every concurrent acquire / CLI switch for hundreds of ms
            // each tick. The walk is safe to run lockless: every per-file merge
            // is independent, self-converging under "latest mtime wins" + the
            // byte-equality skip, and never deletes — so a file changing in the
            // TOCTOU window between snapshot and copy just re-converges on the
            // next 1s tick. settings.json / .credentials.json are skipped by
            // mirror_tree, so it never races build_runtime_dir's per-profile
            // writes. Only credential reconciliation, which must not interleave
            // with acquire / switch credential writes, stays under the lock.
            mirror_tree(claude_home, runtime)?;
            with_state_lock(|| mirror_credentials(&runtime.join(".credentials.json"), canonical))
        }
    }
}

/// If Claude Code's internal refresh has replaced `<runtime>/.credentials.json`
/// with a regular file, copy its bytes into the profile's canonical creds
/// and swap the file back to a symlink so canonical stays the single source
/// of truth. Returns `true` when bytes were actually written. Real-symlink
/// mode only — fake-symlink mode uses [`mirror_credentials`].
pub(crate) fn sync_credentials(runtime: &Path, canonical: &Path) -> Result<bool> {
    let link_path = runtime.join(".credentials.json");
    with_state_lock(|| sync_credentials_unlocked(&link_path, canonical))
}

fn sync_credentials_unlocked(link_path: &Path, canonical: &Path) -> Result<bool> {
    let Ok(meta) = link_path.symlink_metadata() else {
        return Ok(false);
    };
    if meta.file_type().is_symlink() {
        return Ok(false);
    }
    let runtime_bytes = std::fs::read(link_path).context("failed to read live credentials")?;
    // Skip if CC's write is mid-flight (partial, invalid, or empty object).
    // {} deserializes as ClaudeCredentials { claude_ai_oauth: None } because
    // the field is Option — require Some to confirm a completed write.
    let Ok(runtime_creds) = serde_json::from_slice::<ClaudeCredentials>(&runtime_bytes) else {
        return Ok(false);
    };
    if runtime_creds.claude_ai_oauth.is_none() {
        return Ok(false);
    }
    let canonical_bytes = std::fs::read(canonical).ok();
    let differs = canonical_bytes.as_deref() != Some(runtime_bytes.as_slice());
    let mut wrote_canonical = false;
    if differs {
        // Bytes differ: the TUI may have rotated canonical while CC wrote a
        // fresh login into the runtime regular file. Use expires_at as the
        // tie-breaker so the newer token wins. Canonical wins on tie or when
        // it can't be parsed (missing canonical → runtime wins by default).
        let canonical_exp = canonical_bytes.as_deref().and_then(|cb| {
            let c = serde_json::from_slice::<ClaudeCredentials>(cb).ok()?;
            Some(c.claude_ai_oauth?.expires_at.unwrap_or(0))
        });
        let runtime_exp = runtime_creds
            .claude_ai_oauth
            .as_ref()
            .map(|o| o.expires_at.unwrap_or(0));
        let canonical_wins = match (canonical_exp, runtime_exp) {
            (Some(ce), Some(re)) => ce >= re,
            (Some(_), None) => true,
            _ => false,
        };
        if canonical_wins {
            // TUI rotation wrote a fresher token into canonical; do not
            // overwrite it with the stale runtime bytes.
            eprintln!(
                "clauth: watchdog kept canonical credentials \
                 (canonical expires_at >= runtime); not overwriting with runtime re-login bytes"
            );
        } else {
            atomic_write(canonical, &runtime_bytes)?;
            wrote_canonical = true;
        }
    }
    if canonical.exists() {
        let tmp = link_path.with_file_name(format!(".credentials.json.tmp.{}", std::process::id()));
        let _ = std::fs::remove_file(&tmp);
        create_symlink(canonical, &tmp)?;
        std::fs::rename(&tmp, link_path)?;
    } else {
        std::fs::remove_file(link_path)?;
    }
    Ok(wrote_canonical)
}

/// Bidirectional mtime-based mirror between `runtime/.credentials.json` and
/// the profile's canonical creds. "Latest mtime wins": the newer side is
/// copied over the older. Skips partial writes (invalid JSON). Used in
/// fake-symlink mode only.
fn mirror_credentials(runtime_path: &Path, canonical: &Path) -> Result<()> {
    let runtime_meta = runtime_path.metadata().ok();
    let canonical_meta = canonical.metadata().ok();

    match (runtime_meta, canonical_meta) {
        (Some(rm), Some(cm)) => {
            let rt_time = rm.modified().ok();
            let ca_time = cm.modified().ok();
            match (rt_time, ca_time) {
                (Some(rt), Some(ca)) if rt > ca => {
                    copy_if_valid_creds(runtime_path, canonical)?;
                }
                (Some(rt), Some(ca)) if ca > rt => {
                    copy_if_valid_creds(canonical, runtime_path)?;
                }
                _ => {}
            }
        }
        (Some(_), None) => {
            copy_if_valid_creds(runtime_path, canonical)?;
        }
        (None, Some(_)) => {
            copy_if_valid_creds(canonical, runtime_path)?;
        }
        (None, None) => {}
    }
    Ok(())
}

fn copy_if_valid_creds(src: &Path, dst: &Path) -> Result<()> {
    let bytes = std::fs::read(src).with_context(|| format!("failed to read {}", src.display()))?;
    // Same guard as sync_credentials_unlocked: reject partial, invalid, or
    // empty-object writes before letting them stomp the canonical file.
    let Ok(creds) = serde_json::from_slice::<ClaudeCredentials>(&bytes) else {
        return Ok(());
    };
    if creds.claude_ai_oauth.is_none() {
        return Ok(());
    }
    if std::fs::read(dst).ok().as_deref() == Some(bytes.as_slice()) {
        return Ok(());
    }
    atomic_write(dst, &bytes).with_context(|| format!("failed to write {}", dst.display()))
}

/// Walk both `~/.claude/` and the runtime tree; for any file present on
/// one or both sides, copy the newer bytes onto the older. Files that exist
/// on only one side are seeded onto the other — Claude Code may create
/// state under the runtime tree (new project history, scratch files) and
/// the user may add entries under `~/.claude/` between ticks, both of
/// which must propagate. **No deletion**: a file missing from one side is
/// treated as "not yet seen", never as "intentionally removed", so a
/// content-only mirror never destroys data. Top-level `settings.json` and
/// `.credentials.json` are skipped — settings is intentionally a rewritten
/// copy and credentials has its own mirror with stricter validation.
/// Used in fake-symlink mode only.
fn mirror_tree(claude_home: &Path, runtime: &Path) -> Result<()> {
    // `.claude.json` is a per-profile copy reconciled by `crate::claude_json`,
    // not part of the `~/.claude/` tree — skip it here so the tree mirror never
    // copies it into `~/.claude/.claude.json`.
    let skip_top: HashSet<&str> = ["settings.json", ".credentials.json", ".claude.json"]
        .into_iter()
        .collect();
    for name in union_children(claude_home, runtime) {
        if name.to_str().is_some_and(|n| skip_top.contains(n)) {
            continue;
        }
        merge_path(&claude_home.join(&name), &runtime.join(&name))?;
    }
    Ok(())
}

/// Unioned child-name set of two directories. Either side absent or
/// unreadable contributes an empty set. Returned names are sorted for
/// deterministic test output and stable iteration order.
fn union_children(a: &Path, b: &Path) -> Vec<std::ffi::OsString> {
    let mut names: HashSet<std::ffi::OsString> = HashSet::new();
    for dir in [a, b] {
        if let Ok(entries) = std::fs::read_dir(dir) {
            for entry in entries.flatten() {
                names.insert(entry.file_name());
            }
        }
    }
    let mut out: Vec<_> = names.into_iter().collect();
    out.sort();
    out
}

/// Reconcile one path between canonical (`a`) and runtime (`b`) sides.
/// Directories recurse via the same union-walk; files merge by mtime.
fn merge_path(a: &Path, b: &Path) -> Result<()> {
    let a_meta = a.symlink_metadata().ok();
    let b_meta = b.symlink_metadata().ok();

    let a_is_dir = a_meta.as_ref().is_some_and(|m| m.file_type().is_dir());
    let b_is_dir = b_meta.as_ref().is_some_and(|m| m.file_type().is_dir());

    if a_is_dir || b_is_dir {
        if a_is_dir && !b.exists() {
            std::fs::create_dir_all(b)
                .with_context(|| format!("failed to create {}", b.display()))?;
        }
        if b_is_dir && !a.exists() {
            std::fs::create_dir_all(a)
                .with_context(|| format!("failed to create {}", a.display()))?;
        }
        for name in union_children(a, b) {
            merge_path(&a.join(&name), &b.join(&name))?;
        }
        return Ok(());
    }

    match (a_meta, b_meta) {
        (Some(am), Some(bm)) => {
            let a_time = am.modified().ok();
            let b_time = bm.modified().ok();
            if files_match(a, b)? {
                return Ok(());
            }
            if mtime_newer(a_time, b_time) {
                copy_file(a, b)?;
            } else if mtime_newer(b_time, a_time) {
                copy_file(b, a)?;
            }
        }
        (Some(_), None) => {
            copy_file(a, b)?;
        }
        (None, Some(_)) => {
            copy_file(b, a)?;
        }
        (None, None) => {}
    }
    Ok(())
}

fn mtime_newer(a: Option<SystemTime>, b: Option<SystemTime>) -> bool {
    match (a, b) {
        (Some(a), Some(b)) => a > b,
        (Some(_), None) => true,
        _ => false,
    }
}

fn files_match(a: &Path, b: &Path) -> Result<bool> {
    let a_bytes = std::fs::read(a).with_context(|| format!("failed to read {}", a.display()))?;
    let b_bytes = std::fs::read(b).with_context(|| format!("failed to read {}", b.display()))?;
    Ok(a_bytes == b_bytes)
}

/// Copy `src` onto `dst` via a PID-suffixed tmp + atomic rename. `mirror_tree`
/// now runs lockless, so a concurrent reader (a sibling session, the user, or
/// `build_runtime_dir`) could observe `dst` mid-write. A raw `std::fs::copy`
/// truncates then streams bytes — not atomic — so it could be seen torn. The
/// rename makes the swap atomic on POSIX: any observer sees either the old or
/// the complete new file. The PID suffix keeps two processes from colliding on
/// the same tmp name.
fn copy_file(src: &Path, dst: &Path) -> Result<()> {
    let bytes = std::fs::read(src).with_context(|| format!("failed to read {}", src.display()))?;
    atomic_write(dst, &bytes)
        .with_context(|| format!("failed to copy {} -> {}", src.display(), dst.display()))
}

#[cfg(unix)]
fn link_entry(src: &Path, dst: &Path) -> Result<()> {
    std::os::unix::fs::symlink(src, dst)
        .with_context(|| format!("failed to symlink {} -> {}", dst.display(), src.display()))
}

#[cfg(windows)]
fn link_entry(src: &Path, dst: &Path) -> Result<()> {
    let result = if src.is_dir() {
        std::os::windows::fs::symlink_dir(src, dst)
    } else {
        std::os::windows::fs::symlink_file(src, dst)
    };
    result.with_context(|| {
        format!(
            "failed to symlink {} -> {} (enable developer mode or run as admin)",
            dst.display(),
            src.display()
        )
    })
}

#[cfg(not(any(unix, windows)))]
fn link_entry(_src: &Path, _dst: &Path) -> Result<()> {
    anyhow::bail!("clauth start requires symlink support");
}

#[cfg(test)]
#[path = "../tests/inline/runtime.rs"]
mod tests;