llmswap-cli 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. claude_swap/__init__.py +24 -0
  2. claude_swap/__main__.py +6 -0
  3. claude_swap/app_bundle.py +330 -0
  4. claude_swap/appearance.py +219 -0
  5. claude_swap/autoswitch.py +3065 -0
  6. claude_swap/cache.py +44 -0
  7. claude_swap/claude_locks.py +279 -0
  8. claude_swap/cli.py +2265 -0
  9. claude_swap/credentials.py +2156 -0
  10. claude_swap/exceptions.py +102 -0
  11. claude_swap/fsutil.py +409 -0
  12. claude_swap/json_output.py +455 -0
  13. claude_swap/launch_agent.py +862 -0
  14. claude_swap/lines.py +153 -0
  15. claude_swap/list_view.py +371 -0
  16. claude_swap/locking.py +87 -0
  17. claude_swap/logging_config.py +64 -0
  18. claude_swap/macos_keychain.py +240 -0
  19. claude_swap/mappings.py +127 -0
  20. claude_swap/menubar.py +1433 -0
  21. claude_swap/migrations.py +360 -0
  22. claude_swap/models.py +329 -0
  23. claude_swap/oauth.py +1628 -0
  24. claude_swap/pace.py +161 -0
  25. claude_swap/paths.py +250 -0
  26. claude_swap/poll_policy.py +337 -0
  27. claude_swap/printer.py +252 -0
  28. claude_swap/process_detection.py +370 -0
  29. claude_swap/session.py +2696 -0
  30. claude_swap/settings.py +827 -0
  31. claude_swap/signin.py +238 -0
  32. claude_swap/snapshot_source.py +121 -0
  33. claude_swap/spawn.py +135 -0
  34. claude_swap/subscription.py +349 -0
  35. claude_swap/switcher.py +9807 -0
  36. claude_swap/transfer.py +807 -0
  37. claude_swap/tui/__init__.py +43 -0
  38. claude_swap/tui/app.py +482 -0
  39. claude_swap/tui/autoview.py +381 -0
  40. claude_swap/tui/cswap.tcss +205 -0
  41. claude_swap/tui/dashboard.py +434 -0
  42. claude_swap/tui/data.py +194 -0
  43. claude_swap/tui/modals.py +159 -0
  44. claude_swap/tui/theme.py +88 -0
  45. claude_swap/tui/widgets.py +544 -0
  46. claude_swap/update_check.py +509 -0
  47. claude_swap/usage_bars.py +208 -0
  48. claude_swap/usage_rows.py +160 -0
  49. claude_swap/usage_store.py +1429 -0
  50. llmswap/AGENTS.md +11 -0
  51. llmswap/__init__.py +3 -0
  52. llmswap/__main__.py +4 -0
  53. llmswap/cli.py +535 -0
  54. llmswap/config.py +101 -0
  55. llmswap/httpjson.py +50 -0
  56. llmswap/jwt.py +20 -0
  57. llmswap/menubar.py +218 -0
  58. llmswap/model.py +172 -0
  59. llmswap/paths.py +41 -0
  60. llmswap/providers/AGENTS.md +12 -0
  61. llmswap/providers/base.py +619 -0
  62. llmswap/providers/claude.py +187 -0
  63. llmswap/providers/codex.py +274 -0
  64. llmswap/providers/gemini.py +80 -0
  65. llmswap/providers/registry.py +30 -0
  66. llmswap/render.py +127 -0
  67. llmswap/rotate.py +102 -0
  68. llmswap/store.py +138 -0
  69. llmswap/tui.py +182 -0
  70. llmswap/usage_cache.py +72 -0
  71. llmswap/warm/plan.py +118 -0
  72. llmswap/warm/runner.py +175 -0
  73. llmswap/warm/schedule.py +264 -0
  74. llmswap_cli-1.0.0.dist-info/METADATA +181 -0
  75. llmswap_cli-1.0.0.dist-info/RECORD +78 -0
  76. llmswap_cli-1.0.0.dist-info/WHEEL +4 -0
  77. llmswap_cli-1.0.0.dist-info/entry_points.txt +5 -0
  78. llmswap_cli-1.0.0.dist-info/licenses/LICENSE +22 -0
claude_swap/session.py ADDED
@@ -0,0 +1,2696 @@
1
+ """Session mode: run Claude Code as a stored account in one terminal.
2
+
3
+ ``cswap run NUM|EMAIL`` launches Claude Code with ``CLAUDE_CONFIG_DIR``
4
+ pointing at a persistent per-account profile under
5
+ ``<backup_dir>/sessions/<num>-<email-slug>/``, leaving the default
6
+ ``~/.claude/`` login (and every other terminal, plus the VS Code extension)
7
+ untouched. ``CLAUDE_CONFIG_DIR`` isolates Claude Code's config and, with
8
+ ``CLAUDE_SECURESTORAGE_CONFIG_DIR`` kept out of the session's environment
9
+ (see ``CREDENTIAL_STORE_ENV_VAR``), its credential lookup. On macOS, Claude
10
+ hashes the (NFC-normalized) env var value into its keychain service name, so
11
+ each profile gets its own keychain entry.
12
+
13
+ Profiles are seeded with a plaintext ``.credentials.json`` — deliberate,
14
+ including on macOS: the plaintext fallback is Claude's only credential
15
+ mechanism on Linux (a stable contract), and Claude migrates it into its
16
+ hashed keychain entry on first write. Writing that keychain entry ourselves
17
+ would couple us to Claude's internal storage format and naming, where a
18
+ mismatch is a hard "logged out" failure instead of a harmless stale entry.
19
+
20
+ Sharing: by default the user's ``settings.json``, ``keybindings.json``,
21
+ ``CLAUDE.md``, ``skills/``, ``commands/``, ``agents/``, and ``rules/`` follow
22
+ them into the session profile as links — Claude's settings writer detects
23
+ a symlink and writes through to the target, so in-session ``/config``
24
+ changes land in ``~/.claude``. On macOS and Linux every item is a symlink.
25
+ On Windows a directory is a junction, which any user may create, and a
26
+ file is a symlink when the process may create one (Developer Mode, or an
27
+ elevated terminal) and otherwise a copy re-synced on every launch, as
28
+ before. A manifest records what cswap created so removal never touches
29
+ user data.
30
+
31
+ History sharing (on by default; ``--no-share-history`` or ``run.shareHistory
32
+ false`` turns it off): additionally links ``projects/`` (conversation
33
+ transcripts — what ``claude --resume`` lists) and ``history.jsonl`` (prompt
34
+ history) from ``~/.claude``, so all accounts see one unified conversation
35
+ history. By link only, never by copy, which would fork history rather than
36
+ share it: on Windows without a symlink privilege ``projects/`` is still
37
+ shared (a junction) and ``history.jsonl`` stays the account's own, which
38
+ the launch says once. If the profile already accumulated its own history,
39
+ it is merged into ``~/.claude`` first so nothing disappears from
40
+ ``--resume``. A file that differs on both sides is never deleted: the copy
41
+ not kept is parked under ``<backup_dir>/history-conflicts/``.
42
+
43
+ Junctions are not symlinks to the stdlib: ``is_symlink()`` is False for one,
44
+ ``is_dir()`` follows it, ``rglob`` walks into it. Every test for "is this a
45
+ link cswap made" is therefore ``fsutil.is_link``, and the merge walks a
46
+ profile's history with its own eyes (``_history_tree``).
47
+
48
+ One launch, one account: a slot number names whichever account holds the
49
+ slot when it is read, and ``cswap swap`` and ``cswap move`` renumber slots.
50
+ ``run`` therefore settles on one ``(email, organizationUuid)`` pair, its
51
+ caller's or its own first resolution, and every later read of the slot is
52
+ compared with it: ``setup_session``'s resolution, the slot before a profile
53
+ is reused, and the slot under the bootstrap lock before a profile is seeded.
54
+ Another account under the identifier, or none, stops the launch with a
55
+ message to retry. The lock is released before the exec, so a renumbering
56
+ that starts after the last comparison is not seen.
57
+
58
+ This module must not import ``switcher`` (switcher imports us for the
59
+ session-aware guards); it receives a ``ClaudeAccountSwitcher`` instance.
60
+ """
61
+
62
+ from __future__ import annotations
63
+
64
+ import hashlib
65
+ import json
66
+ import os
67
+ import shutil
68
+ import subprocess
69
+ import sys
70
+ import time
71
+ import unicodedata
72
+ from datetime import UTC, datetime
73
+ from pathlib import Path
74
+ from typing import TYPE_CHECKING, NoReturn
75
+
76
+ from claude_swap import macos_keychain, spawn
77
+ from claude_swap.claude_locks import proper_lockfile
78
+ from claude_swap.exceptions import (
79
+ AccountNotFoundError,
80
+ ClaudeCodeLockTimeout,
81
+ CredentialReadError,
82
+ LockError,
83
+ SessionError,
84
+ )
85
+ from claude_swap.fsutil import (
86
+ atomic_write_text,
87
+ can_junction,
88
+ can_symlink,
89
+ is_link,
90
+ link_points_at,
91
+ make_dir_link,
92
+ remove_link,
93
+ replace_with_retry,
94
+ )
95
+ from claude_swap.locking import FileLock
96
+ from claude_swap.models import Platform
97
+ from claude_swap.paths import get_default_global_config_path
98
+ from claude_swap.printer import accent, dimmed, muted, warning
99
+ from claude_swap.process_detection import ClaudeSession, scan_sessions
100
+ from claude_swap.settings import (
101
+ atomic_write_json,
102
+ explicit_share_history,
103
+ load_run_settings,
104
+ )
105
+
106
+ if TYPE_CHECKING:
107
+ from claude_swap.switcher import ClaudeAccountSwitcher
108
+
109
+ # Items mirrored from ~/.claude into session profiles when sharing is on.
110
+ # Deliberately excludes anything account- or instance-scoped: plugins/,
111
+ # sessions/, ide/, .claude.json, .credentials.json, statsig/ and other
112
+ # telemetry. projects/ and history.jsonl are shared too, but as HISTORY_ITEMS:
113
+ # they have their own switch (run.shareHistory) and their own rules.
114
+ # .claude.json stays excluded as a file, but its one user-scoped key —
115
+ # top-level mcpServers — is mirrored separately by _sync_mcp_servers.
116
+ SHARED_ITEMS = (
117
+ "settings.json",
118
+ "keybindings.json",
119
+ "CLAUDE.md",
120
+ "skills",
121
+ "commands",
122
+ "agents",
123
+ "rules",
124
+ )
125
+
126
+ # Conversation-history items, linked unless history sharing is turned off.
127
+ # Always by link, never by copy: a copy would fork history, not share it.
128
+ HISTORY_ITEMS = (
129
+ "projects",
130
+ "history.jsonl",
131
+ )
132
+
133
+ # The shared names that are directories. Known by name rather than by looking
134
+ # at ``~/.claude`` because a history item may have to be linked before it
135
+ # exists there (``_seed_history_source``), and because the kind decides the
136
+ # link on Windows: a directory gets a junction, which needs no privilege; a
137
+ # file needs a symlink, which does.
138
+ _DIR_ITEMS = frozenset({"skills", "commands", "agents", "rules", "projects"})
139
+
140
+
141
+ # Records which entries in a session profile cswap created (so --no-share and
142
+ # re-syncs only ever remove cswap-managed links/copies, never user data).
143
+ SHARE_MANIFEST = ".cswap-shared.json"
144
+
145
+ # Where a losing copy of a same-named transcript is parked. Never a delete:
146
+ # a UUID collision after an un-share means two different halves of one
147
+ # session, not a duplicate.
148
+ QUARANTINE_DIRNAME = "history-conflicts"
149
+
150
+ # Deferred-invalidation marker: the backup moved to a login the profile does
151
+ # not hold while a session was live (we never pull credentials out from under
152
+ # a running claude), so the profile must be re-bootstrapped on the next
153
+ # non-live `cswap run` even if it still passes the local reuse check.
154
+ STALE_MARKER = ".cswap-stale-credentials"
155
+
156
+ # The user-scope MCP key mirrored from the default profile's .claude.json.
157
+ MCP_KEY = "mcpServers"
158
+
159
+ # Adoption marker: this profile's mcpServers is (or was) cswap-mirrored. Gates
160
+ # both the one-time migration stash and --no-share's removal of the key, so
161
+ # pre-feature session-local definitions are never silently destroyed.
162
+ MCP_MIRROR_MARKER = ".cswap-mcp-mirror-v1"
163
+
164
+ # One-time migration stash: session-local MCP definitions displaced by the
165
+ # first mirror land here (write-once) instead of vanishing.
166
+ MCP_DISPLACED_STASH = ".cswap-mcp-displaced.json"
167
+
168
+ # The one lock every history migration takes. It lives IN the shared
169
+ # destination (``~/.claude``), the only place every launch that can merge into
170
+ # that tree agrees on: on Linux the backup root follows ``XDG_DATA_HOME``, so
171
+ # two cswap stores can share one ``~/.claude``, and a lock inside either store
172
+ # is invisible to the other. Never deleted, not even by ``--purge``: unlinking
173
+ # a flock'd file lets a newcomer create a fresh one and hold "the" lock next
174
+ # to a process still holding the old inode. A named constant rather than an
175
+ # inline literal — after a rename, old and new launches would serialize on
176
+ # different files.
177
+ MIGRATION_LOCK = ".cswap-history-migration.lock"
178
+
179
+ # While a profile's own history is merged into ``~/.claude``, the link that
180
+ # will replace it already stands beside it under this suffix
181
+ # (``<item>.cswap-link-staging``), made before anything moves and renamed
182
+ # into place after. One left behind by an interrupted launch is a link and
183
+ # holds nothing; the next launch removes it.
184
+ _STAGED_LINK_SUFFIX = ".cswap-link-staging"
185
+
186
+ # How long a launch waits for the migration lock only to clear such a
187
+ # leftover. A busy lock means a migration is under way and the "leftover"
188
+ # may be its live staging link, so the wait is short and giving up is fine.
189
+ _STAGED_CLEANUP_LOCK_TIMEOUT = 5.0
190
+
191
+
192
+ def stale_marker_for(session_dir: Path) -> Path:
193
+ """Where a profile's stale marker is WRITTEN: a SIBLING of the profile dir.
194
+
195
+ Not a child. One of the two writers is the fallback for a session-dir
196
+ invalidation that just failed, and the faults it exists for — EACCES on
197
+ the session dir, a read-only mount — are faults on that same directory.
198
+ A child marker therefore asks the very directory that denied the unlink
199
+ to accept a create; it refuses, ``mark_session_stale`` swallows the
200
+ OSError, and the profile goes on serving a superseded token with nothing
201
+ recording it. The parent (``<backup>/sessions/``) is ours and is not what
202
+ a per-profile EACCES denied.
203
+
204
+ Sibling of the DIR, so ``purge``'s ``iterdir()`` (dirs only) and
205
+ ``_delete_session_profile``'s ``rmtree`` both still see what they expect.
206
+ """
207
+ return session_dir.parent / f".{session_dir.name}{STALE_MARKER}"
208
+
209
+
210
+ def is_session_stale(session_dir: Path) -> bool:
211
+ """Whether a profile is flagged for re-bootstrap.
212
+
213
+ Both locations: the child path is where the marker used to live, and a
214
+ profile marked by an older cswap on this machine has a pending
215
+ re-bootstrap that the move must not drop. Read, never written.
216
+ """
217
+ return (
218
+ stale_marker_for(session_dir).exists()
219
+ or (session_dir / STALE_MARKER).exists()
220
+ )
221
+
222
+
223
+ def clear_session_stale(session_dir: Path) -> bool:
224
+ """Drop a profile's stale flag from both marker locations.
225
+
226
+ Both are unlinked under their own ``try/except OSError``, not just
227
+ ``missing_ok=True``: that only covers ENOENT, not EACCES/EROFS, and a
228
+ caller that just tolerated a denied dir (``_delete_session_profile``'s
229
+ ``rmtree(ignore_errors=True)``) runs into the same denial again here --
230
+ on the sibling location (``stale_marker_for``, a denied PARENT) as much
231
+ as the legacy CHILD location. Each unlink still runs first, so the
232
+ happy-path removal is unaffected.
233
+
234
+ Returns whether every marker is gone, the way ``mark_session_stale``
235
+ reports its own landing. Tolerating the fault is right; reporting a
236
+ removal that did not happen is not -- the caller logs the profile as
237
+ removed while a marker survives, and the next run's stale arm re-fires
238
+ on it forever, POSTing a refresh grant each time.
239
+ """
240
+ cleared = True
241
+ for marker in (stale_marker_for(session_dir), session_dir / STALE_MARKER):
242
+ try:
243
+ marker.unlink(missing_ok=True)
244
+ except OSError:
245
+ cleared = False
246
+ return cleared
247
+
248
+
249
+ def mark_session_stale(session_dir: Path) -> bool:
250
+ """Flag a live session profile for re-bootstrap once it exits.
251
+
252
+ Returns whether the marker landed. It can still fail — a read-only mount
253
+ denies the sibling as surely as the child — and the caller that reaches
254
+ here BECAUSE an invalidation failed has no other record of it, so the
255
+ answer is reported rather than swallowed.
256
+ """
257
+ try:
258
+ stale_marker_for(session_dir).touch()
259
+ return True
260
+ except OSError:
261
+ return False
262
+
263
+ # Env vars that make claude bypass account OAuth entirely (verified against
264
+ # claude 2.1.175). Dropped from the auth-status probe (they'd fake "logged in"
265
+ # for the wrong reason) AND scrubbed from the session launch env with a
266
+ # warning: `cswap run N` is an explicit request for account N, so letting an
267
+ # exported API key silently hijack the session would defeat the command. The
268
+ # same-account fast path (plain claude, untouched env) does not scrub.
269
+ AUTH_OVERRIDE_ENV_VARS = (
270
+ "ANTHROPIC_API_KEY",
271
+ "ANTHROPIC_AUTH_TOKEN",
272
+ "CLAUDE_CODE_OAUTH_TOKEN",
273
+ "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR",
274
+ "CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR",
275
+ )
276
+
277
+ # Moves Claude Code's credential store, and only that, away from the config
278
+ # home: while this variable is defined, the ``.credentials.json`` file and the
279
+ # Keychain item are resolved from it and not from ``CLAUDE_CONFIG_DIR``, and
280
+ # an empty value selects the default login's store (see
281
+ # ``paths.get_credentials_path``). Claude Code exports it to the shells it
282
+ # starts (see the ``signin`` module docstring), so a `cswap run N` typed
283
+ # inside a running claude inherits it. A claude started in a session profile
284
+ # with it defined would read that other store's login, not the one the
285
+ # profile was seeded with, so it is removed from the probe and launch
286
+ # environment whenever it is defined, with a warning. The same-account fast
287
+ # path keeps it: plain claude on the default login resolves its store the way
288
+ # the caller's shell does.
289
+ CREDENTIAL_STORE_ENV_VAR = "CLAUDE_SECURESTORAGE_CONFIG_DIR"
290
+
291
+ # `claude auth status` is a local check (no API call) but spawns the full CLI.
292
+ _AUTH_STATUS_TIMEOUT = 10.0
293
+
294
+ # Bootstrap holds the backup-dir lock across one token refresh (10s network
295
+ # timeout) plus auth-status probes, so it needs more headroom than the
296
+ # default 10s acquire used by the switch paths.
297
+ _BOOTSTRAP_LOCK_TIMEOUT = 30.0
298
+
299
+ # Migration moves every transcript in a profile, so it waits longer than the
300
+ # bootstrap for a peer to finish rather than bailing and leaving a half state.
301
+ _MIGRATION_LOCK_TIMEOUT = 30.0
302
+
303
+
304
+ def slugify_email(email: str) -> str:
305
+ """Filesystem-safe slug for an email address.
306
+
307
+ Uniqueness comes from the ``<num>-`` slot prefix on the session dir, so
308
+ this only needs to be safe (incl. Windows-forbidden chars), not injective.
309
+ """
310
+ normalized = unicodedata.normalize("NFC", email)
311
+ return "".join(
312
+ ch if (ch.isascii() and (ch.isalnum() or ch in "._-")) else "_"
313
+ for ch in normalized
314
+ )
315
+
316
+
317
+ def session_dir_for(backup_dir: Path, account_num: str, email: str) -> Path:
318
+ """Session profile directory for an account.
319
+
320
+ Note: the profile itself contains Claude's own ``sessions/<pid>.json``
321
+ PID files, so full paths look like
322
+ ``<backup>/sessions/2-user_x.com/sessions/1234.json`` — intentional.
323
+ """
324
+ return backup_dir / "sessions" / f"{account_num}-{slugify_email(email)}"
325
+
326
+
327
+ def keychain_service_name(config_dir: Path | str) -> str:
328
+ """Keychain service name Claude Code derives for this config dir.
329
+
330
+ Claude hashes the raw ``CLAUDE_CONFIG_DIR`` env var value, NFC-normalized
331
+ and unresolved (claude src ``envUtils.ts``/``macOsKeychainHelpers.ts``).
332
+ Hash exactly the string we export — never a resolved/realpath variant.
333
+ Accepts a ``str`` so a caller holding the raw env value can hash it without
334
+ a ``Path`` round-trip, which would drop a trailing slash or ``./``.
335
+ """
336
+ normalized = unicodedata.normalize("NFC", str(config_dir))
337
+ digest = hashlib.sha256(normalized.encode("utf-8")).hexdigest()[:8]
338
+ return f"Claude Code-credentials-{digest}"
339
+
340
+
341
+ def _keychain_account_name() -> str:
342
+ """Keychain account name, mirroring Claude's ``getUsername()``.
343
+
344
+ Delegates to :func:`macos_keychain.keychain_account_name` so session profiles
345
+ and the active store derive the account name identically.
346
+ """
347
+ return macos_keychain.keychain_account_name()
348
+
349
+
350
+ def delete_macos_keychain_entry(session_dir: Path) -> bool:
351
+ """Best-effort delete of a session profile's hashed keychain entry.
352
+
353
+ No-op off macOS. Needed before seeding (Claude reads the keychain before
354
+ the plaintext file, so a stale entry would shadow a fresh seed) and on
355
+ profile removal (once the dir is gone the hashed name is unrecoverable).
356
+
357
+ Returns ``False`` when the delete failed, so the entry may still be
358
+ there; ``True`` when it is gone, was absent, or this is not macOS.
359
+ """
360
+ if Platform.detect() != Platform.MACOS:
361
+ return True
362
+ try:
363
+ macos_keychain.delete_password(
364
+ keychain_service_name(session_dir), _keychain_account_name()
365
+ )
366
+ except macos_keychain.KEYCHAIN_ERRORS:
367
+ return False # best-effort; absent entry is already success (rc 44)
368
+ return True
369
+
370
+
371
+ def read_session_credentials(session_dir: Path) -> str | None:
372
+ """Best-effort read of a session profile's *current* credential JSON.
373
+
374
+ Once a session has run, the profile — not the backup store — holds the
375
+ newest generation of the account's token family: claude rotates tokens
376
+ in place, and nothing syncs them back to backup. On macOS the rotated
377
+ credential lives in the profile's hashed keychain entry (which shadows
378
+ the plaintext seed from the moment claude first writes it), elsewhere in
379
+ the profile's ``.credentials.json``. Read-only by design: writing either
380
+ location stays claude's job (see the module docstring on why cswap never
381
+ writes the hashed entry). Returns ``None`` when the profile has no
382
+ readable credential material.
383
+ """
384
+ return read_config_dir_credentials(str(session_dir))
385
+
386
+
387
+ def _may_have_credential_material(session_dir: Path) -> bool:
388
+ """Whether a profile's credential material is anything but definitely absent.
389
+
390
+ Existence test for the validation-timeout fallback, not a read: ``False``
391
+ only when every store is *positively* empty — no readable plaintext seed
392
+ and (on macOS) a keychain miss claude itself signals with rc 44. An
393
+ unreadable keychain — locked, denied, ``security`` timing out under the
394
+ same load that timed out the probe — is indeterminate, and leans present:
395
+ the profile may hold the freshest generation of the account's token
396
+ family, and re-bootstrapping over it would start by deleting that entry.
397
+ ``read_session_credentials`` is unsuitable here by design — its
398
+ error-to-plaintext fallback erases exactly this distinction.
399
+ """
400
+ try:
401
+ if (session_dir / ".credentials.json").read_text(encoding="utf-8"):
402
+ return True
403
+ except (OSError, ValueError):
404
+ pass # no readable seed — the keychain may still hold the material
405
+ if Platform.detect() != Platform.MACOS:
406
+ return False
407
+ for service in _keychain_services(str(session_dir)):
408
+ try:
409
+ material = macos_keychain.get_password(service, _keychain_account_name())
410
+ except macos_keychain.KEYCHAIN_ERRORS:
411
+ return True # unreadable is not absent: preserve the profile
412
+ if material is not None:
413
+ return True
414
+ return False
415
+
416
+
417
+ def _artifacts_say_usable(session_dir: Path, email: str, org_uuid: str) -> bool:
418
+ """What local artifacts can say about a profile without running the probe.
419
+
420
+ Upstream's probe-timeout fallback (#224 follow-up), lifted to a function
421
+ because two callers ask it and a copy in each is how they drift apart: the
422
+ REUSE check (`_is_session_valid`) and the post-bootstrap check, which must
423
+ not fail a launch over a probe that merely did not answer.
424
+
425
+ Deliberately NOT consulted for "unreachable". There the question is
426
+ whether `claude` can be run at all, and no file on disk answers it.
427
+ """
428
+ return _may_have_credential_material(session_dir) and (
429
+ not session_identity_drifted(session_dir, email, org_uuid)
430
+ )
431
+
432
+
433
+ # Bounded retry for the strict capture read, mirroring the active store's
434
+ # (credentials._ACTIVE_READ_ATTEMPTS / _ACTIVE_READ_RETRY_DELAY).
435
+ _STRICT_KEYCHAIN_ATTEMPTS = 2
436
+ _STRICT_KEYCHAIN_RETRY_DELAY = 0.3 # seconds between attempts
437
+
438
+
439
+ def _keychain_services(config_dir: str, override: str | None = None) -> list[str]:
440
+ """Keychain service names that may hold a profile's credential, in
441
+ lookup order.
442
+
443
+ Claude hashes the exported ``CLAUDE_CONFIG_DIR`` verbatim, so a profile
444
+ that is a symlink was launched under one of two names: its own path, or
445
+ the target's, when a tool launches claude at the target directly and
446
+ keeps the per-account symlink as its bookkeeping (a lease). Reading only
447
+ the link's name would miss every rotation claude wrote under the
448
+ target's and serve the plaintext seed left behind, which is how a leased
449
+ profile's usage silently froze at the last pre-rotation measurement. The
450
+ profile's own name is tried first, then the target's. A relative target
451
+ is joined onto the link's parent and tried in two spellings, likeliest
452
+ first: the lexical form with ``..`` collapsed (``/x/space``, what a tool
453
+ launching at the target usually exports), offered only when it names the
454
+ link's own directory — under a parent that is itself a symlink elsewhere
455
+ it can name an unrelated directory with its own entry — and then the raw
456
+ join (``/x/sessions/../space``, what ``$(dirname link)/$(readlink link)``
457
+ exports). ``override`` names the unsuffixed default-profile item and
458
+ stands alone.
459
+ """
460
+ if override is not None:
461
+ return [override]
462
+ services = [keychain_service_name(config_dir)]
463
+ try:
464
+ target = os.readlink(config_dir)
465
+ except OSError:
466
+ return services
467
+ if os.path.isabs(target):
468
+ services.append(keychain_service_name(target))
469
+ return services
470
+ raw = os.path.join(os.path.dirname(config_dir), target)
471
+ lexical = os.path.normpath(raw)
472
+ try:
473
+ if lexical != raw and os.path.samefile(lexical, raw):
474
+ services.append(keychain_service_name(lexical))
475
+ except OSError:
476
+ pass # nothing at the lexical path: not a spelling of this directory
477
+ services.append(keychain_service_name(raw))
478
+ return services
479
+
480
+
481
+ def _keychain_entry(service: str, strict: bool) -> str | None:
482
+ """One service's item, or ``None`` when absent (rc 44). An unreadable
483
+ keychain is retried once under ``strict`` and then raised as it stands."""
484
+ attempts = _STRICT_KEYCHAIN_ATTEMPTS if strict else 1
485
+ while True:
486
+ try:
487
+ return macos_keychain.get_password(service, _keychain_account_name())
488
+ except macos_keychain.KEYCHAIN_ERRORS:
489
+ attempts -= 1
490
+ if not attempts:
491
+ raise
492
+ time.sleep(_STRICT_KEYCHAIN_RETRY_DELAY)
493
+
494
+
495
+ def read_config_dir_credentials(
496
+ config_dir: str,
497
+ *,
498
+ strict_keychain: bool = False,
499
+ keychain_service: str | None = None,
500
+ ) -> str | None:
501
+ """Same read for an arbitrary ``CLAUDE_CONFIG_DIR`` value.
502
+
503
+ Takes the raw string rather than a ``Path``: claude derives the keychain
504
+ service name from the exported value verbatim, so a ``Path`` round-trip —
505
+ which drops a trailing slash or a leading ``./`` — would look up a service
506
+ name claude never wrote and fall back to the (possibly stale) plaintext
507
+ seed instead.
508
+
509
+ ``keychain_service`` overrides the derived hashed name for the one profile
510
+ whose item is *unsuffixed*: the default profile, which claude selects with
511
+ ``CLAUDE_SECURESTORAGE_CONFIG_DIR`` defined-but-empty.
512
+
513
+ ``strict_keychain`` is for capture (``add``): an *unreadable* keychain —
514
+ locked, denied, timed out — retries once and then raises
515
+ :class:`CredentialReadError` instead of falling back to the plaintext seed.
516
+ The seed may predate an in-profile ``/login``, and capturing it would file
517
+ one account's email against another's token — the very mismatch the capture
518
+ path exists to prevent. An *absent* entry (rc 44) still falls back either
519
+ way: absence is claude's own signal to read the file. For a symlinked
520
+ profile that fallback includes the target's entry under both modes, on
521
+ purpose: it is the newest generation claude wrote for that directory,
522
+ and the seed it would otherwise capture is the one claude stopped
523
+ updating when it first wrote the keychain.
524
+ """
525
+ directory = Path(config_dir)
526
+ if not directory.is_dir():
527
+ return None
528
+ if Platform.detect() == Platform.MACOS:
529
+ for service in _keychain_services(config_dir, keychain_service):
530
+ try:
531
+ creds = _keychain_entry(service, strict_keychain)
532
+ except macos_keychain.KEYCHAIN_ERRORS as e:
533
+ if strict_keychain:
534
+ raise CredentialReadError(
535
+ f"Keychain entry for profile {config_dir} is unreadable "
536
+ f"(locked or busy) — unlock the keychain and retry: {e}"
537
+ ) from e
538
+ break # best-effort read: the plaintext seed is the next-best truth
539
+ if creds:
540
+ return creds
541
+ # entry absent (rc 44) — claude's own signal to look further
542
+ try:
543
+ return (directory / ".credentials.json").read_text(encoding="utf-8")
544
+ except (OSError, ValueError):
545
+ # ValueError covers UnicodeDecodeError: a byte-corrupt file is "no
546
+ # readable credential material", not an error to propagate.
547
+ return None
548
+
549
+
550
+ def read_session_identity(session_dir: Path) -> tuple[str, str] | None:
551
+ """Best-effort read of the account identity a session profile is logged in as.
552
+
553
+ Claude records the logged-in account in the profile's ``.claude.json``
554
+ ``oauthAccount`` and rewrites it on every (re-)login, so this reflects the
555
+ profile's *current* identity — which an in-session ``/login`` can re-point
556
+ at a different account than the slot the profile was created for. Returns
557
+ ``(email, organization_uuid)`` with ``""`` for a missing org, or ``None``
558
+ when no identity is readable (missing dir/file/field).
559
+ """
560
+ try:
561
+ text = (session_dir / ".claude.json").read_text(encoding="utf-8")
562
+ config = json.loads(text)
563
+ except (OSError, ValueError):
564
+ # ValueError covers JSONDecodeError and UnicodeDecodeError alike: a
565
+ # byte-corrupt file is an unreadable identity, and the usage-fetch
566
+ # path this feeds must never raise.
567
+ return None
568
+ if not isinstance(config, dict):
569
+ return None
570
+ oauth_account = config.get("oauthAccount") or {}
571
+ if not isinstance(oauth_account, dict):
572
+ return None
573
+ email = oauth_account.get("emailAddress") or ""
574
+ if not email:
575
+ return None
576
+ return email, oauth_account.get("organizationUuid") or ""
577
+
578
+
579
+ def session_identity_drifted(session_dir: Path, email: str, org_uuid: str) -> bool:
580
+ """Whether the profile is logged in as a *different* account than its slot.
581
+
582
+ An in-session ``/login`` (e.g. after the slot's account hit its rate limit
583
+ mid-session) re-points the profile's credential at another account while
584
+ the profile directory keeps claiming the original slot. Comparison mirrors
585
+ ``_is_session_valid``: the email must match, the org only when both sides
586
+ have a value. An unreadable identity is NOT drift — missing metadata
587
+ degrades to trusting the profile (its token family is normally the slot's
588
+ freshest) rather than abandoning it over a broken ``.claude.json``. That
589
+ is a read-side policy: ``_adopt_session_credential``, which writes the
590
+ profile's credential into the backup, requires ``read_session_identity``
591
+ to succeed on top of this.
592
+ """
593
+ identity = read_session_identity(session_dir)
594
+ if identity is None:
595
+ return False
596
+ profile_email, profile_org = identity
597
+ if profile_email != email:
598
+ return True
599
+ return bool(profile_org and org_uuid and profile_org != org_uuid)
600
+
601
+
602
+ def scan_live_sessions(session_dir: Path) -> tuple[list[ClaudeSession], int]:
603
+ """Live Claude instances for a profile, and records that could not be read.
604
+
605
+ Every caller of this gates a destructive step, so the unreadable count
606
+ travels with the list: a record we could not read is not evidence that
607
+ nothing is running. Renamed from ``live_sessions_for`` deliberately -- the
608
+ old name returned a bare list, and a call site left on it would read a
609
+ tuple as unconditionally truthy.
610
+ """
611
+ if not session_dir.exists():
612
+ return [], 0
613
+ return scan_sessions(claude_dir=session_dir)
614
+
615
+
616
+ def profile_is_quiescent(session_dir: Path) -> bool:
617
+ """Nothing is running against this profile, AND we could read every record.
618
+
619
+ The predicate every "is it safe to rewrite/remove this profile" site
620
+ wants. False when a record is unreadable: not knowing is not the same as
621
+ knowing nothing is there, and the step behind these callers cannot be
622
+ undone.
623
+ """
624
+ sessions, unreadable = scan_live_sessions(session_dir)
625
+ return not sessions and unreadable == 0
626
+
627
+
628
+ def _history_tree(root: Path) -> list[Path]:
629
+ """Every path under ``root``, deepest first, without looking through a link.
630
+
631
+ ``rglob`` and ``os.walk`` descend into a Windows junction as into a plain
632
+ directory, and the merge moves what it is shown: through a junction
633
+ someone placed inside a profile's ``projects/`` it would carry off the
634
+ contents of whatever that junction leads to. So the walk is spelled out
635
+ here, and a link met on the way — junction or symlink, to a directory or
636
+ a file — ends it with an error naming the path, before anything has
637
+ moved. The merge is of this profile's own files; a link holds none.
638
+ """
639
+ found: list[Path] = []
640
+
641
+ def visit(directory: Path) -> None:
642
+ with os.scandir(directory) as entries:
643
+ children = list(entries)
644
+ for entry in children:
645
+ path = Path(entry.path)
646
+ if entry.is_symlink() or entry.is_junction():
647
+ raise OSError(
648
+ f"{path} is a link, which a history merge never follows; "
649
+ "move it out of the profile to share the rest"
650
+ )
651
+ found.append(path)
652
+ if entry.is_dir(follow_symlinks=False):
653
+ visit(path)
654
+
655
+ visit(root)
656
+ return sorted(found, reverse=True)
657
+
658
+
659
+ def _mkdir_private(path: Path) -> None:
660
+ """mkdir -p with 0o700 on every created level.
661
+
662
+ ``Path.mkdir(parents=True, mode=...)`` applies the mode only to the leaf;
663
+ history dirs must match Claude Code's own 0o700 at every level.
664
+ """
665
+ missing: list[Path] = []
666
+ current = path
667
+ while not current.exists():
668
+ missing.append(current)
669
+ current = current.parent
670
+ for directory in reversed(missing):
671
+ directory.mkdir(mode=0o700, exist_ok=True)
672
+
673
+
674
+ def _last_timestamp(path: Path) -> str | None:
675
+ """Last ISO-8601 ``timestamp`` in a JSONL transcript, scanning backwards.
676
+
677
+ Claude closes nearly every transcript with untimestamped state lines
678
+ (``last-prompt``, ``mode``, ``ai-title``, ``file-history-snapshot``), so
679
+ reading only the final line finds a timestamp in about 1% of real files.
680
+ Scanning back finds one within a line or two. Values are ISO-8601 Zulu
681
+ with milliseconds, so lexical comparison is chronological.
682
+ """
683
+ try:
684
+ text = path.read_text(encoding="utf-8", errors="replace")
685
+ except OSError:
686
+ return None
687
+ for line in reversed(text.splitlines()):
688
+ if not line.strip():
689
+ continue
690
+ try:
691
+ entry = json.loads(line)
692
+ except ValueError:
693
+ continue
694
+ if isinstance(entry, dict):
695
+ stamp = entry.get("timestamp")
696
+ if isinstance(stamp, str) and stamp:
697
+ return stamp
698
+ return None
699
+
700
+
701
+ def _line_count(path: Path) -> int:
702
+ """Lines in a file; 0 when it cannot be read (so it never wins a tiebreak)."""
703
+ try:
704
+ with path.open("rb") as handle:
705
+ return sum(1 for _ in handle)
706
+ except OSError:
707
+ return 0
708
+
709
+
710
+ def _profile_copy_wins(target: Path, candidate: Path) -> bool:
711
+ """Whether the profile's ``candidate`` should replace the shared ``target``.
712
+
713
+ A same-named pair is *not* the same session: a transcript that straddled
714
+ an un-share event exists in both trees under one UUID with different
715
+ content. Order, applied in full so the outcome is deterministic: later
716
+ last-timestamp, then having a timestamp at all, then more lines, then the
717
+ incumbent. The loser is quarantined either way, never dropped.
718
+ """
719
+ target_stamp = _last_timestamp(target)
720
+ candidate_stamp = _last_timestamp(candidate)
721
+ if target_stamp != candidate_stamp:
722
+ if target_stamp is None:
723
+ return True
724
+ if candidate_stamp is None:
725
+ return False
726
+ return candidate_stamp > target_stamp
727
+ return _line_count(candidate) > _line_count(target)
728
+
729
+
730
+ def _adds_nothing(target: Path, candidate: Path) -> bool:
731
+ """Whether the shared ``target`` already holds every byte of ``candidate``.
732
+
733
+ True for a byte-identical pair, and for a target that merely continues
734
+ the candidate — an older snapshot of an append-only transcript is a
735
+ prefix of the newer one. Either way the profile's copy is a true
736
+ duplicate, the one collision that is safe to drop rather than
737
+ quarantine. Unreadable means unknown, which is never "safe to drop".
738
+ """
739
+ try:
740
+ if candidate.stat().st_size > target.stat().st_size:
741
+ return False
742
+ with candidate.open("rb") as profile, target.open("rb") as shared:
743
+ while chunk := profile.read(1 << 20):
744
+ if shared.read(len(chunk)) != chunk:
745
+ return False
746
+ return True
747
+ except OSError:
748
+ return False
749
+
750
+
751
+ def _probe_env(session_dir: Path) -> dict[str, str]:
752
+ """Env for a claude that runs in a session profile.
753
+
754
+ Session config dir, with the auth overrides and the credential-store
755
+ override dropped. The auth-status probe and the launch both use it, so
756
+ the launch reads the store the probe validated: the profile's own.
757
+ """
758
+ dropped = {*AUTH_OVERRIDE_ENV_VARS, CREDENTIAL_STORE_ENV_VAR}
759
+ env = {k: v for k, v in os.environ.items() if k not in dropped}
760
+ env["CLAUDE_CONFIG_DIR"] = str(session_dir)
761
+ return env
762
+
763
+
764
+ class SessionManager:
765
+ """Bootstraps per-account session profiles and launches Claude into them."""
766
+
767
+ def __init__(self, switcher: ClaudeAccountSwitcher):
768
+ self.switcher = switcher
769
+ self.sessions_dir = switcher.backup_dir / "sessions"
770
+ self._logger = switcher._logger
771
+ # Filled by the most recent merge so the launch can report counts
772
+ # without re-deriving them from the filesystem.
773
+ self._last_merge_counts: tuple[int, int, Path | None] = (0, 0, None)
774
+ # A deferred migration is explained once per launch, not once per
775
+ # history item.
776
+ self._deferral_reported = False
777
+ # Whether this launch met history the profile holds on its own (and
778
+ # so tried to merge it), whatever came of the attempt.
779
+ self._own_history_found = False
780
+ # A history item that cannot be linked on this machine is explained
781
+ # once per launch (``_report_history_unlinkable``), as loudly as
782
+ # sharing was asked for: the flag on the command line counts as
783
+ # asking, ``run.shareHistory`` in the settings file too.
784
+ self._unlinkable_reported = False
785
+ self._share_history_asked = False
786
+
787
+ # -- launch ----------------------------------------------------------
788
+
789
+ def run(
790
+ self,
791
+ identifier: str,
792
+ claude_args: list[str],
793
+ share: bool = True,
794
+ share_history: bool | None = None,
795
+ require_session: bool = False,
796
+ expected_identity: tuple[str, str] | None = None,
797
+ ) -> NoReturn:
798
+ """Launch Claude Code as the given account in the current terminal.
799
+
800
+ ``share_history`` is the launch's own choice (``--share-history`` /
801
+ ``--no-share-history``); ``None`` leaves it to ``run.shareHistory``
802
+ (see ``_resolve_share_history``).
803
+
804
+ ``require_session`` turns the same-account fast path (a plain claude
805
+ launch on the default login) into a refusal: a wrapper that hands a
806
+ terminal to one account per session needs the isolation guaranteed,
807
+ and a session on the default login is the one thing an account
808
+ switch can later pull out from under it.
809
+
810
+ ``expected_identity`` is the ``(email, organizationUuid)`` a caller
811
+ already settled on before it turned the account into ``identifier``,
812
+ as the directory mapping does. The launch is for that account, or
813
+ without it for the account ``identifier`` resolves to first. When a
814
+ later read finds another account under ``identifier``, or none,
815
+ nothing is launched and a ``SessionError`` says to retry.
816
+
817
+ Notices on the way are printed plainly. `cswap run` sends them to
818
+ stderr, because stdout is claude's (``cli._run_launch``).
819
+ """
820
+ claude_bin = shutil.which("claude")
821
+ if not claude_bin:
822
+ raise SessionError(
823
+ "'claude' was not found on PATH. Install Claude Code first."
824
+ )
825
+ # Resolved here for the fast path below, which never reaches
826
+ # setup_session. setup_session is then handed the request, not the
827
+ # answer: it resolves it the same way, and only the request says
828
+ # whether sharing was asked for or defaulted (``_share_history_asked``
829
+ # — an answer of True would read as asked for).
830
+ requested_history = share_history
831
+ share_history = self._resolve_share_history(requested_history)
832
+
833
+ account_num, email, org_uuid = self._resolve_expecting(
834
+ identifier, expected_identity
835
+ )
836
+ # The guards and the fast path below judge this account, so it is the
837
+ # one setup_session has to find under ``identifier`` as well.
838
+ identity = (email, org_uuid)
839
+ # Guard before the same-account direct-launch fast path below (which
840
+ # _exec's claude and never returns) — and before setup_session.
841
+ self._ensure_not_api_key(account_num, email)
842
+
843
+ config_dir_preset = os.environ.get("CLAUDE_CONFIG_DIR")
844
+ # Same-account fast path: never create a second credential copy
845
+ # for the account that is already the active default login —
846
+ # two copies of one account can drift if the server rotates the
847
+ # refresh token. With CLAUDE_CONFIG_DIR preset (we may be inside
848
+ # another session's terminal) the *default* login is still what a
849
+ # session for this account would copy, so it is read from the
850
+ # default profile rather than from the preset directory.
851
+ if config_dir_preset:
852
+ labelled = self._default_login_identity()
853
+ else:
854
+ labelled = self.switcher._get_current_account()
855
+ # The config only names an account. Which account the default login
856
+ # is, the login itself says.
857
+ current = self._default_login_account(labelled)
858
+ # A default login with no usable token cannot run claude, and holds no
859
+ # refresh token a session could spend twice, so the account's session
860
+ # profile is the launch that works.
861
+ signed_out = (
862
+ current is not None
863
+ and current == (email, org_uuid)
864
+ and self._default_login_signed_out()
865
+ )
866
+ if signed_out:
867
+ print(
868
+ dimmed(
869
+ f"Account-{account_num} ({email}) is the default login, "
870
+ "but that login holds no usable token; launching from "
871
+ "the stored login in a session profile."
872
+ )
873
+ )
874
+ if current is not None and current == (email, org_uuid) and not signed_out:
875
+ if require_session:
876
+ raise SessionError(
877
+ f"Account-{account_num} ({email}) is the active default "
878
+ "login, so this launch would run plain claude on the "
879
+ "default login rather than in a session profile (a "
880
+ "second copy of the active credential would drift). "
881
+ "Switch the default login to another account first, "
882
+ "or run `claude` directly."
883
+ )
884
+ print(
885
+ dimmed(
886
+ f"Account-{account_num} ({email}) is already the active "
887
+ "default login — launching claude directly."
888
+ )
889
+ )
890
+ self._history_on_the_fast_path(
891
+ session_dir_for(self.switcher.backup_dir, account_num, email),
892
+ share_history,
893
+ )
894
+ env = dict(os.environ)
895
+ # Run on the default login, not on the preset profile.
896
+ env.pop("CLAUDE_CONFIG_DIR", None)
897
+ self._exec(claude_bin, claude_args, env=env)
898
+ if config_dir_preset:
899
+ warning(
900
+ f"CLAUDE_CONFIG_DIR is already set ({config_dir_preset}); "
901
+ "overriding it for this launch."
902
+ )
903
+
904
+ scrubbed = [v for v in AUTH_OVERRIDE_ENV_VARS if os.environ.get(v)]
905
+ if scrubbed:
906
+ warning(
907
+ f"Ignoring {', '.join(scrubbed)} for this session — it would "
908
+ f"override the selected account inside Claude Code."
909
+ )
910
+ # Defined, not truthy: an empty value selects the default login's
911
+ # store.
912
+ if CREDENTIAL_STORE_ENV_VAR in os.environ:
913
+ warning(
914
+ f"Ignoring {CREDENTIAL_STORE_ENV_VAR} for this session: it "
915
+ "would make Claude Code read its login from another "
916
+ "credential store than the selected account's profile."
917
+ )
918
+
919
+ session_dir, account_num, email = self.setup_session(
920
+ identifier, share, requested_history, expected_identity=identity
921
+ )
922
+
923
+ print(
924
+ f"{accent('Launching')} Account-{account_num} ({email}) "
925
+ f"{muted('[session mode]')}"
926
+ )
927
+ self._exec(claude_bin, claude_args, env=_probe_env(session_dir))
928
+
929
+ def _history_on_the_fast_path(
930
+ self, session_dir: Path, share_history: bool
931
+ ) -> None:
932
+ """Deal with history the profile holds, on the launch that skips it.
933
+
934
+ The fast path is plain claude on ``~/.claude``, so what the account's
935
+ sessions wrote into its profile is not in front of the user (#239).
936
+ With sharing on it is merged now, by the steps a session launch
937
+ takes: an account that stays the default login would otherwise never
938
+ be migrated, however often it is run. With sharing off it stays
939
+ apart, and the launch says which history it is about to use.
940
+
941
+ History only. Nothing here seeds, validates or refreshes the
942
+ profile's credentials — a second live copy of the default login's
943
+ credential is what the fast path exists to avoid. A profile with no
944
+ history of its own (never used, or already linked) is left alone.
945
+ """
946
+ if not any(
947
+ (session_dir / name).exists() and not is_link(session_dir / name)
948
+ for name in HISTORY_ITEMS
949
+ ):
950
+ return
951
+ if share_history:
952
+ self._sync_items(session_dir, HISTORY_ITEMS, scope=HISTORY_ITEMS)
953
+ else:
954
+ print(
955
+ dimmed(
956
+ " This launch uses the default login's chat history "
957
+ "(~/.claude), not the account's own."
958
+ )
959
+ )
960
+
961
+ def _resolve_share_history(self, requested: bool | None) -> bool:
962
+ """Whether this launch shares chat history across accounts.
963
+
964
+ ``requested`` is the launch's own choice and wins. ``None`` defers to
965
+ ``run.shareHistory``, which is on unless the user turned it off.
966
+ Resolved here rather than by the caller so every launcher gets the
967
+ same answer from the same ``None``.
968
+
969
+ Whether each history item can then actually be linked on this
970
+ machine is decided per item, in ``_sync_items``: Windows without a
971
+ symlink privilege keeps ``history.jsonl`` apart. The answer here is
972
+ remembered as asked-for or defaulted, so that report can be as loud
973
+ as the asking was.
974
+ """
975
+ self._share_history_asked = requested is True
976
+ if requested is not None:
977
+ return requested
978
+ return load_run_settings(self.switcher.backup_dir).share_history
979
+
980
+ @staticmethod
981
+ def _default_login_identity() -> tuple[str, str] | None:
982
+ """``(email, org_uuid)`` of the default profile's login, if any.
983
+
984
+ Ignores ``CLAUDE_CONFIG_DIR``, like ``_read_mcp_source``.
985
+ """
986
+ config = SessionManager._load_json_object(get_default_global_config_path())
987
+ oauth = config.get("oauthAccount") if config else None
988
+ if not isinstance(oauth, dict) or not oauth.get("emailAddress"):
989
+ return None
990
+ return oauth["emailAddress"], oauth.get("organizationUuid", "") or ""
991
+
992
+ def _default_login_account(
993
+ self, labelled: tuple[str, str] | None
994
+ ) -> tuple[str, str] | None:
995
+ """``(email, org_uuid)`` of the managed account whose login the
996
+ default profile holds, or None.
997
+
998
+ ``labelled`` is the account the default profile's config names. The
999
+ two differ when another host signed in to a different account
1000
+ rewrote that config (``switcher._active_slot``). Plain claude would
1001
+ then run as the login's account, not the named one, and a session
1002
+ for the login's account would be a second copy of the default login.
1003
+
1004
+ The login is read from the default profile, whatever
1005
+ ``CLAUDE_CONFIG_DIR`` says, like ``_default_login_signed_out``.
1006
+ """
1007
+ preset = os.environ.pop("CLAUDE_CONFIG_DIR", None)
1008
+ try:
1009
+ return self.switcher.live_login_account(labelled)
1010
+ finally:
1011
+ if preset is not None:
1012
+ os.environ["CLAUDE_CONFIG_DIR"] = preset
1013
+
1014
+ def _default_login_signed_out(self) -> bool:
1015
+ """True only when the default login certainly holds no usable token.
1016
+
1017
+ The same-account fast path runs plain claude on the default login.
1018
+ When a refresh is rejected with invalid_grant, Claude Code (2.1.322)
1019
+ empties both tokens in the credential store and leaves
1020
+ ``oauthAccount`` in ``.claude.json``. The login then still names the
1021
+ account, and every launch on it stops at "Not logged in" or "Login
1022
+ expired", while the slot's stored login may still be good.
1023
+ ``/logout`` does not lead here: it removes ``oauthAccount``, so the
1024
+ account is no longer the default login.
1025
+
1026
+ Read as the fast path's claude would read it: the default profile,
1027
+ whatever ``CLAUDE_CONFIG_DIR`` says. An unreadable Keychain, a file
1028
+ read error, a managed API key or a blob of unknown shape cannot be
1029
+ told apart from a working login, so they answer False and keep the
1030
+ fast path.
1031
+
1032
+ A non-empty ``CLAUDE_SECURESTORAGE_CONFIG_DIR`` answers False too.
1033
+ Claude Code (2.1.322) then resolves its credential store from that
1034
+ value, and the plaintext half of this read does not follow it, so
1035
+ an empty result would say nothing about the login claude uses.
1036
+ """
1037
+ from claude_swap import oauth as _oauth
1038
+ from claude_swap.credentials import looks_like_api_key
1039
+
1040
+ if os.environ.get("CLAUDE_SECURESTORAGE_CONFIG_DIR"):
1041
+ return False
1042
+ preset = os.environ.pop("CLAUDE_CONFIG_DIR", None)
1043
+ try:
1044
+ active = self.switcher._read_active_credentials()
1045
+ finally:
1046
+ if preset is not None:
1047
+ os.environ["CLAUDE_CONFIG_DIR"] = preset
1048
+ if active.value is None or active.keychain_unavailable or active.degraded:
1049
+ return False
1050
+ if not active.value.strip():
1051
+ return True
1052
+ if looks_like_api_key(active.value):
1053
+ return False
1054
+ data = _oauth.extract_oauth_data(active.value)
1055
+ if data is None:
1056
+ return False
1057
+ if data.get("refreshToken"):
1058
+ return False
1059
+ if not data.get("accessToken"):
1060
+ return True
1061
+ # An access token without a refresh token works until it expires.
1062
+ expires_at = data.get("expiresAt")
1063
+ return (
1064
+ isinstance(expires_at, (int, float))
1065
+ and not isinstance(expires_at, bool)
1066
+ and expires_at <= time.time() * 1000
1067
+ )
1068
+
1069
+ def exec_default(self, claude_args: list[str]) -> NoReturn:
1070
+ """Launch plain Claude Code with the current default login.
1071
+
1072
+ Used by `cswap run` (no account, no ``--require-session``) when the
1073
+ cwd has no mapping, or its mapped account no longer exists. Equivalent
1074
+ to typing `claude` directly: the unmodified environment is passed
1075
+ through (no session profile, no auth-override scrubbing), so whatever
1076
+ the default login resolves to is what runs.
1077
+ """
1078
+ claude_bin = shutil.which("claude")
1079
+ if not claude_bin:
1080
+ raise SessionError(
1081
+ "'claude' was not found on PATH. Install Claude Code first."
1082
+ )
1083
+ self._exec(claude_bin, claude_args, env=dict(os.environ))
1084
+
1085
+ def _exec(self, claude_bin: str, claude_args: list[str], env: dict[str, str]) -> NoReturn:
1086
+ """Hand the terminal over to claude. Never returns.
1087
+
1088
+ POSIX: ``execvpe`` replaces the cswap process entirely (the lock is
1089
+ already released — an exec'd claude must never inherit a held flock).
1090
+ Windows: ``os.exec*`` detaches from the console confusingly, so stay
1091
+ resident as a thin wrapper and mirror claude's exit code.
1092
+ """
1093
+ argv = [claude_bin, *claude_args]
1094
+ if sys.platform == "win32":
1095
+ try:
1096
+ rc = subprocess.run(argv, env=env).returncode
1097
+ except KeyboardInterrupt:
1098
+ rc = 130 # Ctrl+C went to claude; just mirror the exit
1099
+ sys.exit(rc)
1100
+ os.execvpe(claude_bin, argv, env)
1101
+ raise AssertionError("unreachable") # pragma: no cover
1102
+
1103
+ def _ensure_not_api_key(self, account_num: str, email: str) -> None:
1104
+ """Reject API-key accounts in session mode (not supported yet).
1105
+
1106
+ Session bootstrap is OAuth-shaped — it seeds ``.credentials.json`` and
1107
+ ``_is_session_valid`` requires ``authMethod == "claude.ai"`` — so an API-key
1108
+ account would otherwise fail validation opaquely. Raise early with guidance.
1109
+ """
1110
+ if self.switcher._account_kind(account_num) == "api_key":
1111
+ raise SessionError(
1112
+ f"Account-{account_num} ({email}) is an API-key account; "
1113
+ "'cswap run' (session mode) does not support API-key accounts yet. "
1114
+ "Use 'cswap --switch-to' to make it your default login instead."
1115
+ )
1116
+
1117
+ @staticmethod
1118
+ def _account_changed_error(identifier: str, email: str) -> SessionError:
1119
+ """The refusal to launch another account than the launch settled on."""
1120
+ where = f"slot {identifier}" if identifier.isdigit() else f"'{identifier}'"
1121
+ return SessionError(
1122
+ f"The account this launch settled on ({email}) is not what "
1123
+ f"{where} names now. The accounts changed while the launch was "
1124
+ "being prepared, for example by `cswap swap` or `cswap move` in "
1125
+ "another terminal. Nothing was launched. Check `cswap list`, "
1126
+ "then run the command again."
1127
+ )
1128
+
1129
+ def _resolve_expecting(
1130
+ self, identifier: str, expected_identity: tuple[str, str] | None
1131
+ ) -> tuple[str, str, str]:
1132
+ """Resolve ``identifier`` and hold the answer against the account the
1133
+ launch settled on. Returns what ``switcher.resolve_account`` does.
1134
+
1135
+ With no ``expected_identity`` this is ``switcher.resolve_account``,
1136
+ errors included: nothing is settled yet, and an identifier that names
1137
+ no account is the user's to correct.
1138
+
1139
+ With one, ``identifier`` named that account a moment ago. Another
1140
+ account under it, or none, means the slots changed in between, and
1141
+ the ``SessionError`` says to retry. ``expected_identity`` is
1142
+ ``(email, organizationUuid)``, and both are compared exactly: an
1143
+ empty organisation is the personal account, which can share its
1144
+ email with an organisation account of the same person.
1145
+
1146
+ Takes no lock itself. `cswap swap` and `cswap move` renumber slots
1147
+ under ``switcher.lock_file``, so for a caller that holds that lock
1148
+ neither of them changes the answer before the release.
1149
+ """
1150
+ try:
1151
+ account_num, email, org_uuid = self.switcher.resolve_account(identifier)
1152
+ except AccountNotFoundError:
1153
+ if expected_identity is None:
1154
+ raise
1155
+ raise self._account_changed_error(
1156
+ identifier, expected_identity[0]
1157
+ ) from None
1158
+ if expected_identity is not None and (email, org_uuid) != expected_identity:
1159
+ raise self._account_changed_error(account_num, expected_identity[0])
1160
+ return account_num, email, org_uuid
1161
+
1162
+ # -- bootstrap -------------------------------------------------------
1163
+
1164
+ def setup_session(
1165
+ self,
1166
+ identifier: str,
1167
+ share: bool,
1168
+ share_history: bool | None = None,
1169
+ expected_identity: tuple[str, str] | None = None,
1170
+ ) -> tuple[Path, str, str]:
1171
+ """Ensure a valid session profile exists; returns (dir, num, email).
1172
+
1173
+ ``share_history`` is read like ``run``'s: ``None`` means
1174
+ ``run.shareHistory`` decides.
1175
+
1176
+ ``expected_identity`` is the ``(email, organizationUuid)`` the caller
1177
+ resolved ``identifier`` to. When ``identifier`` names another account
1178
+ by now, or none, nothing is set up and a ``SessionError`` says to
1179
+ retry. With or without it, the slot is read again before a profile
1180
+ is reused and, under the lock, before one is seeded, because the
1181
+ profile path and the backup are both keyed by the slot number.
1182
+ """
1183
+ share_history = self._resolve_share_history(share_history)
1184
+ account_num, email, org_uuid = self._resolve_expecting(
1185
+ identifier, expected_identity
1186
+ )
1187
+ identity = (email, org_uuid)
1188
+ # Defense-in-depth: also guard here (run() guards before its fast path).
1189
+ self._ensure_not_api_key(account_num, email)
1190
+ session_dir = session_dir_for(self.switcher.backup_dir, account_num, email)
1191
+
1192
+ # Deferred invalidation: backup credentials changed while this profile
1193
+ # was live, so its credentials are presumed stale even if they still
1194
+ # pass the local reuse check. Honored only when no session is live —
1195
+ # a second `cswap run` joining a live session must not invalidate
1196
+ # under the running claude (the marker survives for later).
1197
+ stale = is_session_stale(session_dir) and profile_is_quiescent(session_dir)
1198
+
1199
+ # Cheap reuse check without the lock: most launches hit this.
1200
+ if not stale and self._is_session_valid(session_dir, email, org_uuid):
1201
+ # The probe compares the organisation only when both sides have
1202
+ # one, so it passes a profile of the same email's other account,
1203
+ # which is what a swap of the two leaves at this path: a moved
1204
+ # profile that is level with its backup stays signed in
1205
+ # (``_write_account_credentials``). So the slot is read again.
1206
+ # Without the lock: this sees a swap that has committed, not one
1207
+ # that has moved the profiles and not yet written sequence.json.
1208
+ self._resolve_expecting(account_num, identity)
1209
+ self._sync_sharing(session_dir, share, share_history)
1210
+ return session_dir, account_num, email
1211
+
1212
+ # One refresh so the profile starts with a fresh access token —
1213
+ # BEFORE the bootstrap lock (the gate takes the same non-reentrant
1214
+ # FileLock and POSTs over the network, which must never run under a
1215
+ # held lock). The gate re-reads the freshest copy itself and
1216
+ # persists via fingerprint CAS; _bootstrap then reads the rotated
1217
+ # backup. Failure is non-fatal: the stored token may still be
1218
+ # valid, and claude refreshes on its own at runtime. Setup-token
1219
+ # accounts (--add-token) have no refresh token by design — skip
1220
+ # silently instead of warning about a flow that can't happen.
1221
+ pre_creds = self.switcher.read_account_credentials(account_num, email)
1222
+ if pre_creds and self._has_refresh_token(pre_creds):
1223
+ outcome = self.switcher.consume_backup_grant(
1224
+ account_num, email, pre_creds
1225
+ )
1226
+ if outcome.error is not None and outcome.credentials:
1227
+ # `error is None` is the gate's own "the slot is freshened
1228
+ # and safe to activate" signal, and it is NOT implied by
1229
+ # credentials being present: a failed persist returns the
1230
+ # successor AND `transient`, with the backup still holding
1231
+ # the generation whose grant was just spent.
1232
+ #
1233
+ # WARNING ABOUT IT IS NOT ENOUGH. `_bootstrap` re-reads the
1234
+ # backup, so continuing seeds the profile from that spent
1235
+ # generation and claude's first refresh gets invalid_grant —
1236
+ # the warning scrolls past and the session is broken anyway.
1237
+ #
1238
+ # Refuse — but the two demoted shapes need OPPOSITE advice,
1239
+ # and `error`/`credentials` cannot tell them apart, which is
1240
+ # why the gate carries `stashed`.
1241
+ #
1242
+ # Stashed: retrying is right. The next run's gate adopts the
1243
+ # successor without consuming anything and bootstraps
1244
+ # normally, so the recovery machinery already built here does
1245
+ # the rest.
1246
+ #
1247
+ # NOT stashed (`consume-gate-unpersisted`, where the persist
1248
+ # AND the stash both failed): retrying POSTs the spent
1249
+ # predecessor and earns a strike. The successor survived only
1250
+ # in this return value, which the raise discards — saying
1251
+ # "nothing was lost" there would be false on both counts. The
1252
+ # remedy is the storage failure, which is what the gate's own
1253
+ # ERROR log at that site already says.
1254
+ #
1255
+ # This shape is distinguishable at the call site: a genuine
1256
+ # network-transient carries `credentials=None` and falls to
1257
+ # the warning below, where continuing on the stored
1258
+ # credentials is correct because nothing was spent.
1259
+ if outcome.stashed:
1260
+ raise SessionError(
1261
+ f"Account-{account_num}'s refreshed credential could "
1262
+ f"not be stored, so the backup still holds a spent "
1263
+ f"grant. The successor is stashed — please retry, and "
1264
+ f"the next run adopts it automatically."
1265
+ )
1266
+ raise SessionError(
1267
+ f"Account-{account_num}'s refreshed credential could "
1268
+ f"neither be stored nor stashed, so the backup holds a "
1269
+ f"spent grant and the successor is gone. Fix the storage "
1270
+ f"failure first; retrying before that spends nothing but "
1271
+ f"earns a strike. If the slot strikes, log in again and "
1272
+ f"re-add it: cswap --add-account --slot {account_num}"
1273
+ )
1274
+ if outcome.error == "live-login":
1275
+ # The gate declined because the live login holds this same
1276
+ # grant. ``_bootstrap`` refuses that copy too; raising here
1277
+ # keeps the "continuing with the stored credentials" warning
1278
+ # below from preceding it.
1279
+ raise self._live_login_error(account_num)
1280
+ if outcome.error is not None:
1281
+ warning(
1282
+ f"Could not refresh the token for Account-{account_num}; "
1283
+ "continuing with the stored credentials."
1284
+ )
1285
+
1286
+ with FileLock(self.switcher.lock_file, timeout=_BOOTSTRAP_LOCK_TIMEOUT):
1287
+ # Swap and move renumber slots under this lock, and the backup
1288
+ # _bootstrap reads is keyed by slot and email. Once the slot is
1289
+ # seen to hold the resolved account here, neither of them can
1290
+ # put another account's credential under that key before the
1291
+ # release.
1292
+ self._resolve_expecting(account_num, identity)
1293
+ # Re-evaluate the marker under the lock, then re-check validity:
1294
+ # another `cswap run` may have bootstrapped while we waited.
1295
+ if is_session_stale(session_dir) and profile_is_quiescent(session_dir):
1296
+ self.switcher._invalidate_session_credentials(account_num, email)
1297
+ clear_session_stale(session_dir)
1298
+ if self._is_session_valid(session_dir, email, org_uuid):
1299
+ # Valid, but possibly not on the generation WE just paid for.
1300
+ # The consume above runs outside this lock (it POSTs), so a
1301
+ # peer `cswap run` can bootstrap while we wait — and its
1302
+ # profile predates our rotation. Its refresh token is the one
1303
+ # our gate consumed, so claude's own refresh would get
1304
+ # invalid_grant on first use: a spent grant, silently.
1305
+ # Validity is an identity check, not a generation check, so it
1306
+ # cannot see this. Re-seed instead of returning early.
1307
+ #
1308
+ # NEVER under a live claude. _bootstrap deletes the profile's
1309
+ # Keychain entry and overwrites .credentials.json, and the peer
1310
+ # that bootstrapped ahead of us has already exec'd into that
1311
+ # profile — rewriting it beneath a running instance is the
1312
+ # failure every other invalidation site in this file guards
1313
+ # against (the STALE_MARKER branch above, and
1314
+ # _post_backup_write's). This branch fires precisely when the
1315
+ # profile is VALID, which is the live case, so it needed the
1316
+ # guard most and had it least. Deferring costs the peer a
1317
+ # generation it can still refresh from; rewriting costs it the
1318
+ # session.
1319
+ if not self._profile_matches_backup(
1320
+ session_dir, account_num, email
1321
+ ) and profile_is_quiescent(session_dir):
1322
+ self._bootstrap(session_dir, account_num, email, org_uuid)
1323
+ self._sync_sharing(session_dir, share, share_history)
1324
+ return session_dir, account_num, email
1325
+
1326
+ self._bootstrap(session_dir, account_num, email, org_uuid)
1327
+ self._sync_sharing(session_dir, share, share_history)
1328
+
1329
+ verdict = self._session_validity(session_dir, email, org_uuid)
1330
+ # NEITHER probe-failure verdict may reach `_cleanup_failed_session`
1331
+ # below: it deletes the Keychain entry and the whole directory, and
1332
+ # running it here would destroy a profile we never managed to look
1333
+ # at — on nothing worse than a 10s timeout on a loaded machine.
1334
+ #
1335
+ # But "do not delete" is not "do not proceed". We have just
1336
+ # bootstrapped from the backup credentials, so the same local
1337
+ # artifacts that answer the reuse path answer this one, and a
1338
+ # timeout here must not fail a launch that is fine (#224
1339
+ # follow-up). Only "unreachable" still stops: no local file can
1340
+ # tell us whether `claude` runs, and a session we cannot exec into
1341
+ # is not a session.
1342
+ if verdict == "unknown" and _artifacts_say_usable(
1343
+ session_dir, email, org_uuid
1344
+ ):
1345
+ verdict = "valid"
1346
+ if verdict in ("unknown", "unreachable"):
1347
+ raise SessionError(
1348
+ f"Session profile for Account-{account_num} ({email}) could "
1349
+ f"not be verified: `claude auth status` did not run or did "
1350
+ f"not answer. The profile is left in place — check that "
1351
+ f"`claude` is on PATH, then retry."
1352
+ )
1353
+ if verdict != "valid":
1354
+ self._cleanup_failed_session(session_dir)
1355
+ raise SessionError(
1356
+ f"Session profile for Account-{account_num} ({email}) failed "
1357
+ f"validation. Log in with that account and re-add it: "
1358
+ f"cswap --add-account --slot {account_num}"
1359
+ )
1360
+ # Lock released here, before any exec.
1361
+
1362
+ return session_dir, account_num, email
1363
+
1364
+ def _profile_matches_backup(
1365
+ self, session_dir: Path, account_num: str, email: str
1366
+ ) -> bool:
1367
+ """Is the profile on the same credential generation as the backup?
1368
+
1369
+ Compared by fingerprint, because that is what identifies a generation;
1370
+ the identity (email/org) is the same across all of them, which is why
1371
+ ``_is_session_valid`` cannot answer this.
1372
+
1373
+ Unknowable answers are TRUE — an unreadable backup or profile is not
1374
+ evidence of a mismatch, and re-bootstrapping on one would throw away a
1375
+ working profile over a read error.
1376
+ """
1377
+ from claude_swap import oauth as _oauth
1378
+
1379
+ profile = read_session_credentials(session_dir)
1380
+ backup = self.switcher.read_account_credentials(account_num, email)
1381
+ if not profile or not backup:
1382
+ return True
1383
+ return _oauth.credential_fingerprint(
1384
+ profile
1385
+ ) == _oauth.credential_fingerprint(backup)
1386
+
1387
+ def _bootstrap(
1388
+ self, session_dir: Path, account_num: str, email: str, org_uuid: str
1389
+ ) -> None:
1390
+ """Seed the session profile from backup storage. Caller holds the lock."""
1391
+ # Checked here, on the login about to be copied, and before anything
1392
+ # of the profile is touched. The consume gate's own check does not
1393
+ # cover every way in: it reports success without reaching it when the
1394
+ # backup moved after the caller's snapshot. Only a certain match
1395
+ # refuses: a live store that cannot be read is no reason to fail a
1396
+ # launch the stored credentials can serve.
1397
+ if self.switcher._live_login_holds(
1398
+ self.switcher.read_account_credentials(account_num, email) or ""
1399
+ ):
1400
+ raise self._live_login_error(account_num)
1401
+
1402
+ # Claude reads the keychain before the plaintext file — a stale hashed
1403
+ # entry from an earlier profile at this path would shadow the seed.
1404
+ delete_macos_keychain_entry(session_dir)
1405
+
1406
+ creds, unreadable = self.switcher._read_account_credentials_ex(
1407
+ account_num, email
1408
+ )
1409
+ if not creds:
1410
+ if unreadable:
1411
+ # Third copy of the switch path's message; same reason not to
1412
+ # send the user to a re-add over a locked Keychain.
1413
+ raise SessionError(
1414
+ f"Account-{account_num}'s backup is in the macOS Keychain "
1415
+ f"but it is unreadable right now (locked or no GUI "
1416
+ f"session). Retry from a GUI terminal; do not re-add."
1417
+ )
1418
+ raise SessionError(
1419
+ f"Account-{account_num} has no stored credentials. "
1420
+ f"Re-add with: cswap --add-account --slot {account_num}"
1421
+ )
1422
+
1423
+ # The pre-lock refresh (see run(): the consume gate must not run
1424
+ # under this lock — its POST is network and the FileLock is
1425
+ # non-reentrant) may have already rotated the backup; the read
1426
+ # above picked that successor up. No POST happens here.
1427
+
1428
+ config_text = self.switcher.read_account_config(account_num, email)
1429
+ try:
1430
+ config_data = json.loads(config_text) if config_text else {}
1431
+ except json.JSONDecodeError:
1432
+ config_data = {}
1433
+ oauth_account = config_data.get("oauthAccount")
1434
+ if not oauth_account:
1435
+ raise SessionError(
1436
+ f"Account-{account_num} has no stored config backup. "
1437
+ f"Re-add with: cswap --add-account --slot {account_num}"
1438
+ )
1439
+
1440
+ session_dir.mkdir(parents=True, exist_ok=True)
1441
+ if sys.platform != "win32":
1442
+ os.chmod(session_dir, 0o700)
1443
+
1444
+ creds_path = session_dir / ".credentials.json"
1445
+ atomic_write_text(creds_path, creds)
1446
+
1447
+ # Merge the identity seed into any existing .claude.json so a
1448
+ # re-bootstrap preserves the profile's own projects/history. The
1449
+ # `theme` key is load-bearing: claude shows onboarding when
1450
+ # `!config.theme || !config.hasCompletedOnboarding`.
1451
+ config_path = session_dir / ".claude.json"
1452
+ existing: dict = {}
1453
+ if config_path.exists():
1454
+ try:
1455
+ existing = json.loads(config_path.read_text(encoding="utf-8")) or {}
1456
+ except (json.JSONDecodeError, OSError):
1457
+ existing = {}
1458
+ existing["oauthAccount"] = oauth_account
1459
+ existing["hasCompletedOnboarding"] = True
1460
+ existing.setdefault("theme", config_data.get("theme") or "dark")
1461
+ atomic_write_text(config_path, json.dumps(existing, indent=2))
1462
+
1463
+ self._logger.info(
1464
+ f"Bootstrapped session profile for account {account_num} at {session_dir}"
1465
+ )
1466
+
1467
+ @staticmethod
1468
+ def _live_login_error(account_num: str) -> SessionError:
1469
+ """The refusal to copy the live login into a session profile: two
1470
+ Claude Codes on one refresh token invalidate each other."""
1471
+ return SessionError(
1472
+ f"Account-{account_num}'s stored login is the live login right "
1473
+ f"now, so a session would be a second copy of the same login. "
1474
+ f"Run 'cswap --switch-to {account_num}' so cswap treats it as the "
1475
+ f"active account, then start claude normally."
1476
+ )
1477
+
1478
+ @staticmethod
1479
+ def _has_refresh_token(creds: str) -> bool:
1480
+ try:
1481
+ return bool(json.loads(creds).get("claudeAiOauth", {}).get("refreshToken"))
1482
+ except (json.JSONDecodeError, AttributeError):
1483
+ return True # unknown shape — let the refresh attempt decide
1484
+
1485
+ def _cleanup_failed_session(self, session_dir: Path) -> None:
1486
+ # Keychain first: claude may have partially migrated the seed, and the
1487
+ # hashed service name can't be recomputed once the dir is gone. The
1488
+ # stale marker is a sibling, so rmtree does not take it.
1489
+ delete_macos_keychain_entry(session_dir)
1490
+ shutil.rmtree(session_dir, ignore_errors=True)
1491
+ clear_session_stale(session_dir)
1492
+
1493
+ # -- validation ------------------------------------------------------
1494
+
1495
+ def _session_validity(
1496
+ self, session_dir: Path, email: str, org_uuid: str
1497
+ ) -> str:
1498
+ """``"valid"`` / ``"invalid"`` / ``"unknown"`` / ``"unreachable"``.
1499
+
1500
+ Local check only (`claude auth status` makes no API call): a revoked
1501
+ but unexpired token still passes and fails on first real use.
1502
+
1503
+ The last two are both "the PROBE failed, not the profile", and neither
1504
+ may share a return value with ``"invalid"`` — the caller that acts on
1505
+ ``"invalid"`` deletes the profile's Keychain entry and rmtree's the
1506
+ directory, and a probe we could not run is not evidence about the
1507
+ profile. They are split because REUSE wants opposite answers:
1508
+
1509
+ ``"unknown"`` — the probe ran and did not answer (timeout, output that
1510
+ will not parse). Nothing suggests the profile is bad, so reuse leans
1511
+ valid; on a loaded machine `claude`'s cold start exceeds the 10s
1512
+ timeout and forcing a re-bootstrap there fails a launch that would
1513
+ have worked (upstream #224/#225).
1514
+
1515
+ ``"unreachable"`` — `claude` could not be spawned at all. Reuse leans
1516
+ invalid: a binary we cannot run cannot serve the session either way,
1517
+ so the honest outcome is the bootstrap path and its "check that
1518
+ `claude` is on PATH" error, not a silent reuse.
1519
+ """
1520
+ if not session_dir.is_dir():
1521
+ return "invalid"
1522
+ # On Windows `claude` is a `.cmd` shim, and a bare "claude" passed to
1523
+ # subprocess won't resolve it (PATHEXT isn't applied) — it raises
1524
+ # FileNotFoundError. `shutil.which` finds the shim; when it finds
1525
+ # nothing at all the run below still raises, and that is "unknown".
1526
+ claude_bin = shutil.which("claude") or "claude"
1527
+ try:
1528
+ result = spawn.run(
1529
+ [claude_bin, "auth", "status", "--json"],
1530
+ env=_probe_env(session_dir),
1531
+ capture_output=True,
1532
+ text=True,
1533
+ timeout=_AUTH_STATUS_TIMEOUT,
1534
+ )
1535
+ except subprocess.TimeoutExpired:
1536
+ # The verdict layer answers what the PROBE established, and a
1537
+ # timeout established nothing. Upstream's artifact fallback is a
1538
+ # REUSE judgement, not a verdict, so it lives in
1539
+ # `_is_session_valid` where its answer is what gets consumed —
1540
+ # putting it here would make "the probe timed out" and "the
1541
+ # profile is bad" the same value again, which is the conflation
1542
+ # this whole tri-state exists to undo.
1543
+ return "unknown"
1544
+ except OSError:
1545
+ return "unreachable"
1546
+ if result.returncode != 0:
1547
+ return "invalid"
1548
+ try:
1549
+ status = json.loads(result.stdout)
1550
+ except json.JSONDecodeError:
1551
+ return "unknown"
1552
+ if not isinstance(status, dict):
1553
+ return "unknown"
1554
+ if status.get("loggedIn") is not True:
1555
+ return "invalid"
1556
+ # Verified against claude 2.1.175; an env API key reports a different
1557
+ # method, and the probe env already drops those vars anyway.
1558
+ if status.get("authMethod") != "claude.ai":
1559
+ return "invalid"
1560
+ if status.get("email") != email:
1561
+ return "invalid"
1562
+ # Lenient org check: only when both sides have a value, so schema
1563
+ # drift degrades to email-only validation instead of false negatives.
1564
+ status_org = status.get("orgId")
1565
+ if status_org and org_uuid and status_org != org_uuid:
1566
+ return "invalid"
1567
+ return "valid"
1568
+
1569
+ def _is_session_valid(self, session_dir: Path, email: str, org_uuid: str) -> bool:
1570
+ """Whether the profile is usable as far as we can tell.
1571
+
1572
+ Reuse-shaped view of :meth:`_session_validity`, and best-effort by
1573
+ design. ``"unknown"`` — the probe ran and did not answer — is decided
1574
+ from local artifacts instead of blanket-True, because "the probe timed
1575
+ out" is not by itself a reason to reuse: credential material must not
1576
+ be definitely absent (keychain-aware — claude migrates a macOS
1577
+ profile's credential into the keychain and deletes the plaintext seed,
1578
+ while stale invalidation deletes both) and the recorded identity must
1579
+ not have drifted (in-session /login to another account). Anything
1580
+ subtler still fails on first real use.
1581
+
1582
+ ``"unreachable"`` answers False without consulting artifacts: the
1583
+ question there is not whether the profile holds a credential but
1584
+ whether `claude` can be run at all, and no local file answers that.
1585
+
1586
+ Callers that DESTROY on a negative must use the full verdict instead.
1587
+ For them the difference between "invalid" and "could not tell" is the
1588
+ difference between a correct cleanup and deleting a working profile,
1589
+ and this boolean cannot express it.
1590
+ """
1591
+ verdict = self._session_validity(session_dir, email, org_uuid)
1592
+ if verdict == "unknown":
1593
+ return _artifacts_say_usable(session_dir, email, org_uuid)
1594
+ return verdict == "valid"
1595
+
1596
+ # -- sharing ---------------------------------------------------------
1597
+
1598
+ def _sync_sharing(
1599
+ self, session_dir: Path, share: bool, share_history: bool = False
1600
+ ) -> None:
1601
+ """Mirror shared items from ~/.claude into the profile (or undo it).
1602
+
1603
+ ``share`` governs SHARED_ITEMS (customizations) and the mcpServers
1604
+ mirror (see ``_sync_mcp_servers`` — its --no-share removal is gated
1605
+ on the adoption marker); ``share_history`` governs HISTORY_ITEMS
1606
+ (conversation history) — independent concerns, so ``--no-share``
1607
+ alone gives a bare profile that still has the unified history. Both
1608
+ arrive here already decided (``_resolve_share_history`` for history).
1609
+ Idempotent; runs on every launch. Deliberately sources from the
1610
+ default ``~/.claude`` (not ``get_claude_config_home()``): sharing
1611
+ always mirrors the default profile, even when ``CLAUDE_CONFIG_DIR``
1612
+ is set in the invoking environment. File/dir sharing is lock-free on
1613
+ the reuse path — concurrent runs with different flags are last-writer-
1614
+ wins and self-heal on the next launch. The MCP mirror takes Claude's
1615
+ config lock, and only when it needs to write; merging a profile's own
1616
+ history into ``~/.claude`` takes ``MIGRATION_LOCK``.
1617
+ """
1618
+ if not session_dir.is_dir():
1619
+ return
1620
+ self._sync_mcp_servers(session_dir, share)
1621
+ self._sync_items(
1622
+ session_dir,
1623
+ (SHARED_ITEMS if share else ())
1624
+ + (HISTORY_ITEMS if share_history else ()),
1625
+ )
1626
+
1627
+ def _sync_items(
1628
+ self,
1629
+ session_dir: Path,
1630
+ active_items: tuple[str, ...],
1631
+ scope: tuple[str, ...] = SHARED_ITEMS + HISTORY_ITEMS,
1632
+ ) -> None:
1633
+ """Link (or copy) ``active_items`` into the profile; undo the others.
1634
+
1635
+ ``scope`` is what this call decides about. An entry in it that is not
1636
+ active is removed, and a managed entry outside it stays exactly as it
1637
+ is, on disk and in the manifest. Everything by default; the fast
1638
+ path passes the history items alone (``_history_on_the_fast_path``).
1639
+ """
1640
+ # Reset per call: _prepare_history_share accumulates into this as it
1641
+ # runs (once per HISTORY_ITEMS entry), so a launch with nothing to
1642
+ # migrate must not report counts left over from a previous one.
1643
+ self._last_merge_counts = (0, 0, None)
1644
+ self._deferral_reported = False
1645
+ self._own_history_found = False
1646
+ self._unlinkable_reported = False
1647
+ source_root = Path.home() / ".claude"
1648
+ manifest_path = session_dir / SHARE_MANIFEST
1649
+ managed = self._read_manifest(manifest_path)
1650
+ out_of_scope = [name for name in managed if name not in scope]
1651
+ self._clear_staged_links(session_dir, source_root, scope)
1652
+
1653
+ # A flag turned off since last launch: remove the links we created
1654
+ # for it (never plain files/dirs the user accumulated themselves).
1655
+ # For history items that holds even when the manifest claims them:
1656
+ # a stale manifest (lock-free launches race) must never be able to
1657
+ # delete real conversation history — only ever unlink symlinks.
1658
+ for name in managed:
1659
+ if name in scope and name not in active_items:
1660
+ dest = session_dir / name
1661
+ if name in HISTORY_ITEMS and dest.exists() and not is_link(dest):
1662
+ continue
1663
+ self._remove_managed(dest)
1664
+ if not active_items and not out_of_scope:
1665
+ manifest_path.unlink(missing_ok=True)
1666
+ return
1667
+
1668
+ new_managed: list[str] = list(out_of_scope)
1669
+
1670
+ for name in active_items:
1671
+ src = source_root / name
1672
+ dest = session_dir / name
1673
+ # Whether a link can be made here: always off Windows; on Windows
1674
+ # a junction for a directory (any user), a symlink for a file
1675
+ # (Developer Mode or an elevated terminal). Decided before the
1676
+ # history merge below, which must never move a profile's history
1677
+ # into a tree the profile then cannot be linked to.
1678
+ linkable = self._can_link(name, session_dir, source_root)
1679
+
1680
+ # Link to the fully resolved target. When ~/.claude/<name> is itself
1681
+ # a symlink (a dotfiles setup), linking to the unresolved path makes
1682
+ # a link-to-a-link, and Claude Code's atomic settings write — which
1683
+ # resolves only one hop — renames its temp file over the intermediate
1684
+ # link, silently replacing it with a regular file
1685
+ # (anthropics/claude-code#78162).
1686
+ link_target = src.resolve() if src.is_symlink() else src
1687
+
1688
+ if name in HISTORY_ITEMS and not linkable:
1689
+ # History is shared by link or not at all. A link already
1690
+ # here keeps working — only making one takes the privilege
1691
+ # — so a profile linked in an elevated terminal, or before
1692
+ # Developer Mode was turned off, stays shared.
1693
+ if is_link(dest) and link_points_at(dest, link_target):
1694
+ new_managed.append(name)
1695
+ continue
1696
+ self._report_history_unlinkable(name)
1697
+ continue
1698
+
1699
+ if name in HISTORY_ITEMS and not self._prepare_history_share(
1700
+ src, dest, session_dir
1701
+ ):
1702
+ continue
1703
+
1704
+ if not src.exists():
1705
+ # Source vanished (or never existed): prune our own entry.
1706
+ if name in managed:
1707
+ self._remove_managed(dest)
1708
+ continue
1709
+
1710
+ if is_link(dest):
1711
+ in_place = link_points_at(dest, link_target)
1712
+ ours = in_place or name in managed or link_points_at(dest, src)
1713
+ if not ours:
1714
+ # A link cswap never made, leading somewhere else: the
1715
+ # user's own redirect, left alone like a directory of
1716
+ # their own — and what it leads to is never touched.
1717
+ print(
1718
+ dimmed(
1719
+ f"Not sharing {name}: the session profile already "
1720
+ "has its own link."
1721
+ )
1722
+ )
1723
+ continue
1724
+ if in_place:
1725
+ # Ours, or made by hand to the same place: adopted. Kept
1726
+ # even where no link could be made now (Windows without
1727
+ # the privilege): only making one takes the privilege.
1728
+ new_managed.append(name)
1729
+ continue
1730
+ # Ours, but not pointing where it should: at the intermediate
1731
+ # symlink of a dotfiles setup, or at a ~/.claude that moved.
1732
+ # Remade below — as a link where one can be made, else as a
1733
+ # copy.
1734
+ try:
1735
+ remove_link(dest)
1736
+ except OSError:
1737
+ continue
1738
+ elif dest.exists() and name not in managed:
1739
+ # Pre-existing user data in the profile — never touch it.
1740
+ print(
1741
+ dimmed(
1742
+ f"Not sharing {name}: the session profile already has "
1743
+ "its own copy."
1744
+ )
1745
+ )
1746
+ continue
1747
+
1748
+ try:
1749
+ if dest.exists():
1750
+ self._remove_managed(dest)
1751
+ if not linkable:
1752
+ self._copy_item(src, dest)
1753
+ else:
1754
+ try:
1755
+ self._make_link(link_target, dest)
1756
+ except OSError as e:
1757
+ if name in HISTORY_ITEMS:
1758
+ raise # history is shared by link or not at all
1759
+ # The probe said yes and this link still failed (a
1760
+ # target the volume will not link to, say). The copy
1761
+ # of old, refreshed on every launch, beats nothing.
1762
+ self._logger.warning(
1763
+ f"Could not link {name} into the session ({e}); "
1764
+ "copying it instead."
1765
+ )
1766
+ self._copy_item(src, dest)
1767
+ except OSError as e:
1768
+ self._logger.warning(f"Failed to share {name} into session: {e}")
1769
+ continue
1770
+ new_managed.append(name)
1771
+
1772
+ # Anything we managed before but no longer created gets removed above;
1773
+ # write the manifest atomically so a concurrent reader never sees a
1774
+ # truncated file.
1775
+ self._write_manifest(manifest_path, new_managed)
1776
+ self._report_quarantine()
1777
+ self._report_sharing_is_the_default()
1778
+
1779
+ def _clear_staged_links(
1780
+ self, session_dir: Path, source_root: Path, scope: tuple[str, ...]
1781
+ ) -> None:
1782
+ """Remove a staging link that an interrupted launch left behind.
1783
+
1784
+ ``_migrate_under_lock`` makes the link that will replace a profile's
1785
+ history under a staging name first and renames it into place last.
1786
+ A launch killed in between leaves that link there, and nothing else
1787
+ looks at the staging name: the next launch links ``dest`` afresh and
1788
+ would walk past the leftover forever. It is a link and holds nothing,
1789
+ so removing it costs nothing — except that a peer launch may be in
1790
+ the middle of a migration with its own staging link live. So the
1791
+ lock every migration holds is taken here too, briefly: a busy lock
1792
+ means the "leftover" may be someone's work in progress, and it is
1793
+ left for the next launch. Nothing but a link is ever removed.
1794
+ """
1795
+ leftovers = [
1796
+ session_dir / (name + _STAGED_LINK_SUFFIX)
1797
+ for name in HISTORY_ITEMS
1798
+ if name in scope
1799
+ ]
1800
+ if not any(is_link(staged) for staged in leftovers):
1801
+ return
1802
+ try:
1803
+ _mkdir_private(source_root)
1804
+ with FileLock(
1805
+ source_root / MIGRATION_LOCK, timeout=_STAGED_CLEANUP_LOCK_TIMEOUT
1806
+ ):
1807
+ for staged in leftovers:
1808
+ if is_link(staged):
1809
+ remove_link(staged)
1810
+ self._logger.info(
1811
+ f"Removed the staging link an interrupted launch "
1812
+ f"left at {staged}"
1813
+ )
1814
+ except (LockError, OSError) as e:
1815
+ self._logger.warning(
1816
+ f"Could not clear a staging link in {session_dir}: {e}"
1817
+ )
1818
+
1819
+ def _can_link(self, name: str, session_dir: Path, source_root: Path) -> bool:
1820
+ """Whether ``name`` can be shared into ``session_dir`` by link.
1821
+
1822
+ Always off Windows. On Windows a directory takes a junction, which
1823
+ needs no privilege but a volume with reparse points and a target
1824
+ Windows accepts; a file takes a symlink, which needs Developer Mode
1825
+ or an elevated terminal. Both are probed once per process in the
1826
+ profile directory itself — the junction to ``source_root``, the
1827
+ parent of every target — so the answer holds for the link made a
1828
+ moment later in the same place. A probe is still not the link: the
1829
+ callers keep a copy fallback and a link-before-merge order for the
1830
+ case where the link itself fails.
1831
+ """
1832
+ if self.switcher.platform != Platform.WINDOWS:
1833
+ return True
1834
+ if name in _DIR_ITEMS:
1835
+ return can_junction(session_dir, source_root)
1836
+ return can_symlink(session_dir)
1837
+
1838
+ @staticmethod
1839
+ def _copy_item(src: Path, dest: Path) -> None:
1840
+ """The copy of old: ``dest`` becomes a snapshot of ``src``."""
1841
+ if src.is_dir():
1842
+ shutil.copytree(src, dest)
1843
+ else:
1844
+ shutil.copy2(src, dest)
1845
+
1846
+ def _make_link(self, target: Path, dest: Path) -> None:
1847
+ """Put the link for ``target`` at ``dest``: a symlink, except that a
1848
+ directory on Windows gets a junction (``fsutil.make_dir_link``)."""
1849
+ if self.switcher.platform == Platform.WINDOWS and target.is_dir():
1850
+ make_dir_link(target, dest)
1851
+ else:
1852
+ dest.symlink_to(target)
1853
+
1854
+ def _report_history_unlinkable(self, name: str) -> None:
1855
+ """Say that ``name`` stays the account's own: no link can be made here.
1856
+
1857
+ The common case is Windows without Developer Mode: ``projects/`` is
1858
+ shared through a junction, which needs nothing, but a file can only
1859
+ be linked with a symlink, and a copy of ``history.jsonl`` would fork
1860
+ the prompt history. Printed once per launch, as a warning when
1861
+ sharing was asked for (the flag, or the setting written by hand) and
1862
+ dimmed when only the built-in default could not be applied; the log
1863
+ gets every item.
1864
+ """
1865
+ self._logger.warning(
1866
+ f"share-history: {name} cannot be linked in this profile "
1867
+ "(Windows without a symlink privilege); the account keeps its own."
1868
+ )
1869
+ if self._unlinkable_reported:
1870
+ return
1871
+ self._unlinkable_reported = True
1872
+ asked = (
1873
+ self._share_history_asked
1874
+ or explicit_share_history(self.switcher.backup_dir) is True
1875
+ )
1876
+ line = f"share-history: {name} stays per-account on this Windows machine."
1877
+ if asked:
1878
+ warning(line)
1879
+ else:
1880
+ print(dimmed(line))
1881
+ if name in _DIR_ITEMS:
1882
+ print(
1883
+ dimmed(
1884
+ " A directory junction could not be made in the profile "
1885
+ "folder (not an NTFS volume?) — see the log."
1886
+ )
1887
+ )
1888
+ else:
1889
+ print(
1890
+ dimmed(
1891
+ " Windows lets cswap link a file only with Developer Mode "
1892
+ "on (Settings > System > For developers) or in an elevated "
1893
+ "terminal. Conversations (projects/) are shared through a "
1894
+ "junction, which needs neither."
1895
+ )
1896
+ )
1897
+
1898
+ def _sync_mcp_servers(self, session_dir: Path, share: bool) -> None:
1899
+ """Mirror the default profile's user-scope ``mcpServers`` (issue #139).
1900
+
1901
+ Pure mirror: the default profile is the single source of truth, so
1902
+ adds, edits, and deletions all propagate, and MCP changes made inside
1903
+ a session are overwritten the next time cswap prepares the profile.
1904
+ Nothing ever flows back into the default config, and per-project
1905
+ (``projects[…].mcpServers``) entries are untouched on both sides.
1906
+
1907
+ ``share=False`` removes the mirrored key — but only from profiles
1908
+ that have adopted mirroring (MCP_MIRROR_MARKER), so ``--no-share``
1909
+ can never destroy pre-feature session-local definitions. The first
1910
+ mirror on an unadopted profile stashes any definitions it would
1911
+ displace into MCP_DISPLACED_STASH (write-once) before resetting.
1912
+
1913
+ Fail-open throughout: an unreadable or malformed file on either side,
1914
+ a symlinked target, or a contended lock leaves the profile untouched
1915
+ and never blocks the launch. The adopted in-sync steady state takes
1916
+ no lock and writes nothing; first adoption always goes through the
1917
+ lock so the marker can never certify a state a concurrent claude
1918
+ changed between the read and the touch.
1919
+ """
1920
+ config_path = session_dir / ".claude.json"
1921
+ marker = session_dir / MCP_MIRROR_MARKER
1922
+
1923
+ if share:
1924
+ source = self._read_mcp_source()
1925
+ if source is None:
1926
+ return
1927
+ elif marker.exists():
1928
+ source = {} # remove what we mirrored; restored on a share run
1929
+ else:
1930
+ return # never adopted: --no-share must not touch local data
1931
+
1932
+ # Type-check before reading: reading a FIFO would hang the launch,
1933
+ # and a symlinked target must never be written through or replaced.
1934
+ if not config_path.exists():
1935
+ return # bootstrap/validation owns a missing config
1936
+ if config_path.is_symlink() or not config_path.is_file():
1937
+ self._logger.warning(
1938
+ f"Not syncing MCP servers: {config_path} is not a regular file."
1939
+ )
1940
+ return
1941
+
1942
+ existing = self._load_json_object(config_path)
1943
+ if existing is None:
1944
+ return # bootstrap/validation owns a broken config
1945
+ target = existing.get(MCP_KEY, {})
1946
+ if not isinstance(target, dict):
1947
+ self._logger.warning(
1948
+ f"Not syncing MCP servers: the profile's {MCP_KEY} is not "
1949
+ "an object."
1950
+ )
1951
+ return
1952
+ if target == source and (not share or marker.exists()):
1953
+ return
1954
+
1955
+ # The same lock a claude running in this profile takes for its own
1956
+ # .claude.json writes (CLAUDE_CONFIG_DIR is the session dir), so the
1957
+ # splice below never interleaves with its config writes.
1958
+ lock_dir = config_path.parent / (config_path.name + ".lock")
1959
+ try:
1960
+ with proper_lockfile(lock_dir):
1961
+ # Re-read both sides: a writer that waited here must not
1962
+ # clobber a newer mirror with its stale pre-lock snapshot.
1963
+ if share:
1964
+ source = self._read_mcp_source()
1965
+ if source is None:
1966
+ return
1967
+ if config_path.is_symlink() or not config_path.is_file():
1968
+ return
1969
+ existing = self._load_json_object(config_path)
1970
+ if existing is None:
1971
+ return
1972
+ target = existing.get(MCP_KEY, {})
1973
+ if not isinstance(target, dict):
1974
+ return
1975
+ if target == source:
1976
+ if share:
1977
+ self._ensure_mcp_marker(marker)
1978
+ return
1979
+ if share and not marker.exists():
1980
+ displaced = {
1981
+ name: value
1982
+ for name, value in target.items()
1983
+ if name not in source or source[name] != value
1984
+ }
1985
+ if displaced and not self._stash_displaced_mcp(
1986
+ session_dir, displaced
1987
+ ):
1988
+ return # never destroy the only copy
1989
+ if source:
1990
+ existing[MCP_KEY] = source
1991
+ else:
1992
+ # Claude itself strips default-valued keys; match it.
1993
+ existing.pop(MCP_KEY, None)
1994
+ try:
1995
+ atomic_write_json(config_path, existing)
1996
+ except OSError as e:
1997
+ self._logger.warning(f"Could not sync MCP servers: {e}")
1998
+ return
1999
+ if share:
2000
+ # Only after a successful write: an unadopted profile
2001
+ # whose marker fails to land simply retries next launch,
2002
+ # by then already in sync so nothing can be mis-stashed.
2003
+ self._ensure_mcp_marker(marker)
2004
+ except (ClaudeCodeLockTimeout, OSError) as e:
2005
+ # OSError covers lock-machinery failures (mkdir on a read-only
2006
+ # or full filesystem); everything inside handles its own.
2007
+ self._logger.warning(
2008
+ f"Could not sync MCP servers ({e}) — skipping this launch."
2009
+ )
2010
+
2011
+ @staticmethod
2012
+ def _read_mcp_source() -> dict | None:
2013
+ """The default profile's user-scope mcpServers, or None if unusable.
2014
+
2015
+ ``{}`` and ``None`` are distinct: a readable config without the key
2016
+ genuinely has no user servers (``{}`` propagates the removal), while
2017
+ a missing/corrupt config or a non-dict key returns ``None`` so the
2018
+ caller leaves the profile untouched. Reads the default-home path
2019
+ (ignoring CLAUDE_CONFIG_DIR — a nested `cswap run` must not source
2020
+ from another session); no lock needed, claude's writes are atomic.
2021
+ """
2022
+ config = SessionManager._load_json_object(get_default_global_config_path())
2023
+ if config is None:
2024
+ return None
2025
+ value = config.get(MCP_KEY, {})
2026
+ return value if isinstance(value, dict) else None
2027
+
2028
+ @staticmethod
2029
+ def _load_json_object(path: Path) -> dict | None:
2030
+ # ValueError covers both JSONDecodeError and UnicodeDecodeError.
2031
+ try:
2032
+ data = json.loads(path.read_text(encoding="utf-8"))
2033
+ except (OSError, ValueError):
2034
+ return None
2035
+ return data if isinstance(data, dict) else None
2036
+
2037
+ def _ensure_mcp_marker(self, marker: Path) -> None:
2038
+ if marker.exists():
2039
+ return
2040
+ try:
2041
+ marker.touch()
2042
+ except OSError as e:
2043
+ self._logger.warning(f"Could not write {marker.name}: {e}")
2044
+
2045
+ def _stash_displaced_mcp(self, session_dir: Path, displaced: dict) -> bool:
2046
+ """Save definitions the first mirror would displace; False aborts it.
2047
+
2048
+ Write-once: a stash left by an earlier interrupted adoption is the
2049
+ pre-feature data and must not be overwritten with mirror noise. But
2050
+ only a *valid* stash counts as a saved copy — a directory, symlink,
2051
+ or unrelated file squatting on the name must block the reset, not
2052
+ green-light it.
2053
+ """
2054
+ stash = session_dir / MCP_DISPLACED_STASH
2055
+ if stash.is_symlink() or stash.exists():
2056
+ if self._is_valid_stash(stash):
2057
+ return True
2058
+ self._logger.warning(
2059
+ f"{stash.name} exists but is not a valid stash; leaving "
2060
+ "the profile's MCP servers in place."
2061
+ )
2062
+ return False
2063
+ try:
2064
+ atomic_write_json(
2065
+ stash, {"schemaVersion": 1, MCP_KEY: displaced}
2066
+ )
2067
+ except OSError as e:
2068
+ self._logger.warning(
2069
+ f"Could not stash the profile's MCP servers ({e}); "
2070
+ "leaving them in place."
2071
+ )
2072
+ return False
2073
+ print(
2074
+ dimmed(
2075
+ "Session MCP servers now mirror your default profile; the "
2076
+ f"profile's previous definitions were saved to {stash.name}."
2077
+ )
2078
+ )
2079
+ return True
2080
+
2081
+ @staticmethod
2082
+ def _is_valid_stash(stash: Path) -> bool:
2083
+ if stash.is_symlink() or not stash.is_file():
2084
+ return False
2085
+ data = SessionManager._load_json_object(stash)
2086
+ return data is not None and isinstance(data.get(MCP_KEY), dict)
2087
+
2088
+ def _prepare_history_share(
2089
+ self, src: Path, dest: Path, session_dir: Path
2090
+ ) -> bool:
2091
+ """Make a history item linkable; returns False to skip it this launch.
2092
+
2093
+ Handles the two ways a history item differs from a plain shared item:
2094
+ the profile may already hold real history that must survive (merged
2095
+ into ``~/.claude``, never discarded — the generic loop would just
2096
+ refuse), and the share source may not exist yet on a fresh install
2097
+ (created empty so there is something to link). Real history is merged
2098
+ even when the manifest claims the entry is managed: a stale manifest
2099
+ (lock-free launches race) must never let the generic loop delete it.
2100
+
2101
+ A merge runs under ``MIGRATION_LOCK`` together with everything it
2102
+ depends on: the path and liveness checks are read again inside the
2103
+ lock, and the link is installed before it is released (see
2104
+ ``_migrate_under_lock``). A profile with nothing to merge never
2105
+ takes it.
2106
+ """
2107
+ if dest.exists() and not is_link(dest):
2108
+ # Real per-account history: the profile kept its own while
2109
+ # sharing was off (before it became the default, or by choice).
2110
+ self._own_history_found = True
2111
+ # Merging moves files out from under any claude still running in
2112
+ # this profile, so only migrate when the profile is quiescent.
2113
+ # This first look is a cheap early out — a profile that is always
2114
+ # busy should not queue on the lock every launch for a merge that
2115
+ # cannot run. The look that counts is taken under the lock.
2116
+ if not profile_is_quiescent(session_dir):
2117
+ self._report_deferral(session_dir, dest)
2118
+ return False
2119
+ try:
2120
+ # The lock sits beside the shared history, so that directory
2121
+ # has to exist first — and with Claude Code's own mode, not
2122
+ # the default one FileLock would create it with.
2123
+ _mkdir_private(src.parent)
2124
+ with FileLock(
2125
+ src.parent / MIGRATION_LOCK,
2126
+ timeout=_MIGRATION_LOCK_TIMEOUT,
2127
+ ):
2128
+ if not self._migrate_under_lock(src, dest, session_dir):
2129
+ return False
2130
+ except LockError:
2131
+ # A peer is still merging — the timeout means "still busy",
2132
+ # not "broken", so this degrades exactly like every other
2133
+ # deferral instead of aborting the launch.
2134
+ self._report_deferral(session_dir, dest, lock_busy=True)
2135
+ return False
2136
+ except OSError as e:
2137
+ # The lock file could not be created or opened (a read-only
2138
+ # ~/.claude, say). No lock means no safe merge, and a history
2139
+ # problem must not cost the launch.
2140
+ self._logger.warning(
2141
+ f"Could not lock {src.parent} to merge {dest.name}: {e}"
2142
+ )
2143
+ print(
2144
+ dimmed(
2145
+ f"Not sharing {dest.name}: the shared history could "
2146
+ "not be locked (see log)."
2147
+ )
2148
+ )
2149
+ return False
2150
+ return self._seed_history_source(src, dest)
2151
+
2152
+ def _seed_history_source(self, src: Path, dest: Path) -> bool:
2153
+ """Create an empty share target when ``~/.claude`` has none yet."""
2154
+ if src.exists():
2155
+ return True
2156
+ # Fresh ~/.claude (or first run): seed an empty share target so
2157
+ # there is something to link.
2158
+ try:
2159
+ # 0o600/0o700 to match Claude Code's own modes for history
2160
+ # data — its mode= applies only at creation, so a loose seed
2161
+ # here would stay world-readable forever.
2162
+ if dest.name.endswith(".jsonl"):
2163
+ src.parent.mkdir(parents=True, exist_ok=True)
2164
+ src.touch(mode=0o600)
2165
+ else:
2166
+ _mkdir_private(src)
2167
+ except OSError as e:
2168
+ self._logger.warning(f"Could not create {src}: {e}")
2169
+ return False
2170
+ return True
2171
+
2172
+ def _migrate_under_lock(
2173
+ self, src: Path, dest: Path, session_dir: Path
2174
+ ) -> bool:
2175
+ """Merge the profile's history into ``src`` and link it, as one step.
2176
+
2177
+ Runs with ``MIGRATION_LOCK`` held. That lock is keyed on the shared
2178
+ destination — it is a file in it — rather than on the profile or the
2179
+ backup store, because the destination is what two migrations contend
2180
+ for: with a lock per profile (or per store), two DIFFERENT profiles
2181
+ can each find a shared path missing, and the second move lands on
2182
+ top of the first. It is its own file, so it cannot deadlock against
2183
+ ``setup_session``'s bootstrap lock — still held across this call on
2184
+ some paths, and never taken from in here.
2185
+
2186
+ Nothing decided before the wait is trusted. The peer we queued
2187
+ behind may have merged this very item (``dest`` is gone: merging it
2188
+ raises FileNotFoundError and reports a peer's success as our
2189
+ failure), or linked it (``dest.is_dir()`` follows the link, so the
2190
+ walk would file every shared transcript against itself), or a claude
2191
+ may have started in the profile. Each is read again here.
2192
+
2193
+ The link goes in before the lock is released, so no peer ever finds
2194
+ the profile in between — history moved out, nothing linked yet — and
2195
+ takes that for a profile with nothing to share.
2196
+
2197
+ And it is made before the merge, under a staging name beside the
2198
+ history — the real kind, to the real target, in the real directory —
2199
+ and only renamed into place once the merge is done. A probe that
2200
+ said yes is not the link itself: a link that cannot be made is found
2201
+ out while the profile's history is still exactly where it was.
2202
+ """
2203
+ if not dest.exists() or is_link(dest):
2204
+ return True # a peer finished this item; the generic loop links
2205
+ if not profile_is_quiescent(session_dir):
2206
+ self._report_deferral(session_dir, dest)
2207
+ return False
2208
+ if not self._seed_history_source(src, dest):
2209
+ print(
2210
+ dimmed(
2211
+ f"Not sharing {dest.name}: {src} could not be created "
2212
+ "(see log)."
2213
+ )
2214
+ )
2215
+ return False
2216
+ # The same target the generic loop links to (see its note on a
2217
+ # ~/.claude entry that is itself a symlink).
2218
+ link_target = src.resolve() if src.is_symlink() else src
2219
+ staged = dest.with_name(dest.name + _STAGED_LINK_SUFFIX)
2220
+ try:
2221
+ if is_link(staged):
2222
+ remove_link(staged) # left by an interrupted launch
2223
+ elif staged.exists():
2224
+ raise OSError(f"{staged} exists and is not a link")
2225
+ self._make_link(link_target, staged)
2226
+ except OSError as e:
2227
+ self._logger.warning(f"Could not link {dest.name} into the session: {e}")
2228
+ print(
2229
+ dimmed(
2230
+ f"Not sharing {dest.name}: it could not be linked here "
2231
+ "(see log) — the account keeps its own."
2232
+ )
2233
+ )
2234
+ return False
2235
+ try:
2236
+ self._merge_history_into_source(src, dest)
2237
+ except (OSError, ValueError) as e:
2238
+ # ValueError covers UnicodeDecodeError: a byte-corrupt history
2239
+ # file is "nothing readable to merge", and losing a launch to a
2240
+ # stray byte in ~/.claude/history.jsonl would strand every
2241
+ # account that has not migrated yet.
2242
+ self._discard_staged_link(staged)
2243
+ self._logger.warning(f"Could not merge {dest.name} into {src}: {e}")
2244
+ print(
2245
+ dimmed(
2246
+ f"Not sharing {dest.name}: merging the profile's "
2247
+ "existing history failed (see log)."
2248
+ )
2249
+ )
2250
+ return False
2251
+ try:
2252
+ # The merge has emptied and removed ``dest``; the link slides
2253
+ # into its place by rename, which moves the link, not its target.
2254
+ replace_with_retry(staged, dest)
2255
+ except OSError as rename_error:
2256
+ # The link beside it stands, so making one is possible here; the
2257
+ # rename is what failed (a hold on the directory, say). One more
2258
+ # try, made at ``dest`` directly, before the launch goes on with
2259
+ # the merged history in ~/.claude and the profile unlinked until
2260
+ # the next launch, which links it afresh.
2261
+ try:
2262
+ self._make_link(link_target, dest)
2263
+ except OSError as e:
2264
+ self._discard_staged_link(staged)
2265
+ self._logger.warning(
2266
+ f"Failed to share {dest.name} into session: {rename_error}; "
2267
+ f"then {e}"
2268
+ )
2269
+ print(
2270
+ dimmed(
2271
+ f"Merged the profile's existing {dest.name} into {src}, "
2272
+ "but linking it back failed (see log) — retrying on "
2273
+ "the next launch."
2274
+ )
2275
+ )
2276
+ return False
2277
+ self._discard_staged_link(staged)
2278
+ print(
2279
+ dimmed(
2280
+ f"Merged the profile's existing {dest.name} into "
2281
+ f"{src} — conversation history is now shared."
2282
+ )
2283
+ )
2284
+ return True
2285
+
2286
+ def _discard_staged_link(self, staged: Path) -> None:
2287
+ """Best effort: a staging link that will not be used must not linger."""
2288
+ try:
2289
+ remove_link(staged)
2290
+ except OSError as e:
2291
+ self._logger.warning(f"Could not remove {staged}: {e}")
2292
+
2293
+ def _report_deferral(
2294
+ self, session_dir: Path, dest: Path, lock_busy: bool = False
2295
+ ) -> None:
2296
+ """Explain a skipped migration loudly enough to be noticed.
2297
+
2298
+ The old one-line dimmed print was scrolled away by Claude's startup
2299
+ banner and never logged, so a profile could sit unshared for days
2300
+ with sharing asked for on every launch and no visible signal. Printed
2301
+ once per launch: both history items defer for the same reason, and a
2302
+ second copy of the block only buries the first.
2303
+
2304
+ ``lock_busy`` is the one deferral that has nothing to do with this
2305
+ profile's own sessions: a peer cswap launch held ``MIGRATION_LOCK``
2306
+ past the timeout, merging some profile's history (not necessarily
2307
+ this one's) into the same shared tree.
2308
+ """
2309
+ account = session_dir.name
2310
+ slot = account.split("-")[0]
2311
+ blockers: list[ClaudeSession] = []
2312
+ if lock_busy:
2313
+ why = "the migration lock is held by a peer process"
2314
+ else:
2315
+ blockers, _ = scan_live_sessions(session_dir)
2316
+ why = (
2317
+ f"{len(blockers)} live session(s): "
2318
+ + ", ".join(f"pid {b.pid} ({b.cwd})" for b in blockers)
2319
+ if blockers
2320
+ else "a session record could not be read"
2321
+ )
2322
+ self._logger.warning(
2323
+ f"History migration of {dest.name} deferred for {account}: {why}"
2324
+ )
2325
+ if self._deferral_reported:
2326
+ return
2327
+ self._deferral_reported = True
2328
+ warning(f"share-history: {account} keeps its own {dest.name} for now.")
2329
+ retry = self._sharing_relaunch_command(slot)
2330
+ if lock_busy:
2331
+ # Nothing to close; the only useful action is to retry once the
2332
+ # peer is done.
2333
+ print(
2334
+ dimmed(
2335
+ " Another cswap launch is merging history into "
2336
+ "~/.claude right now."
2337
+ )
2338
+ )
2339
+ print(dimmed(f" Once it finishes, relaunch: {retry}"))
2340
+ elif blockers:
2341
+ for live in blockers:
2342
+ started = datetime.fromtimestamp(
2343
+ live.started_at / 1000, tz=UTC
2344
+ ).astimezone()
2345
+ print(
2346
+ dimmed(
2347
+ f" pid {live.pid} {live.cwd} "
2348
+ f"(since {started:%Y-%m-%d %H:%M})"
2349
+ )
2350
+ )
2351
+ print(
2352
+ dimmed(
2353
+ " Sessions started here will not appear in "
2354
+ "`claude --resume` under other accounts."
2355
+ )
2356
+ )
2357
+ print(dimmed(f" Close them, then relaunch: {retry}"))
2358
+ else:
2359
+ # Not quiescent, yet nobody to name: a record in the profile's
2360
+ # sessions/ could not be read, and "cannot tell" is never
2361
+ # treated as "nobody there".
2362
+ print(
2363
+ dimmed(
2364
+ " A session record in this profile could not be read, "
2365
+ "so it may still be in use."
2366
+ )
2367
+ )
2368
+ print(dimmed(f" Close anything using it, then relaunch: {retry}"))
2369
+
2370
+ def _sharing_relaunch_command(self, slot: str) -> str:
2371
+ """The ``cswap run`` that shares history next time, as the user would
2372
+ type it: the flag only where their settings turn sharing off."""
2373
+ if load_run_settings(self.switcher.backup_dir).share_history:
2374
+ return f"cswap run {slot}"
2375
+ return f"cswap run {slot} --share-history"
2376
+
2377
+ def _report_sharing_is_the_default(self) -> None:
2378
+ """Name the opt-out when the default reaches history a profile holds.
2379
+
2380
+ Sharing no longer has to be asked for, and for a profile with history
2381
+ of its own that is not a silent change: this launch merged it into
2382
+ ``~/.claude``, or explained why it could not yet. One line, and only
2383
+ for a user who never chose — with ``run.shareHistory`` in the file
2384
+ either way, there is nothing to tell them. It goes quiet by itself:
2385
+ once the profile is linked there is no history of its own to meet.
2386
+ """
2387
+ if not self._own_history_found:
2388
+ return
2389
+ if explicit_share_history(self.switcher.backup_dir) is not None:
2390
+ return
2391
+ print(
2392
+ dimmed(
2393
+ "Chat history is shared between accounts by default now "
2394
+ "(turn off: cswap config set run.shareHistory false)."
2395
+ )
2396
+ )
2397
+
2398
+ def _note_merge_progress(
2399
+ self, moved: int, quarantined: int, run_dir: Path | None
2400
+ ) -> None:
2401
+ """Add one merge's counts to this launch's total.
2402
+
2403
+ HISTORY_ITEMS holds two entries (projects, history.jsonl), so a
2404
+ launch merges up to twice — accumulate rather than overwrite, and
2405
+ keep the first quarantine dir a run produces (the file-merge branch
2406
+ never quarantines, so at most one of the two sets it).
2407
+ """
2408
+ prev_moved, prev_quarantined, prev_run_dir = self._last_merge_counts
2409
+ self._last_merge_counts = (
2410
+ prev_moved + moved,
2411
+ prev_quarantined + quarantined,
2412
+ prev_run_dir if prev_run_dir is not None else run_dir,
2413
+ )
2414
+
2415
+ def _report_quarantine(self) -> None:
2416
+ """Say where a merge parked the copies it did not keep.
2417
+
2418
+ One line per launch, after both history items. Without it the only
2419
+ trace of a conflict is an INFO log line per file, and nothing tells
2420
+ the user a second copy of anything exists. Printed after a merge that
2421
+ failed halfway too: what it parked before failing is still parked.
2422
+ """
2423
+ _, quarantined, run_dir = self._last_merge_counts
2424
+ if not quarantined or run_dir is None:
2425
+ return
2426
+ noun = "file" if quarantined == 1 else "files"
2427
+ print(
2428
+ dimmed(
2429
+ f"Kept {quarantined} conflicting history {noun} aside in "
2430
+ f"{run_dir} — nothing was deleted."
2431
+ )
2432
+ )
2433
+ self._logger.warning(
2434
+ f"History merge kept {quarantined} conflicting {noun} in {run_dir}"
2435
+ )
2436
+
2437
+ def _shared_side_sessions(self, shared_root: Path) -> tuple[set[str], bool]:
2438
+ """Ids of the sessions that appear to be writing the shared history.
2439
+
2440
+ A claude on the default login writes ``shared_root``'s history
2441
+ directly, and one in a linked profile writes it through the link, so
2442
+ ``shared_root`` and every profile of THIS store are read. The flag is
2443
+ False when the answer cannot be trusted — a record that could not be
2444
+ read, or a live session that names no transcript — and the caller
2445
+ must then treat every shared file as in use: not knowing is not the
2446
+ same as knowing nothing is there.
2447
+
2448
+ Best effort, not a guarantee. What is read is the ``sessionId``
2449
+ Claude Code keeps in ``sessions/<pid>.json``. It follows ``--resume``
2450
+ and ``/clear`` (read from the 2.1.319 bundle), but it is rewritten in
2451
+ the background after the switch and a failed rewrite is only logged,
2452
+ so a record read a moment ago can already be behind. Two kinds of
2453
+ writer are not seen at all: a process that never registers a record
2454
+ (a teammate or subagent process), and a session running in a profile
2455
+ of ANOTHER cswap store that shares this ``~/.claude`` (a second
2456
+ ``XDG_DATA_HOME``), whose records are kept where this store cannot
2457
+ find them. Such a session goes undetected, and a transcript it is
2458
+ writing can be replaced by a later profile copy — the copy it was
2459
+ writing is then in the quarantine, not gone.
2460
+ """
2461
+ roots = [shared_root]
2462
+ try:
2463
+ roots.extend(p for p in self.sessions_dir.iterdir() if p.is_dir())
2464
+ except FileNotFoundError:
2465
+ pass
2466
+ except OSError:
2467
+ return set(), False
2468
+ ids: set[str] = set()
2469
+ complete = True
2470
+ for root in roots:
2471
+ sessions, unreadable = scan_live_sessions(root)
2472
+ if unreadable:
2473
+ complete = False
2474
+ for live in sessions:
2475
+ if live.session_id:
2476
+ ids.add(live.session_id)
2477
+ else:
2478
+ complete = False
2479
+ return ids, complete
2480
+
2481
+ def _shared_copy_in_use(self, shared_root: Path, rel: Path) -> bool:
2482
+ """Whether a live session appears to be writing the shared ``rel``.
2483
+
2484
+ Read fresh on every call and never kept for the rest of a merge: a
2485
+ session can ``/resume`` another conversation while the merge is busy
2486
+ with other files, and a snapshot taken at the first collision would
2487
+ wave the newly live transcript through. What remains open is the
2488
+ moment between this read and the rename, and the limits of the
2489
+ records themselves (see ``_shared_side_sessions``).
2490
+ """
2491
+ live_ids, known = self._shared_side_sessions(shared_root)
2492
+ if not known:
2493
+ return True
2494
+ # ``<slug>/<id>.jsonl`` is a session's transcript and ``<slug>/<id>/``
2495
+ # holds its subagents: the id is a path component either way. Claude
2496
+ # appends to both by path, so a file swapped in under a live session
2497
+ # gets its next message.
2498
+ names = {*rel.parts[:-1], rel.name.removesuffix(".jsonl")}
2499
+ return not names.isdisjoint(live_ids)
2500
+
2501
+ def _quarantine(self, path: Path, rel: Path, run_dir: Path, side: str) -> Path:
2502
+ """Move a losing copy under ``run_dir``, never over an existing file.
2503
+
2504
+ ``side`` is which tree the loser came from — ``"shared"`` or ``"profile"`` —
2505
+ because both sides otherwise land at the same relative path and the operator
2506
+ reconciling two disjoint halves of one session would have no way to tell which
2507
+ half is which.
2508
+ """
2509
+ dest = run_dir / side / rel
2510
+ _mkdir_private(dest.parent)
2511
+ if dest.exists():
2512
+ counter = 2
2513
+ while True:
2514
+ candidate = dest.parent / f"{dest.stem}.{counter}{dest.suffix}"
2515
+ if not candidate.exists():
2516
+ dest = candidate
2517
+ break
2518
+ counter += 1
2519
+ shutil.move(str(path), str(dest))
2520
+ self._logger.info(f"Quarantined colliding history file to {dest}")
2521
+ return dest
2522
+
2523
+ def _merge_history_into_source(
2524
+ self, src: Path, dest: Path
2525
+ ) -> tuple[int, int, Path | None]:
2526
+ """Move the profile's own history at ``dest`` into ``src``.
2527
+
2528
+ Directories merge file-by-file, and a name collision does *not* mean
2529
+ the same content: stable names (``memory/MEMORY.md``) diverge between
2530
+ accounts, and a transcript that straddled an un-share event exists in
2531
+ both trees under one UUID. Neither side's copy is ever deleted unless
2532
+ the other side holds every byte of it:
2533
+
2534
+ - The shared copy already contains the profile's (identical, or it
2535
+ continues it): the profile's is a true duplicate and is dropped.
2536
+ - A transcript whose profile copy is the later one
2537
+ (``_profile_copy_wins``) replaces the shared copy, which is
2538
+ quarantined — unless a live session appears to be writing that
2539
+ shared copy, in which case it stays where the session expects it.
2540
+ That check is best effort (``_shared_side_sessions`` says what it
2541
+ cannot see).
2542
+ - Everything else keeps the shared copy and quarantines the
2543
+ profile's. That covers every non-transcript file: nothing ties a
2544
+ ``MEMORY.md`` to one session, so it can never be shown to be idle,
2545
+ and a claude rewriting it in place would write straight over a
2546
+ copy swapped in beneath it.
2547
+
2548
+ ``history.jsonl`` merges by appending lines not already present.
2549
+ ``dest`` is removed once empty; any failure — an OSError, or a
2550
+ UnicodeDecodeError on a byte-corrupt history file — propagates and
2551
+ leaves remaining files in place for the next try. Returns
2552
+ ``(moved, quarantined, run_dir)``: ``moved`` counts files relocated
2553
+ into ``src`` — a plain (non-colliding) move, or the winning half of a
2554
+ collision; ``quarantined`` counts losers parked instead of dropped. A
2555
+ collision where the profile copy wins increments *both* for the one
2556
+ file pair (the winner is moved, the incumbent is quarantined), so
2557
+ callers must not sum the two counters as "files handled". The same
2558
+ counts are added to ``_last_merge_counts`` however the walk ends,
2559
+ so a merge that raises halfway still leaves what it parked on record.
2560
+ """
2561
+ # Never merge the shared history into itself. ``is_dir()`` and
2562
+ # ``rglob`` both follow a link, so a ``dest`` that is one — or that
2563
+ # reaches ``src`` any other way — collides every shared file with
2564
+ # itself. The caller already checks under the lock; it is repeated
2565
+ # here because being wrong costs the whole shared history.
2566
+ if is_link(dest) or (src.exists() and os.path.samefile(src, dest)):
2567
+ raise OSError(f"{dest} is the shared history, not the profile's own")
2568
+
2569
+ run_dir: Path | None = None
2570
+ moved = 0
2571
+ quarantined = 0
2572
+
2573
+ def quarantine_root() -> Path:
2574
+ nonlocal run_dir
2575
+ if run_dir is None:
2576
+ # Stamped per merge and named for the profile: several
2577
+ # profiles migrate on the same day, and "profile" alone does
2578
+ # not say whose MEMORY.md a parked copy is.
2579
+ stamp = datetime.now(UTC).strftime("%Y-%m-%dT%H-%M-%S")
2580
+ run_dir = (
2581
+ self.switcher.backup_dir
2582
+ / QUARANTINE_DIRNAME
2583
+ / f"{stamp}-{dest.parent.name}"
2584
+ )
2585
+ _mkdir_private(run_dir)
2586
+ return run_dir
2587
+
2588
+ if dest.is_dir():
2589
+ _mkdir_private(src)
2590
+ try:
2591
+ for path in _history_tree(dest):
2592
+ rel = path.relative_to(dest)
2593
+ target = src / rel
2594
+ if path.is_dir():
2595
+ path.rmdir() # children already moved (reverse walk)
2596
+ continue
2597
+ if target.exists():
2598
+ if _adds_nothing(target, path):
2599
+ path.unlink()
2600
+ continue
2601
+ if (
2602
+ path.suffix == ".jsonl"
2603
+ and target.is_file()
2604
+ and _profile_copy_wins(target, path)
2605
+ and not self._shared_copy_in_use(src.parent, rel)
2606
+ ):
2607
+ # Park the incumbent first: a crash between the
2608
+ # two leaves the shared path empty, and the next
2609
+ # run moves the profile copy in cleanly. Counted
2610
+ # as parked right here, not after the move: if
2611
+ # the move fails, this is the copy the user has
2612
+ # to be pointed at.
2613
+ self._quarantine(
2614
+ target, rel, quarantine_root(), "shared"
2615
+ )
2616
+ quarantined += 1
2617
+ _mkdir_private(target.parent)
2618
+ shutil.move(str(path), str(target))
2619
+ moved += 1
2620
+ else:
2621
+ self._quarantine(
2622
+ path, rel, quarantine_root(), "profile"
2623
+ )
2624
+ quarantined += 1
2625
+ continue
2626
+ _mkdir_private(target.parent)
2627
+ shutil.move(str(path), str(target))
2628
+ moved += 1
2629
+ finally:
2630
+ # However the walk ends. A merge that stops halfway has
2631
+ # still parked what it parked, and the launch must be able
2632
+ # to say where.
2633
+ self._note_merge_progress(moved, quarantined, run_dir)
2634
+ dest.rmdir()
2635
+ else:
2636
+ existing_text = ""
2637
+ if src.exists():
2638
+ existing_text = src.read_text(encoding="utf-8")
2639
+ existing = set(existing_text.splitlines())
2640
+ lines = [
2641
+ line
2642
+ for line in dest.read_text(encoding="utf-8").splitlines()
2643
+ if line and line not in existing
2644
+ ]
2645
+ if lines:
2646
+ src.parent.mkdir(parents=True, exist_ok=True)
2647
+ if not src.exists():
2648
+ src.touch(mode=0o600) # match Claude Code's history mode
2649
+ # A history.jsonl torn by a crashed append ends mid-line, and
2650
+ # appending onto it would weld that tail to the first merged
2651
+ # entry — one line that parses as neither, with no second
2652
+ # copy to recover from once dest is unlinked below.
2653
+ torn = bool(existing_text) and not existing_text.endswith("\n")
2654
+ terminator = "\n" if torn else ""
2655
+ with src.open("a", encoding="utf-8") as f:
2656
+ f.write(terminator + "\n".join(lines) + "\n")
2657
+ dest.unlink()
2658
+ return moved, quarantined, run_dir
2659
+
2660
+ @staticmethod
2661
+ def _read_manifest(manifest_path: Path) -> list[str]:
2662
+ try:
2663
+ data = json.loads(manifest_path.read_text(encoding="utf-8"))
2664
+ items = data.get("items", [])
2665
+ # Only ever act on names we could have created.
2666
+ return [i for i in items if i in SHARED_ITEMS + HISTORY_ITEMS]
2667
+ except (OSError, json.JSONDecodeError, AttributeError):
2668
+ return []
2669
+
2670
+ def _write_manifest(self, manifest_path: Path, items: list[str]) -> None:
2671
+ # ``mode`` is informational — nothing reads it back — and says how
2672
+ # files are shared: by symlink, or (Windows without the privilege)
2673
+ # by copy. Directories are links on every platform.
2674
+ if self.switcher.platform != Platform.WINDOWS:
2675
+ mode = "symlink"
2676
+ else:
2677
+ mode = "symlink" if can_symlink(manifest_path.parent) else "copy"
2678
+ payload = json.dumps({"items": items, "mode": mode}, indent=2)
2679
+ try:
2680
+ atomic_write_text(manifest_path, payload)
2681
+ except OSError:
2682
+ pass # best effort: a failed manifest must not fail a launch
2683
+
2684
+ @staticmethod
2685
+ def _remove_managed(dest: Path) -> None:
2686
+ """Remove a cswap-created share entry (link or copy), never user data
2687
+ beyond it — callers guarantee `dest` is manifest-listed or a link."""
2688
+ try:
2689
+ if is_link(dest):
2690
+ remove_link(dest) # the link itself, never what it leads to
2691
+ elif dest.is_file():
2692
+ dest.unlink(missing_ok=True)
2693
+ elif dest.is_dir():
2694
+ shutil.rmtree(dest, ignore_errors=True)
2695
+ except OSError:
2696
+ pass