diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..e9618d7 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,219 @@ +name: release + +# Cut a release by pushing a tag like v0.1.0. +on: + push: + tags: ["v*"] + workflow_dispatch: + inputs: + tag: + description: "Existing tag to (re)build, e.g. v0.1.0" + required: true + +permissions: + contents: write + +env: + BIN: ccswitch + +jobs: + build: + name: build ${{ matrix.target }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + include: + - os: macos-14 + target: aarch64-apple-darwin + # x86_64 mac is cross-compiled on the Apple-Silicon runner — the + # scarce macos-13 Intel runner was leaving releases stuck in queue. + - os: macos-14 + target: x86_64-apple-darwin + - os: ubuntu-latest + target: x86_64-unknown-linux-gnu + - os: ubuntu-24.04-arm + target: aarch64-unknown-linux-gnu + steps: + - uses: actions/checkout@v4 + - name: Resolve tag + id: tag + shell: bash + env: + INPUT_TAG: ${{ github.event.inputs.tag }} + REF_NAME: ${{ github.ref_name }} + run: | + tag="${INPUT_TAG:-$REF_NAME}" + if ! printf '%s' "$tag" | grep -qE '^v[0-9A-Za-z.+-]+$'; then + echo "::error::invalid tag '$tag'"; exit 1 + fi + echo "tag=$tag" >> "$GITHUB_OUTPUT" + - uses: dtolnay/rust-toolchain@stable + with: + targets: ${{ matrix.target }} + - uses: Swatinem/rust-cache@v2 + with: + key: ${{ matrix.target }} + - name: Build + run: cargo build --release --locked --target ${{ matrix.target }} + - name: Package + id: pkg + shell: bash + run: | + set -euo pipefail + tag="${{ steps.tag.outputs.tag }}" + name="${BIN}-${tag}-${{ matrix.target }}" + dist="dist/$name" + mkdir -p "$dist" + cp "target/${{ matrix.target }}/release/${BIN}" "$dist/" + cp README.md LICENSE "$dist/" 2>/dev/null || true + tar -C "$dist" -czf "dist/$name.tar.gz" . # binary at archive root + ( cd dist && shasum -a 256 "$name.tar.gz" > "$name.tar.gz.sha256" ) + echo "artifact=dist/$name.tar.gz" >> "$GITHUB_OUTPUT" + - uses: actions/upload-artifact@v4 + with: + name: ${{ matrix.target }} + path: dist/*.tar.gz* + if-no-files-found: error + + release: + name: publish release + bump cask + needs: build + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Resolve tag + id: tag + shell: bash + env: + INPUT_TAG: ${{ github.event.inputs.tag }} + REF_NAME: ${{ github.ref_name }} + run: | + tag="${INPUT_TAG:-$REF_NAME}" + if ! printf '%s' "$tag" | grep -qE '^v[0-9A-Za-z.+-]+$'; then + echo "::error::invalid tag '$tag'"; exit 1 + fi + echo "tag=$tag" >> "$GITHUB_OUTPUT" + - uses: actions/download-artifact@v4 + with: + path: artifacts + - name: Collect artifacts + shell: bash + run: | + set -euo pipefail + mkdir -p dist + find artifacts -type f \( -name '*.tar.gz' -o -name '*.sha256' \) -exec cp {} dist/ \; + ls -l dist + - name: Create GitHub release + uses: softprops/action-gh-release@v2 + with: + tag_name: ${{ steps.tag.outputs.tag }} + generate_release_notes: true + files: dist/* + - name: Bump Homebrew cask + shell: bash + run: | + set -euo pipefail + tag="${{ steps.tag.outputs.tag }}" + version="${tag#v}" + sha() { cut -d' ' -f1 "dist/${BIN}-${tag}-$1.tar.gz.sha256"; } + arm_mac=$(sha aarch64-apple-darwin) + x86_mac=$(sha x86_64-apple-darwin) + arm_lin=$(sha aarch64-unknown-linux-gnu) + x86_lin=$(sha x86_64-unknown-linux-gnu) + mkdir -p Casks + cat > Casks/ccswitch.rb < Formula/ccswitch.rb < **Every real OS/network side effect sits behind a trait whose only real +> implementation lives in a `*_shim.rs` file. All decision logic lives outside +> shims and is unit-tested. Coverage target: ≥98% line AND region.** + +If you internalize one thing, make it that. + +--- + +## Build / test / lint + +```sh +cargo build +cargo test +cargo fmt +cargo clippy --all-targets --all-features -- -D warnings +``` + +All four must be green before you finish. `cargo fmt` and a clippy run with +`-D warnings` are non-negotiable. + +Dependencies are lean and pinned in `Cargo.toml`. The sanctioned set: `clap` +(derive) + `clap_complete` for the CLI and completions, `serde`/`serde_json` +for the JSON config and profile files, and `thiserror`/`anyhow` for errors. Do +not add crates casually — there is no database, HTTP, or async runtime here. + +--- + +## Coverage discipline (the important part) + +Run coverage with Homebrew LLVM so `llvm-cov`/`llvm-profdata` match the +toolchain: + +```sh +LLVM_COV="$(brew --prefix llvm)/bin/llvm-cov" \ +LLVM_PROFDATA="$(brew --prefix llvm)/bin/llvm-profdata" \ +cargo llvm-cov \ + --all-features \ + --ignore-filename-regex '(_shim\.rs$|/main\.rs$)' \ + --summary-only +``` + +**Ignore regex:** `(_shim\.rs$|/main\.rs$)`. That is the coverage boundary — the +`*_shim.rs` adapters plus the trivial `main.rs` entry point (which only +delegates to `ccswitch::cli_shim::run`). Everything else must be covered to +≥98% line **and** region. + +Rules that keep coverage reachable: + +- A `*_shim.rs` file holds a trait's **real** adapter and *nothing a test needs + to reach*: no branching, no parsing, no decisions. If you find yourself + writing an `if`/`match` that matters inside a shim, it belongs in a non-shim + module behind the trait. +- Reading and writing plain files under a **temp root** is testable — do it + directly, no shim. Only spawning processes (`claude`, `csx`, `fzf`), + creating symlinks, terminal prompting, the macOS Keychain (`security` + binary), and replacing the process via `exec` need shims. +- Every non-shim module carries its own `#[cfg(test)] mod tests` exercising all + branches with fakes and `std::env::temp_dir()`-based temp directories. + +--- + +## Architecture / module map + +Ports (traits) are consumed by pure logic; the matching `*_shim.rs` supplies the +one real adapter. Data flow: **`cli::parse_from` → `Command` → `App::dispatch` +→ (`Switcher` over `CredentialStore` + `config` + `Store`) and/or the `System` +port → output.** + +| Module | Role | Port(s) → shim | +| ---------------- | ------------------------------------------------------------------------------------------------ | -------------- | +| `model.rs` | Domain types: `Account` (uuid/org/email/org-name) and `Profile` (persisted `account.json`). | — | +| `error.rs` | `Error` / `Result` (`ProfileNotFound`, `ReservedName`, `Invalid`, wrapped `Io`/`Json`). | — | +| `config.rs` | Read/splice `~/.claude.json`: extract + reinsert the `{oauthAccount, userID}` identity, leaving every other key untouched. Plain-file JSON, temp-tested. | — | +| `creds.rs` | `CredentialStore` trait + the `FileStore` (`/.credentials.json`) fallback used off macOS. Temp-tested. | `CredentialStore` | +| `creds_shim.rs` | Real macOS Keychain adapter (`security` binary) + `platform_store` `cfg` selection. | `CredentialStore` → **shim** | +| `store.rs` | The on-disk profile store under `$CCSWITCH_HOME`; `TokenScope` (`PerAccount` / `PerAccountOrg`) — the knob behind the auth-loss fix. Temp-tested. | — | +| `switch.rs` | `Switcher` — save/activate orchestration over `creds` + `config` + `store`; re-snapshots the outgoing credential into every token-sharing sibling. | consumes `CredentialStore` | +| `cli.rs` | clap types, the `Command` model, `App::dispatch` + every handler, `System` port, path resolution, symlink planning, `search`/`isolate`/`seed` logic, completion generation. | `System` | +| `cli_shim.rs` | `RealSystem` (spawn `claude`/`csx`/`fzf`, symlinks, prompts, `exec`) + `run` — the one impure entry point (real env, `$HOME`/`$CCSWITCH_*`, stdio, platform stores). | `System` → **shim** | +| `main.rs` | Binary entry point; delegates to `cli_shim::run`. | — (ignored) | + +The `System` trait in `cli.rs` is the seam that keeps the whole command surface +testable: handlers call `claude_login`, `command_exists`, `claude_is_running`, +`make_symlink`, `confirm`, `csx_current`, `csx_sessions`, `fzf_pick`, and +`exec` through it, and the tests drive a `FakeSystem` recording every call. + +--- + +## The auth-loss fix (why `TokenScope` exists) + +The Claude Code OAuth **refresh token rotates per account**, shared across +every organization a single login can operate in (org selection is client-side +state in `~/.claude.json`, not part of the credential). The original tool +re-snapshotted the live credential into only the one profile whose +`(accountUuid, organizationUuid)` matched — so two profiles for the same login +but different orgs each held a copy of the one shared token, and the first +refresh under either org stranded the sibling with a dead one. + +`Switcher` closes that gap: before switching away it re-snapshots the live +credential into **every** profile that shares the outgoing account's token, as +selected by `TokenScope`. Production wires `TokenScope::PerAccount` (group by +`accountUuid` alone), so a rotation under any org keeps every sibling current. +Preserve this behavior; it is the reason the Rust tool exists. + +--- + +## Adding a feature + +1. **Decide where the logic goes.** Any real side effect (a new process to + spawn, a new prompt, a new file to watch) becomes a method on the `System` + trait in `cli.rs`, implemented once in `RealSystem` (`cli_shim.rs`). Pure + decision logic — parsing, validation, path math, JSON shaping — goes in the + plain module and is unit-tested with a fake. Never put a decision in a + `_shim.rs`. +2. **A new subcommand:** add a variant to `Sub` (clap) and `Command` in + `cli.rs`, map it in `From>`, add a handler on `App`, route it in + `dispatch`, and extend `help_text()` and `RESERVED` if it introduces a new + word. Cover the parse, the dispatch, and each error branch. +3. **A new credential backend:** implement `CredentialStore` in `creds.rs` (if + temp-testable) or add the real adapter to `creds_shim.rs` and select it in + `platform_store`. +4. **Run the gate:** `cargo build && cargo test`, then `cargo fmt`, + `cargo clippy --all-targets --all-features -- -D warnings`, then the + coverage command above — line and region must stay ≥98%. + +--- + +## Distribution + +`.github/workflows/release.yml` cuts a release on a `v*` tag (or manual +`workflow_dispatch` with a validated `tag` input): it cross-compiles the four +targets (`aarch64`/`x86_64` × macOS/Linux — the Intel mac is built on the +Apple-Silicon `macos-14` runner), publishes per-arch `.tar.gz` + `.sha256` +assets to a GitHub release, and regenerates `Casks/ccswitch.rb` with the real +checksums (a `github_latest` livecheck keeps it tracking the latest tag). The +binary name is `ccswitch`. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..258e69e --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,52 @@ +# Changelog + +All notable changes to ccswitch are documented here. The format follows +[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow +[Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +_Nothing yet._ + +## [0.1.0] — 2026-07-08 + +First release of the Rust CLI, superseding the original fish plugin (now under +`legacy-fish/`). + +### Added + +- **Account switching** — `save`, `use`, and the bare `ccswitch + [args...]` form snapshot both halves of a Claude Code identity (the OAuth + credential and the `~/.claude.json` `oauthAccount` + `userID`) into a plain + profile directory and restore them as a unit, launching `claude` on the bare + form. +- **`add`** — sign in to a new account (`claude auth login`) and save it in one + step; `--force` on `add`/`save` overwrites an existing profile. +- **`list`, `current`, `rm`** — enumerate profiles (`*` marks the active one), + show the active account, and delete a profile; with aliases `ls`, `whoami`, + and `remove`/`delete`. +- **Token-rotation fix** — on every switch the outgoing credential is + re-snapshotted into **every** profile that shares its per-account refresh + token (`TokenScope::PerAccount`), so an actively used account never strands a + sibling profile with a rotated-out token. +- **Concurrent sessions** — `isolate` runs a session under a per-profile + `CLAUDE_CONFIG_DIR` with `projects/`, `history.jsonl`, and `CLAUDE.md` + symlinked to a shared directory, and `seed` imports that shared memory from + `~/.claude` (or a given dir). Empty shared memory triggers a confirm. +- **`search`** — bridges to [`csx`](https://github.com/mysqto/csx) + `fzf` to + fuzzy-pick and resume a past session, defaulting the scope to the active tool + and resuming with the right command per tool (`claude`, `codex`). +- **Cross-shell completions** — `completions ` for bash, zsh, fish, + PowerShell, and elvish. +- **Cross-platform credentials** — macOS Keychain via the `security` binary, + with a `~/.claude/.credentials.json` file store fallback elsewhere. +- **Docs & distribution** — README, `AGENTS.md`, a GitHub release workflow with + a cross-compile matrix, and an auto-bumped Homebrew cask. + +### Notes + +- Test suite covers decision logic to ≥98% line and region; OS/network I/O + lives in `*_shim.rs` files behind traits (see `AGENTS.md`). + +[Unreleased]: https://github.com/mysqto/ccswitch/compare/v0.1.0...HEAD +[0.1.0]: https://github.com/mysqto/ccswitch/releases/tag/v0.1.0 diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..505a552 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,287 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + +[[package]] +name = "anyhow" +version = "1.0.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3" + +[[package]] +name = "ccswitch" +version = "0.1.0" +dependencies = [ + "anyhow", + "clap", + "clap_complete", + "serde", + "serde_json", + "thiserror", +] + +[[package]] +name = "clap" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_complete" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db8b397918185f0161ff3d6fcaa9e4bfc09b8367caf6e1d4a2848e5477ed027b" +dependencies = [ + "clap", +] + +[[package]] +name = "clap_derive" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.150" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "syn" +version = "2.0.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "thiserror" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "zmij" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..42a9a60 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "ccswitch" +version = "0.1.0" +edition = "2021" +description = "Switch between multiple Claude Code accounts" +license = "MIT" + +[[bin]] +name = "ccswitch" +path = "src/main.rs" + +[lib] +name = "ccswitch" +path = "src/lib.rs" + +[dependencies] +clap = { version = "4.5", features = ["derive"] } +clap_complete = "4.5" +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +anyhow = "1.0" +thiserror = "2.0" diff --git a/Casks/ccswitch.rb b/Casks/ccswitch.rb new file mode 100644 index 0000000..60c032a --- /dev/null +++ b/Casks/ccswitch.rb @@ -0,0 +1,36 @@ +# Auto-generated by .github/workflows/release.yml on each tag. Do not edit by hand. +cask "ccswitch" do + version "0.1.0" + + on_macos do + on_arm do + sha256 :no_check + url "https://github.com/mysqto/ccswitch/releases/download/v#{version}/ccswitch-v#{version}-aarch64-apple-darwin.tar.gz" + end + on_intel do + sha256 :no_check + url "https://github.com/mysqto/ccswitch/releases/download/v#{version}/ccswitch-v#{version}-x86_64-apple-darwin.tar.gz" + end + end + on_linux do + on_arm do + sha256 :no_check + url "https://github.com/mysqto/ccswitch/releases/download/v#{version}/ccswitch-v#{version}-aarch64-unknown-linux-gnu.tar.gz" + end + on_intel do + sha256 :no_check + url "https://github.com/mysqto/ccswitch/releases/download/v#{version}/ccswitch-v#{version}-x86_64-unknown-linux-gnu.tar.gz" + end + end + + livecheck do + url :url + strategy :github_latest + end + + name "ccswitch" + desc "Switch between multiple Claude Code accounts" + homepage "https://github.com/mysqto/ccswitch" + + binary "ccswitch" +end diff --git a/Formula/ccswitch.rb b/Formula/ccswitch.rb new file mode 100644 index 0000000..3fbc924 --- /dev/null +++ b/Formula/ccswitch.rb @@ -0,0 +1,44 @@ +# Auto-generated by .github/workflows/release.yml on each tag. Do not edit by hand. +# This committed copy is a template until the first release fills in real checksums. +class Ccswitch < Formula + desc "Cross-shell switcher for multiple Claude Code accounts" + homepage "https://github.com/mysqto/ccswitch" + version "0.0.0" + + on_macos do + on_arm do + url "https://github.com/mysqto/ccswitch/releases/download/v#{version}/ccswitch-v#{version}-aarch64-apple-darwin.tar.gz" + sha256 "0000000000000000000000000000000000000000000000000000000000000000" + end + on_intel do + url "https://github.com/mysqto/ccswitch/releases/download/v#{version}/ccswitch-v#{version}-x86_64-apple-darwin.tar.gz" + sha256 "0000000000000000000000000000000000000000000000000000000000000000" + end + end + on_linux do + on_arm do + url "https://github.com/mysqto/ccswitch/releases/download/v#{version}/ccswitch-v#{version}-aarch64-unknown-linux-gnu.tar.gz" + sha256 "0000000000000000000000000000000000000000000000000000000000000000" + end + on_intel do + url "https://github.com/mysqto/ccswitch/releases/download/v#{version}/ccswitch-v#{version}-x86_64-unknown-linux-gnu.tar.gz" + sha256 "0000000000000000000000000000000000000000000000000000000000000000" + end + end + + livecheck do + url :url + strategy :github_latest + end + + def install + bin.install "ccswitch" + # Runs `ccswitch completions {bash,zsh,fish}` and installs each script so + # tab-completion works immediately — the piece a cask can't do. + generate_completions_from_executable(bin/"ccswitch", "completions") + end + + test do + assert_match "ccswitch", shell_output("#{bin}/ccswitch --help") + end +end diff --git a/README.md b/README.md index 2022284..5f16095 100644 --- a/README.md +++ b/README.md @@ -1,72 +1,155 @@ # ccswitch -A tiny [fish](https://fishshell.com) plugin to switch between multiple -[Claude Code](https://claude.com/claude-code) accounts — personal, work, -different orgs — and jump straight into a session. +**Switch between multiple Claude Code accounts — personal, work, different +orgs — and jump straight into a session.** -```fish +`ccswitch` is a small, fast, cross-shell command-line tool. An account is two +things that must travel together: the OAuth credential (in the macOS Keychain, +or `~/.claude/.credentials.json` elsewhere) and the identity Claude Code +validates it against (`oauthAccount` + `userID` inside `~/.claude.json`). +`ccswitch` snapshots both into a plain profile directory and restores them as a +unit, so one command becomes an account and drops you into `claude`. + +```sh ccswitch work # switch to the "work" account and start claude ccswitch personal -c # switch to "personal", launch claude with -c ccswitch use work # just switch, don't launch -ccswitch list # see every saved profile (* = active) +ccswitch list # every saved profile (* = active) ``` -## How it works +- **One binary, every shell.** A single Rust binary with completions for bash, + zsh, fish, and PowerShell. +- **Token-rotation safe.** OAuth refresh tokens rotate per *login*, shared + across every org that login can see; `ccswitch` re-snapshots the outgoing + credential into every sibling profile on each switch, so an actively used + account never goes stale. +- **Concurrent sessions.** Run two accounts at once in separate terminals with + isolated config dirs but shared project memory and history. +- **Session recall.** `ccswitch search` bridges to + [`csx`](https://github.com/mysqto/csx) + `fzf` to fuzzy-pick and resume any + past session. -An account is two things that must travel together: +> This Rust CLI supersedes the original fish plugin, now preserved under +> [`legacy-fish/`](legacy-fish/). The commands are the same; the tool is now a +> single portable binary rather than a fish-only function. -1. **OAuth tokens** — the real credential. On macOS these live in the login - Keychain (`Claude Code-credentials`); on Linux/others in - `~/.claude/.credentials.json`. `ccswitch` picks the right backend per platform. -2. **Identity** — the `oauthAccount` object and `userID` inside `~/.claude.json`, - which Claude Code validates the token against. - -`ccswitch save ` snapshots both into a plain profile directory. Switching -restores the credential into the platform store and splices only `oauthAccount` -and `userID` back into `~/.claude.json` (backing it up first — the rest of that -file is shared and left untouched). Because a profile is just two JSON files, it -is portable across machines and operating systems. +--- ## Install -With [fisher](https://github.com/jorgebucaran/fisher): +### Homebrew (macOS & Linux) -```fish -fisher install mysqto/ccswitch +```sh +brew tap mysqto/ccswitch https://github.com/mysqto/ccswitch +brew install ccswitch # formula (recommended) — also installs shell completions +# or: +brew install --cask ccswitch # cask — installs the binary only (no completions) ``` -Requires [`jq`](https://jqlang.github.io/jq/). +The tap ships **both** a formula and a cask, auto-regenerated with real +checksums on each release. Prefer `brew install ccswitch` (the **formula**): it +runs `ccswitch completions {bash,zsh,fish}` during install and drops each script +into Homebrew's completion directories, so tab-completion works right away. The +`--cask` route installs just the binary — use it if you don't want the formula, +and set up completions yourself (see [Shell completions](#shell-completions)). Install one, +not both — they each provide a `ccswitch` binary. -## Usage +### From source with Cargo + +```sh +cargo install --git https://github.com/mysqto/ccswitch # or, in a clone: cargo install --path . +``` + +### Prebuilt binary + +Download the tarball for your platform from the [latest release][releases], +extract it, and put `ccswitch` on your `PATH`. Assets are named +`ccswitch--.tar.gz`, each with a matching `.sha256`: + +| Platform | Target | +| --- | --- | +| macOS Apple Silicon | `aarch64-apple-darwin` | +| macOS Intel | `x86_64-apple-darwin` | +| Linux x86_64 | `x86_64-unknown-linux-gnu` | +| Linux ARM64 | `aarch64-unknown-linux-gnu` | + +Every method produces a single `ccswitch` binary with no runtime dependencies +(the optional `search` bridge aside). + +[releases]: https://github.com/mysqto/ccswitch/releases/latest + +--- + +## Commands + +Run `ccswitch` (or `ccswitch help`) for usage. Every command is below. | Command | Action | | --- | --- | | `ccswitch [args...]` | Switch to ``, then start `claude` (extra args passed through) | | `ccswitch use ` | Switch without launching | -| `ccswitch add ` | Sign in to a new account (`claude auth login`) and save it as `` | -| `ccswitch isolate [args...]` | Run a **concurrent** session isolated to `` (own credential) with memory/history shared across profiles | -| `ccswitch save ` | Save the current account as `` | -| `ccswitch list` / `ls` | List profiles (`*` marks the active one) | -| `ccswitch current` / `whoami` | Show the active account | -| `ccswitch search` / `s` `[scope…]` | Fuzzy-pick a past session (via [`csx`](https://github.com/mysqto/csx)) and resume it | -| `ccswitch rm ` | Delete a profile | +| `ccswitch add [--force]` | Sign in to a new account (`claude auth login`) and save it as `` | +| `ccswitch save [--force]` | Snapshot the current account as `` | +| `ccswitch isolate [args...]` | Run a **concurrent** session isolated to `` (own credential, shared memory) | +| `ccswitch isolate` | With no name, list existing isolated profiles | +| `ccswitch seed [dir]` | Seed the shared isolate memory from `~/.claude` (or `dir`) | +| `ccswitch search [scope...]` | Fuzzy-pick a past session (via `csx` + `fzf`) and resume it | +| `ccswitch list` | List saved profiles (`*` marks the active one) | +| `ccswitch current` | Show the active account | +| `ccswitch rm ` | Delete a saved profile | +| `ccswitch completions ` | Print a completion script to stdout | +| `ccswitch help` | Show usage | -## Search past sessions +**Aliases:** `iso` = `isolate`, `s` = `search`, `ls` = `list`, `whoami` = +`current`, `remove`/`delete` = `rm`. -`ccswitch search` (alias `s`) is an optional bridge to -[`csx`](https://github.com/mysqto/csx), a local index of your AI-coding -sessions. It fuzzy-picks a session and resumes it in the tool that produced it: +**`--force`** (on `add` and `save`) overwrites an existing profile of the same +name; without it, saving over an existing profile is refused. -```fish -ccswitch search # sessions for the active tool → fzf → resume -ccswitch search --repo payments # any csx scope flag passes straight through +Profile names may not collide with a reserved subcommand word (`save`, `add`, +`isolate`, `iso`, `seed`, `search`, `s`, `list`, `ls`, `current`, `whoami`, +`use`, `rm`, `remove`, `delete`, `help`). + +### Environment + +| Variable | Purpose | Default | +| --- | --- | --- | +| `CCSWITCH_HOME` | Where saved profiles live. | `~/.claude/accounts` | +| `CCSWITCH_ISOLATE_HOME` | Where isolated profiles + shared memory live. | `~/.claude/profiles` | + +--- + +## Shell completions + +`ccswitch completions ` prints a completion script to stdout for +`bash`, `zsh`, `fish`, `powershell` (and `elvish`). Install it once for your +shell: + +**bash** — add to `~/.bashrc`: + +```sh +source <(ccswitch completions bash) ``` -It shells out to `csx sessions` (defaulting the scope to the active tool), -previews each transcript with `csx show ` in `fzf`, and resumes the pick -(`claude --resume `, `codex resume `, …). Requires `csx` and `fzf` on -`PATH` (`jq` optional, for a nicer picker list). If `csx` isn't installed, every -other `ccswitch` command still works — this subcommand just prints a hint. +**zsh** — write into a directory on your `$fpath` (before `compinit`): + +```sh +ccswitch completions zsh > "${fpath[1]}/_ccswitch" +``` + +**fish**: + +```fish +ccswitch completions fish > ~/.config/fish/completions/ccswitch.fish +``` + +**PowerShell** — add to your `$PROFILE`: + +```powershell +ccswitch completions powershell | Out-String | Invoke-Expression +``` + +--- ## Walkthrough @@ -74,12 +157,9 @@ A complete run, from a fresh install to switching daily. ### 1. Save the account you're already signed into -```fish +```sh claude auth status # confirm who you're logged in as ccswitch save personal # snapshot the active account as "personal" -``` - -```fish ccswitch list # * personal you@gmail.com ``` @@ -90,22 +170,13 @@ The `*` marks the currently active account. `ccswitch add` signs you in to another account and saves it in one step: -```fish +```sh ccswitch add work # runs `claude auth login`, then saves it as "work" ``` -
-Prefer to do it by hand? - -```fish -claude auth login # sign in as the other account (or switch org via /login) -ccswitch save work -``` -
- Both are now saved: -```fish +```sh ccswitch list # personal you@gmail.com # * work you@company.com (Acme) @@ -113,7 +184,7 @@ ccswitch list ### 3. Switch and work — the daily loop -```fish +```sh ccswitch work # become "work" and start a claude session ccswitch personal -c # become "personal", continue the last conversation ccswitch use work # just switch, don't launch anything @@ -123,29 +194,13 @@ ccswitch current # you@company.com (Acme) One command becomes an account and drops you into a session. Switching also re-snapshots the account you're leaving, so rotating tokens never go stale. -### 4. Run two accounts at the same time - -Steps 1–3 swap one machine-global account (sequential — one at a time). To keep -**two live sessions as different accounts concurrently**, use isolated profiles -with shared memory: - -```fish -ccswitch seed # once: copy your ~/.claude memory + history into shared/ -ccswitch isolate work # terminal 1 — sign in once as work -ccswitch isolate personal # terminal 2 — sign in once as personal, at the same time -``` - -Each isolated session has its own credential but shares project memory and -history. Re-running `ccswitch isolate ` reuses the earlier login. (If you -skip `seed`, the first `isolate` warns that memory is empty and asks to confirm.) - -## Same login, multiple orgs +### Same login, multiple orgs If one login (e.g. a Claude Team account) belongs to several organizations, each org is a separate profile — Claude Code issues a distinct org-scoped token per org. Save one after switching org inside Claude Code (`/login`): -```fish +```sh ccswitch save org-a # while the first org is active # switch org in Claude Code, then: ccswitch save org-b @@ -154,16 +209,19 @@ ccswitch save org-b `ccswitch list` distinguishes them by account **and** organization, so the same email can appear more than once with only the active org starred. -## Concurrent sessions (shared memory, separate accounts) +--- -`ccswitch ` swaps a single machine-global account, so it is sequential — -one active account at a time. To run **two accounts at once** (two terminals), +## Concurrent sessions (isolate + seed) + +`ccswitch ` swaps a single machine-global account, so it is **sequential** +— one active account at a time. To run **two accounts at once** (two terminals), use `ccswitch isolate`, which gives each profile its own [`CLAUDE_CONFIG_DIR`](https://code.claude.com/docs/en/settings): -```fish -ccswitch isolate work # terminal 1 — signs in once, then reuses -ccswitch isolate personal # terminal 2 — a different account, at the same time +```sh +ccswitch seed # once: copy your ~/.claude memory + history into shared/ +ccswitch isolate work # terminal 1 — sign in once as work +ccswitch isolate personal # terminal 2 — sign in once as personal, at the same time ``` Each profile keeps its **own credential and identity**, but memory and history @@ -172,7 +230,8 @@ are **shared** — `isolate` symlinks `projects/` (session transcripts + the `shared/` directory. So both accounts see the same project memory and past sessions while staying logged in as different users. -Layout (centralized under `~/.claude`, override with `$CCSWITCH_ISOLATE_HOME`): +Layout (centralized under `~/.claude/profiles`, override with +`$CCSWITCH_ISOLATE_HOME`): ``` ~/.claude/profiles/ @@ -192,27 +251,47 @@ Layout (centralized under `~/.claude`, override with `$CCSWITCH_ISOLATE_HOME`): `ccswitch isolate` with no name lists existing isolated profiles. Existing non-symlink files in a profile dir are left untouched (never clobbered). -`shared/` starts **empty** — isolated profiles begin with fresh memory. To carry -your existing memory/history over, seed it once from your default `~/.claude`: +**Seeding.** `shared/` starts empty — isolated profiles begin with fresh +memory. Carry your existing memory/history over once: -```fish +```sh ccswitch seed # copies CLAUDE.md, history.jsonl and projects/ from ~/.claude ccswitch seed # ... or from another config dir ``` Re-run `ccswitch seed` anytime to re-sync from the source (source wins on -same-named files). +same-named files). While `shared/` is empty, `ccswitch isolate` warns and asks +for confirmation before launching, so you don't start with no memory by +accident. The prompt stops once `shared/` has content. -While `shared/` is empty, `ccswitch isolate` warns and asks for confirmation -before launching (so you don't start with no memory by accident). The prompt -stops appearing once `shared/` has content — from `ccswitch seed` or from your -first session. - -> Note: this pattern relies on `CLAUDE_CONFIG_DIR` (supported) plus symlinking of +> This pattern relies on `CLAUDE_CONFIG_DIR` (supported) plus symlinking of > account-agnostic paths (a community pattern, not officially documented). Auth > stays isolated; only memory/history is shared. Two sessions writing the same > project's memory simultaneously can race — low risk in practice. +--- + +## Search past sessions + +`ccswitch search` (alias `s`) is an optional bridge to +[`csx`](https://github.com/mysqto/csx), a local index of your AI-coding +sessions. It fuzzy-picks a session and resumes it in the tool that produced it: + +```sh +ccswitch search # sessions for the active tool → fzf → resume +ccswitch search --repo payments # any csx scope flag passes straight through +ccswitch search --tool codex # pick from Codex sessions instead +``` + +It shells out to `csx sessions --json` (defaulting the scope to the tool +reported by `csx current`), previews each transcript with `csx show ` in +`fzf`, and resumes the pick — `claude --resume ` for Claude Code, `codex +resume ` for Codex. Requires `csx` and `fzf` on `PATH`. If either is +missing, every other `ccswitch` command still works — this subcommand just +prints a hint. + +--- + ## Profile storage Profiles live in `$CCSWITCH_HOME` (default `~/.claude/accounts`), one directory @@ -221,35 +300,48 @@ per profile: ``` ~/.claude/accounts/work/ ├── credentials.json # OAuth blob - └── account.json # oauthAccount + userID + └── account.json # oauthAccount + userID (+ keychain account attr) ``` Point `$CCSWITCH_HOME` at a synced folder or repo to move profiles between -machines: +machines. -```fish -set -Ux CCSWITCH_HOME ~/vault/claude-accounts -``` - -## ⚠️ These files are secrets +### ⚠️ These files are secrets `credentials.json` holds a live bearer token. If you sync `$CCSWITCH_HOME` with git or a cloud folder, **encrypt it** — use a private repo with -[git-crypt](https://github.com/AGWA/git-crypt) / [age](https://github.com/FiloSottile/age) / +[git-crypt](https://github.com/AGWA/git-crypt) / +[age](https://github.com/FiloSottile/age) / [SOPS](https://github.com/getsops/sops), or a real secret manager. Never commit plaintext tokens to a shared or public repo. +--- + ## Notes - Quit any running `claude` session before switching — an open session can - rewrite `~/.claude.json` on exit and clobber the swap. `ccswitch` warns when it - detects one. + rewrite `~/.claude.json` on exit and clobber the swap. `ccswitch` warns when + it detects one. - Access tokens expire, but the refresh token is restored too, so Claude Code re-refreshes automatically after a switch. - OAuth refresh tokens rotate on every use. To keep snapshots valid, `ccswitch` - re-captures the outgoing account into its matching profile automatically on - every switch — so an account you actively use won't go stale. + re-captures the outgoing account into **every** profile that shares its token + on each switch — so an account you actively use won't go stale. + +--- + +## Development + +```sh +cargo build +cargo test +cargo fmt +cargo clippy --all-targets --all-features -- -D warnings +``` + +Architecture, the ports-and-adapters layout, and the coverage discipline are +documented in [`AGENTS.md`](AGENTS.md). ## License -MIT +MIT — see [`LICENSE`](LICENSE). Copyright (c) 2026 Chen Lei. diff --git a/legacy-fish/LICENSE b/legacy-fish/LICENSE new file mode 100644 index 0000000..2d8670f --- /dev/null +++ b/legacy-fish/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2026 Chen Lei + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/legacy-fish/README.md b/legacy-fish/README.md new file mode 100644 index 0000000..2022284 --- /dev/null +++ b/legacy-fish/README.md @@ -0,0 +1,255 @@ +# ccswitch + +A tiny [fish](https://fishshell.com) plugin to switch between multiple +[Claude Code](https://claude.com/claude-code) accounts — personal, work, +different orgs — and jump straight into a session. + +```fish +ccswitch work # switch to the "work" account and start claude +ccswitch personal -c # switch to "personal", launch claude with -c +ccswitch use work # just switch, don't launch +ccswitch list # see every saved profile (* = active) +``` + +## How it works + +An account is two things that must travel together: + +1. **OAuth tokens** — the real credential. On macOS these live in the login + Keychain (`Claude Code-credentials`); on Linux/others in + `~/.claude/.credentials.json`. `ccswitch` picks the right backend per platform. +2. **Identity** — the `oauthAccount` object and `userID` inside `~/.claude.json`, + which Claude Code validates the token against. + +`ccswitch save ` snapshots both into a plain profile directory. Switching +restores the credential into the platform store and splices only `oauthAccount` +and `userID` back into `~/.claude.json` (backing it up first — the rest of that +file is shared and left untouched). Because a profile is just two JSON files, it +is portable across machines and operating systems. + +## Install + +With [fisher](https://github.com/jorgebucaran/fisher): + +```fish +fisher install mysqto/ccswitch +``` + +Requires [`jq`](https://jqlang.github.io/jq/). + +## Usage + +| Command | Action | +| --- | --- | +| `ccswitch [args...]` | Switch to ``, then start `claude` (extra args passed through) | +| `ccswitch use ` | Switch without launching | +| `ccswitch add ` | Sign in to a new account (`claude auth login`) and save it as `` | +| `ccswitch isolate [args...]` | Run a **concurrent** session isolated to `` (own credential) with memory/history shared across profiles | +| `ccswitch save ` | Save the current account as `` | +| `ccswitch list` / `ls` | List profiles (`*` marks the active one) | +| `ccswitch current` / `whoami` | Show the active account | +| `ccswitch search` / `s` `[scope…]` | Fuzzy-pick a past session (via [`csx`](https://github.com/mysqto/csx)) and resume it | +| `ccswitch rm ` | Delete a profile | + +## Search past sessions + +`ccswitch search` (alias `s`) is an optional bridge to +[`csx`](https://github.com/mysqto/csx), a local index of your AI-coding +sessions. It fuzzy-picks a session and resumes it in the tool that produced it: + +```fish +ccswitch search # sessions for the active tool → fzf → resume +ccswitch search --repo payments # any csx scope flag passes straight through +``` + +It shells out to `csx sessions` (defaulting the scope to the active tool), +previews each transcript with `csx show ` in `fzf`, and resumes the pick +(`claude --resume `, `codex resume `, …). Requires `csx` and `fzf` on +`PATH` (`jq` optional, for a nicer picker list). If `csx` isn't installed, every +other `ccswitch` command still works — this subcommand just prints a hint. + +## Walkthrough + +A complete run, from a fresh install to switching daily. + +### 1. Save the account you're already signed into + +```fish +claude auth status # confirm who you're logged in as +ccswitch save personal # snapshot the active account as "personal" +``` + +```fish +ccswitch list +# * personal you@gmail.com +``` + +The `*` marks the currently active account. + +### 2. Add a second account + +`ccswitch add` signs you in to another account and saves it in one step: + +```fish +ccswitch add work # runs `claude auth login`, then saves it as "work" +``` + +
+Prefer to do it by hand? + +```fish +claude auth login # sign in as the other account (or switch org via /login) +ccswitch save work +``` +
+ +Both are now saved: + +```fish +ccswitch list +# personal you@gmail.com +# * work you@company.com (Acme) +``` + +### 3. Switch and work — the daily loop + +```fish +ccswitch work # become "work" and start a claude session +ccswitch personal -c # become "personal", continue the last conversation +ccswitch use work # just switch, don't launch anything +ccswitch current # you@company.com (Acme) +``` + +One command becomes an account and drops you into a session. Switching also +re-snapshots the account you're leaving, so rotating tokens never go stale. + +### 4. Run two accounts at the same time + +Steps 1–3 swap one machine-global account (sequential — one at a time). To keep +**two live sessions as different accounts concurrently**, use isolated profiles +with shared memory: + +```fish +ccswitch seed # once: copy your ~/.claude memory + history into shared/ +ccswitch isolate work # terminal 1 — sign in once as work +ccswitch isolate personal # terminal 2 — sign in once as personal, at the same time +``` + +Each isolated session has its own credential but shares project memory and +history. Re-running `ccswitch isolate ` reuses the earlier login. (If you +skip `seed`, the first `isolate` warns that memory is empty and asks to confirm.) + +## Same login, multiple orgs + +If one login (e.g. a Claude Team account) belongs to several organizations, +each org is a separate profile — Claude Code issues a distinct org-scoped token +per org. Save one after switching org inside Claude Code (`/login`): + +```fish +ccswitch save org-a # while the first org is active +# switch org in Claude Code, then: +ccswitch save org-b +``` + +`ccswitch list` distinguishes them by account **and** organization, so the same +email can appear more than once with only the active org starred. + +## Concurrent sessions (shared memory, separate accounts) + +`ccswitch ` swaps a single machine-global account, so it is sequential — +one active account at a time. To run **two accounts at once** (two terminals), +use `ccswitch isolate`, which gives each profile its own +[`CLAUDE_CONFIG_DIR`](https://code.claude.com/docs/en/settings): + +```fish +ccswitch isolate work # terminal 1 — signs in once, then reuses +ccswitch isolate personal # terminal 2 — a different account, at the same time +``` + +Each profile keeps its **own credential and identity**, but memory and history +are **shared** — `isolate` symlinks `projects/` (session transcripts + the +`memory/` files), `history.jsonl`, and `CLAUDE.md` from each profile to a common +`shared/` directory. So both accounts see the same project memory and past +sessions while staying logged in as different users. + +Layout (centralized under `~/.claude`, override with `$CCSWITCH_ISOLATE_HOME`): + +``` +~/.claude/profiles/ + ├── shared/ # one real copy of the shared memory/history + │ ├── projects/ + │ ├── history.jsonl + │ └── CLAUDE.md + ├── work/ # CLAUDE_CONFIG_DIR for "work" + │ ├── projects -> ../shared/projects + │ ├── history.jsonl -> ../shared/history.jsonl + │ ├── CLAUDE.md -> ../shared/CLAUDE.md + │ ├── .claude.json # own account identity (NOT shared) + │ └── settings.json # own settings + └── personal/ # CLAUDE_CONFIG_DIR for "personal" (same shared links) +``` + +`ccswitch isolate` with no name lists existing isolated profiles. Existing +non-symlink files in a profile dir are left untouched (never clobbered). + +`shared/` starts **empty** — isolated profiles begin with fresh memory. To carry +your existing memory/history over, seed it once from your default `~/.claude`: + +```fish +ccswitch seed # copies CLAUDE.md, history.jsonl and projects/ from ~/.claude +ccswitch seed # ... or from another config dir +``` + +Re-run `ccswitch seed` anytime to re-sync from the source (source wins on +same-named files). + +While `shared/` is empty, `ccswitch isolate` warns and asks for confirmation +before launching (so you don't start with no memory by accident). The prompt +stops appearing once `shared/` has content — from `ccswitch seed` or from your +first session. + +> Note: this pattern relies on `CLAUDE_CONFIG_DIR` (supported) plus symlinking of +> account-agnostic paths (a community pattern, not officially documented). Auth +> stays isolated; only memory/history is shared. Two sessions writing the same +> project's memory simultaneously can race — low risk in practice. + +## Profile storage + +Profiles live in `$CCSWITCH_HOME` (default `~/.claude/accounts`), one directory +per profile: + +``` +~/.claude/accounts/work/ + ├── credentials.json # OAuth blob + └── account.json # oauthAccount + userID +``` + +Point `$CCSWITCH_HOME` at a synced folder or repo to move profiles between +machines: + +```fish +set -Ux CCSWITCH_HOME ~/vault/claude-accounts +``` + +## ⚠️ These files are secrets + +`credentials.json` holds a live bearer token. If you sync `$CCSWITCH_HOME` with +git or a cloud folder, **encrypt it** — use a private repo with +[git-crypt](https://github.com/AGWA/git-crypt) / [age](https://github.com/FiloSottile/age) / +[SOPS](https://github.com/getsops/sops), or a real secret manager. Never commit +plaintext tokens to a shared or public repo. + +## Notes + +- Quit any running `claude` session before switching — an open session can + rewrite `~/.claude.json` on exit and clobber the swap. `ccswitch` warns when it + detects one. +- Access tokens expire, but the refresh token is restored too, so Claude Code + re-refreshes automatically after a switch. +- OAuth refresh tokens rotate on every use. To keep snapshots valid, `ccswitch` + re-captures the outgoing account into its matching profile automatically on + every switch — so an account you actively use won't go stale. + +## License + +MIT diff --git a/completions/ccswitch.fish b/legacy-fish/completions/ccswitch.fish similarity index 100% rename from completions/ccswitch.fish rename to legacy-fish/completions/ccswitch.fish diff --git a/functions/ccswitch.fish b/legacy-fish/functions/ccswitch.fish similarity index 100% rename from functions/ccswitch.fish rename to legacy-fish/functions/ccswitch.fish diff --git a/src/cli.rs b/src/cli.rs new file mode 100644 index 0000000..2a7014e --- /dev/null +++ b/src/cli.rs @@ -0,0 +1,2703 @@ +//! Command-line surface: the parsed [`Command`] model and the [`App`] dispatch +//! logic that maps subcommands onto the orchestration layer. +//! +//! Every decision here — the `clap` argument parser, argument validation, +//! reserved-word checks, symlink planning, isolate/seed bookkeeping, search +//! scope resolution, and shell-completion generation — is pure logic exercised +//! by unit tests with a fake [`System`] and temporary directories. The real +//! process-spawning adapter (launching `claude`, `fzf`, `csx`, creating +//! symlinks, prompting, and replacing the process via `exec`) lives behind the +//! [`System`] port in [`crate::cli_shim`], which owns only the real-environment +//! wiring. + +use crate::config; +use crate::creds::CredentialStore; +use crate::error::{Error, Result}; +use crate::store::{Store, TokenScope}; +use crate::switch::Switcher; +use clap::{CommandFactory, Parser, Subcommand}; +use clap_complete::{generate, Shell}; +use serde_json::Value; +use std::ffi::OsString; +use std::fs; +use std::io::Write; +use std::path::{Path, PathBuf}; + +/// Subcommand words a profile may not be named, to keep the bare +/// `ccswitch ` dispatch unambiguous. +pub const RESERVED: &[&str] = &[ + "save", "add", "isolate", "iso", "seed", "search", "s", "list", "ls", "current", "whoami", + "use", "rm", "remove", "delete", "help", +]; + +/// Whether `name` collides with a reserved subcommand word. +#[must_use] +pub fn is_reserved(name: &str) -> bool { + RESERVED.contains(&name) +} + +/// The parsed command, decoupled from the `clap` types so all dispatch logic +/// is testable by constructing values directly. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Command { + /// Sign in a new account and save it as a profile. + Add { + /// Profile name. + name: String, + /// Overwrite an existing profile of the same name. + force: bool, + }, + /// Snapshot the active account into a profile. + Save { + /// Profile name. + name: String, + /// Overwrite an existing profile of the same name. + force: bool, + }, + /// Restore a profile as the active account, without launching `claude`. + Use { + /// Profile name. + name: String, + }, + /// List saved profiles. + List, + /// Show the active account. + Current, + /// Delete a saved profile. + Rm { + /// Profile name. + name: String, + }, + /// Run a concurrent session isolated to a per-profile config dir. + Isolate { + /// Isolated profile name; `None` lists existing isolates. + name: Option, + /// Extra arguments forwarded to `claude`. + args: Vec, + }, + /// Seed the shared isolate memory from `~/.claude` (or `dir`). + Seed { + /// Optional source directory. + dir: Option, + }, + /// Fuzzy-pick and resume a past session via `csx` + `fzf`. + Search { + /// Scope arguments forwarded to `csx sessions`. + scope: Vec, + }, + /// Bare `ccswitch [args...]`: switch then launch `claude`. + Bare { + /// Profile name. + name: String, + /// Extra arguments forwarded to `claude`. + args: Vec, + }, + /// Print a shell completion script to stdout. + Completions { + /// The shell to generate completions for. + shell: Shell, + }, + /// Print usage. + Help, +} + +/// `ccswitch` — switch between multiple Claude Code accounts. +/// +/// The `clap` derive front end. Kept here (rather than in the shim) so parsing +/// every subcommand, flag, and alias is exercised by unit tests. +#[derive(Parser, Debug)] +#[command( + name = "ccswitch", + version, + about = "Switch between multiple Claude Code accounts", + disable_help_subcommand = true +)] +pub struct Cli { + /// The chosen subcommand, or `None` for bare `ccswitch`. + #[command(subcommand)] + pub command: Option, +} + +/// The `clap`-parsed subcommand, mapped onto the internal [`Command`] model. +#[derive(Subcommand, Debug)] +pub enum Sub { + /// Sign in a new account and save it as a profile. + Add { + /// Profile name. + name: String, + /// Overwrite an existing profile of the same name. + #[arg(long)] + force: bool, + }, + /// Snapshot the active account into a profile. + Save { + /// Profile name. + name: String, + /// Overwrite an existing profile of the same name. + #[arg(long)] + force: bool, + }, + /// Restore a profile as the active account. + Use { + /// Profile name. + name: String, + }, + /// List saved profiles. + #[command(visible_alias = "ls")] + List, + /// Show the active account. + #[command(visible_alias = "whoami")] + Current, + /// Delete a saved profile. + #[command(visible_aliases = ["remove", "delete"])] + Rm { + /// Profile name. + name: String, + }, + /// Run a concurrent session isolated to a per-profile config dir. + #[command(visible_alias = "iso")] + Isolate { + /// Isolated profile name; omit to list existing isolates. + name: Option, + /// Extra arguments forwarded to `claude`. + #[arg(trailing_var_arg = true, allow_hyphen_values = true)] + args: Vec, + }, + /// Seed the shared isolate memory from `~/.claude` (or a directory). + Seed { + /// Optional source directory. + dir: Option, + }, + /// Fuzzy-pick and resume a past session via `csx` + `fzf`. + #[command(visible_alias = "s")] + Search { + /// Scope arguments forwarded to `csx sessions`. + #[arg(trailing_var_arg = true, allow_hyphen_values = true)] + scope: Vec, + }, + /// Print a shell completion script to stdout. + Completions { + /// The shell to generate completions for. + shell: Shell, + }, + /// Bare `ccswitch [args...]`, or `help`. + #[command(external_subcommand)] + External(Vec), +} + +impl From> for Command { + fn from(sub: Option) -> Self { + match sub { + None => Command::Help, + Some(Sub::Add { name, force }) => Command::Add { name, force }, + Some(Sub::Save { name, force }) => Command::Save { name, force }, + Some(Sub::Use { name }) => Command::Use { name }, + Some(Sub::List) => Command::List, + Some(Sub::Current) => Command::Current, + Some(Sub::Rm { name }) => Command::Rm { name }, + Some(Sub::Isolate { name, args }) => Command::Isolate { name, args }, + Some(Sub::Seed { dir }) => Command::Seed { dir }, + Some(Sub::Search { scope }) => Command::Search { scope }, + Some(Sub::Completions { shell }) => Command::Completions { shell }, + Some(Sub::External(mut parts)) => { + let name = parts.remove(0); + if name == "help" { + Command::Help + } else { + Command::Bare { name, args: parts } + } + } + } + } +} + +/// Parse an argument iterator into the internal [`Command`] model. +/// +/// # Errors +/// +/// Returns the `clap` error for a parse failure or for the built-in `--help` +/// / `--version` flags, so the caller can render it and exit. +pub fn parse_from(args: I) -> std::result::Result +where + I: IntoIterator, + T: Into + Clone, +{ + Ok(Cli::try_parse_from(args)?.command.into()) +} + +/// Write a shell completion script for `ccswitch` to `out`. +pub fn generate_completions(shell: Shell, out: &mut dyn Write) { + let mut cmd = Cli::command(); + generate(shell, &mut cmd, "ccswitch", out); +} + +/// The side-effecting operations the CLI needs, behind a port so the decision +/// logic can be tested with a fake. The real adapter is in +/// [`crate::cli_shim`]. +pub trait System { + /// Run `claude auth login`, returning whether it succeeded. + /// + /// # Errors + /// + /// Returns an error if the process could not be spawned. + fn claude_login(&self) -> Result; + + /// Whether `program` is found on `PATH`. + fn command_exists(&self, program: &str) -> bool; + + /// Whether a `claude` process is currently running. + fn claude_is_running(&self) -> bool; + + /// Create (or replace) a symlink at `link` pointing to `target`. + /// + /// # Errors + /// + /// Returns an error if the link could not be created. + fn make_symlink(&self, target: &Path, link: &Path) -> Result<()>; + + /// Prompt the user with `prompt` for a yes/no answer. + /// + /// # Errors + /// + /// Returns an error if the prompt could not be read. + fn confirm(&self, prompt: &str) -> Result; + + /// Run `csx current --json` and return its stdout. + /// + /// # Errors + /// + /// Returns an error if the process could not be spawned. + fn csx_current(&self) -> Result>; + + /// Run `csx sessions --json ` and return its stdout. + /// + /// # Errors + /// + /// Returns an error if the process could not be spawned. + fn csx_sessions(&self, scope: &[String]) -> Result>; + + /// Pipe `rows` into `fzf` (with `preview` as its preview command) and + /// return the selected line, or `None` when the user cancels. + /// + /// # Errors + /// + /// Returns an error if `fzf` could not be spawned. + fn fzf_pick(&self, rows: &str, preview: &str) -> Result>; + + /// Replace the current process with `program args...`, layering `envs` on + /// top of the inherited environment. On success this never returns. + /// + /// # Errors + /// + /// Returns an error if the program could not be executed. + fn exec(&self, program: &str, args: &[String], envs: &[(String, String)]) -> Result<()>; +} + +/// Bundled output sinks so every message is captured in tests. +pub struct Io<'a> { + /// Normal (stdout) output. + pub out: &'a mut dyn Write, + /// Diagnostic (stderr) output. + pub err: &'a mut dyn Write, +} + +/// Filesystem locations the CLI operates on, resolved from the environment. +#[derive(Debug, Clone)] +pub struct Paths { + /// Path to `~/.claude.json`. + pub config: PathBuf, + /// Base directory holding isolated profiles. + pub isolate_base: PathBuf, + /// Default source directory for `seed` (`~/.claude`). + pub seed_default: PathBuf, +} + +/// Resolve the profile-store root: `$CCSWITCH_HOME` or `~/.claude/accounts`. +#[must_use] +pub fn ccswitch_home(var: Option, home: &Path) -> PathBuf { + non_empty(var).map_or_else(|| home.join(".claude").join("accounts"), PathBuf::from) +} + +/// Resolve the isolate base: `$CCSWITCH_ISOLATE_HOME` or `~/.claude/profiles`. +#[must_use] +pub fn isolate_home(var: Option, home: &Path) -> PathBuf { + non_empty(var).map_or_else(|| home.join(".claude").join("profiles"), PathBuf::from) +} + +/// The `~/.claude.json` config path for a home directory. +#[must_use] +pub fn config_path(home: &Path) -> PathBuf { + home.join(".claude.json") +} + +/// The `~/.claude` directory for a home directory. +#[must_use] +pub fn claude_dir(home: &Path) -> PathBuf { + home.join(".claude") +} + +/// Treat an empty string the same as an unset variable. +fn non_empty(var: Option) -> Option { + var.filter(|s| !s.is_empty()) +} + +/// What to do with a would-be symlink at a given path. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum LinkPlan { + /// The path is free; create the link. + Create, + /// The path is already a symlink; replace it. + Replace, + /// The path exists as a non-symlink; leave it and warn. + SkipExists, +} + +/// Decide how to (re)create the symlink at `link`. +#[must_use] +pub fn plan_link(link: &Path) -> LinkPlan { + if link.is_symlink() { + LinkPlan::Replace + } else if link.exists() { + LinkPlan::SkipExists + } else { + LinkPlan::Create + } +} + +/// Whether the shared isolate directory holds any seeded memory or history. +#[must_use] +pub fn shared_is_seeded(shared: &Path) -> bool { + if file_is_non_empty(&shared.join("history.jsonl")) + || file_is_non_empty(&shared.join("CLAUDE.md")) + { + return true; + } + dir_has_entry(&shared.join("projects")) +} + +/// Whether `path` is a file with a non-zero length. +fn file_is_non_empty(path: &Path) -> bool { + fs::metadata(path).is_ok_and(|m| m.is_file() && m.len() > 0) +} + +/// Whether `dir` exists and contains at least one entry. +fn dir_has_entry(dir: &Path) -> bool { + fs::read_dir(dir).is_ok_and(|mut entries| entries.next().is_some()) +} + +/// The `--tool ` override embedded in a search scope, if any. +#[must_use] +pub fn tool_flag_value(scope: &[String]) -> Option { + let mut it = scope.iter(); + while let Some(arg) = it.next() { + if arg == "--tool" { + return it.next().cloned(); + } + } + None +} + +/// Parse `csx sessions --json` output into `id\tlabel` rows for `fzf`. +/// +/// # Errors +/// +/// Returns an error if the bytes are not a JSON array. +pub fn parse_session_rows(json: &[u8]) -> Result> { + let sessions: Vec = serde_json::from_slice(json)?; + Ok(sessions + .iter() + .map(|s| { + let field = |k: &str| s.get(k).and_then(Value::as_str).unwrap_or("-"); + let id = s.get("session_id").and_then(Value::as_str).unwrap_or(""); + let msgs = s + .get("msg_count") + .and_then(Value::as_u64) + .map_or_else(|| "0".to_string(), |n| n.to_string()); + format!( + "{id}\t{} {} {} ({msgs} msgs)", + field("tool"), + field("project_name"), + field("git_branch"), + ) + }) + .collect()) +} + +/// The tool of the first entry in `csx current --json` output, if present. +#[must_use] +pub fn parse_current_tool(json: &[u8]) -> Option { + let sessions: Vec = serde_json::from_slice(json).ok()?; + sessions + .first()? + .get("tool") + .and_then(Value::as_str) + .filter(|t| !t.is_empty()) + .map(str::to_string) +} + +/// Orchestrates the subcommands over the credential store, profile store, and +/// [`System`] port. +pub struct App<'a> { + system: &'a dyn System, + creds: &'a dyn CredentialStore, + store: &'a Store, + paths: Paths, + scope: TokenScope, +} + +impl<'a> App<'a> { + /// Build an app over its ports and resolved paths. + pub fn new( + system: &'a dyn System, + creds: &'a dyn CredentialStore, + store: &'a Store, + paths: Paths, + scope: TokenScope, + ) -> Self { + Self { + system, + creds, + store, + paths, + scope, + } + } + + fn switcher(&self) -> Switcher<'_> { + Switcher::new( + self.creds, + self.store, + self.paths.config.clone(), + self.scope, + ) + } + + /// Route a parsed command to its handler. + /// + /// # Errors + /// + /// Propagates the handler's error. + pub fn dispatch(&self, io: &mut Io<'_>, command: Command) -> Result<()> { + match command { + Command::Add { name, force } => self.add(io, &name, force), + Command::Save { name, force } => self.save(io, &name, force), + Command::Use { name } => self.use_profile(io, &name), + Command::List => self.list(io), + Command::Current => self.current(io), + Command::Rm { name } => self.rm(io, &name), + Command::Isolate { name, args } => self.isolate(io, name.as_deref(), &args), + Command::Seed { dir } => self.seed(io, dir.as_deref()), + Command::Search { scope } => self.search(io, &scope), + Command::Bare { name, args } => self.bare(io, &name, &args), + Command::Completions { shell } => self.completions(io, shell), + Command::Help => self.help(io), + } + } + + /// Print a shell completion script to stdout. + fn completions(&self, io: &mut Io<'_>, shell: Shell) -> Result<()> { + generate_completions(shell, io.out); + Ok(()) + } + + /// Sign in a new account and save it as `name`. + fn add(&self, io: &mut Io<'_>, name: &str, force: bool) -> Result<()> { + self.reject_reserved(name)?; + if self.store.contains(name) && !force { + return Err(Error::Invalid(format!( + "profile '{name}' already exists (rm it first, or pass --force)" + ))); + } + writeln!( + io.out, + "signing in as '{name}' (a browser window will open)..." + )?; + if !self.system.claude_login()? { + return Err(Error::Invalid( + "login did not complete — nothing saved".to_string(), + )); + } + self.save(io, name, force) + } + + /// Snapshot the active account into `name`. + fn save(&self, io: &mut Io<'_>, name: &str, force: bool) -> Result<()> { + self.reject_reserved(name)?; + let account = self.switcher().save(name, force)?; + writeln!(io.out, "saved profile '{name}' ({})", email_of(&account))?; + Ok(()) + } + + /// Restore `name` as the active account. + fn use_profile(&self, io: &mut Io<'_>, name: &str) -> Result<()> { + if self.system.claude_is_running() { + writeln!( + io.err, + "warning: a running 'claude' may overwrite ~/.claude.json on exit; quit it first" + )?; + } + let account = self.switcher().activate(name)?; + writeln!(io.out, "switched to '{name}' ({})", email_of(&account))?; + Ok(()) + } + + /// List saved profiles, marking the active one. + fn list(&self, io: &mut Io<'_>) -> Result<()> { + let active_key = config::load(&self.paths.config) + .ok() + .map(|c| config::account_of(&c).key()); + let profiles = self.store.list()?; + if profiles.is_empty() { + writeln!( + io.out, + "no profiles yet — save one with 'ccswitch save '" + )?; + return Ok(()); + } + for summary in profiles { + let account = &summary.account; + let key = account.key(); + let mark = if key != "|" && Some(&key) == active_key.as_ref() { + "* " + } else { + " " + }; + let email = email_of(account); + if account.org.is_empty() { + writeln!(io.out, "{mark}{:<16} {email}", summary.name)?; + } else { + writeln!( + io.out, + "{mark}{:<16} {email} ({})", + summary.name, account.org + )?; + } + } + Ok(()) + } + + /// Show the active account. + fn current(&self, io: &mut Io<'_>) -> Result<()> { + let config = config::load(&self.paths.config) + .map_err(|_| Error::Invalid(format!("{} not found", self.paths.config.display())))?; + let account = config::account_of(&config); + if account.org.is_empty() { + writeln!(io.out, "{}", email_of(&account))?; + } else { + writeln!(io.out, "{} ({})", email_of(&account), account.org)?; + } + Ok(()) + } + + /// Delete a saved profile. + fn rm(&self, io: &mut Io<'_>, name: &str) -> Result<()> { + self.store.remove(name)?; + writeln!(io.out, "removed profile '{name}'")?; + Ok(()) + } + + /// Switch to `name`, then replace the process with `claude args...`. + fn bare(&self, io: &mut Io<'_>, name: &str, args: &[String]) -> Result<()> { + self.use_profile(io, name)?; + self.system.exec("claude", args, &[]) + } + + /// Run a concurrent session isolated to `name`'s config dir, sharing memory + /// through symlinks into the shared directory. + fn isolate(&self, io: &mut Io<'_>, name: Option<&str>, args: &[String]) -> Result<()> { + let base = &self.paths.isolate_base; + let shared = base.join("shared"); + let Some(name) = name else { + return self.list_isolates(io, base); + }; + if name == "shared" || is_reserved(name) { + return Err(Error::ReservedName(name.to_string())); + } + + let dir = base.join(name); + fs::create_dir_all(shared.join("projects"))?; + fs::create_dir_all(&dir)?; + touch(&shared.join("history.jsonl"))?; + touch(&shared.join("CLAUDE.md"))?; + + for entry in ["projects", "history.jsonl", "CLAUDE.md"] { + self.link_into(io, &shared.join(entry), &dir.join(entry))?; + } + + if !shared_is_seeded(&shared) { + writeln!( + io.err, + "warning: shared isolate memory is empty — this session starts with no" + )?; + writeln!( + io.err, + " history or CLAUDE.md. Run 'ccswitch seed' first to import your ~/.claude memory." + )?; + if !self + .system + .confirm(&format!(" launch '{name}' anyway? [y/N] "))? + { + return Err(Error::Invalid("aborted — nothing launched".to_string())); + } + } + + writeln!( + io.out, + "launching isolated '{name}' — CLAUDE_CONFIG_DIR={} (memory shared via {})", + dir.display(), + shared.display() + )?; + writeln!(io.out, "(first run for a profile will ask you to sign in)")?; + let env = vec![( + "CLAUDE_CONFIG_DIR".to_string(), + dir.to_string_lossy().into_owned(), + )]; + self.system.exec("claude", args, &env) + } + + /// List existing isolated profiles under `base`. + fn list_isolates(&self, io: &mut Io<'_>, base: &Path) -> Result<()> { + writeln!(io.out, "isolated profiles in {}:", base.display())?; + let mut any = false; + if let Ok(entries) = fs::read_dir(base) { + let mut names: Vec = entries + .flatten() + .filter(|e| e.path().is_dir()) + .map(|e| e.file_name().to_string_lossy().into_owned()) + .filter(|n| n != "shared" && base.join(n).join("projects").is_symlink()) + .collect(); + names.sort(); + for name in names { + any = true; + writeln!(io.out, " {name}")?; + } + } + if !any { + writeln!(io.out, " (none yet)")?; + } + writeln!(io.out, "usage: ccswitch isolate [claude args...]")?; + Ok(()) + } + + /// Apply a [`plan_link`] decision for one shared entry. + fn link_into(&self, io: &mut Io<'_>, target: &Path, link: &Path) -> Result<()> { + match plan_link(link) { + LinkPlan::Create | LinkPlan::Replace => self.system.make_symlink(target, link), + LinkPlan::SkipExists => { + writeln!( + io.err, + "warning: {} exists and is not a symlink — leaving it as-is", + link.display() + )?; + Ok(()) + } + } + } + + /// Copy `CLAUDE.md`, `history.jsonl`, and `projects/` from a source into the + /// shared isolate directory. + fn seed(&self, io: &mut Io<'_>, dir: Option<&str>) -> Result<()> { + let src = dir.map_or_else(|| self.paths.seed_default.clone(), PathBuf::from); + if !src.is_dir() { + return Err(Error::Invalid(format!( + "source '{}' not found", + src.display() + ))); + } + let shared = self.paths.isolate_base.join("shared"); + fs::create_dir_all(shared.join("projects"))?; + writeln!( + io.out, + "seeding shared memory in {} from {} ...", + shared.display(), + src.display() + )?; + let mut did = false; + for file in ["CLAUDE.md", "history.jsonl"] { + let from = src.join(file); + if from.is_file() { + fs::copy(&from, shared.join(file))?; + writeln!(io.out, " {file}")?; + did = true; + } + } + let projects = src.join("projects"); + if projects.is_dir() { + copy_dir_recursive(&projects, &shared.join("projects"))?; + writeln!(io.out, " projects/ (transcripts + memory)")?; + did = true; + } + if did { + writeln!( + io.out, + "done — isolate profiles now share this memory/history" + )?; + } else { + writeln!(io.out, " nothing to seed from {}", src.display())?; + } + Ok(()) + } + + /// Fuzzy-pick a past session via `csx` + `fzf` and resume it. + fn search(&self, io: &mut Io<'_>, scope: &[String]) -> Result<()> { + if !self.system.command_exists("csx") { + return Err(Error::Invalid( + "csx not found on PATH — see github.com/mysqto/csx".to_string(), + )); + } + if !self.system.command_exists("fzf") { + return Err(Error::Invalid("fzf not found on PATH".to_string())); + } + + let explicit = tool_flag_value(scope); + let tool = explicit.clone().or_else(|| self.default_tool()); + let effective: Vec = if explicit.is_some() { + scope.to_vec() + } else if let Some(tool) = &tool { + let mut v = vec!["--tool".to_string(), tool.clone()]; + v.extend_from_slice(scope); + v + } else { + scope.to_vec() + }; + + let rows = parse_session_rows(&self.system.csx_sessions(&effective)?)?; + if rows.is_empty() { + return Err(Error::Invalid("no sessions matched".to_string())); + } + let Some(picked) = self.system.fzf_pick(&rows.join("\n"), "csx show {1}")? else { + return Ok(()); + }; + let id = picked.split('\t').next().unwrap_or("").trim(); + if id.is_empty() { + return Ok(()); + } + self.resume(io, tool.as_deref(), id) + } + + /// The active tool reported by `csx current`, ignoring any failure. + fn default_tool(&self) -> Option { + parse_current_tool(&self.system.csx_current().ok()?) + } + + /// Resume session `id` with the command for `tool`. + fn resume(&self, _io: &mut Io<'_>, tool: Option<&str>, id: &str) -> Result<()> { + let (program, args) = match tool { + Some("codex") => ("codex", vec!["resume".to_string(), id.to_string()]), + None | Some("" | "claude-code") => { + ("claude", vec!["--resume".to_string(), id.to_string()]) + } + Some(other) => { + return Err(Error::Invalid(format!( + "don't know how to resume tool '{other}' (session {id})" + ))) + } + }; + self.system.exec(program, &args, &[]) + } + + /// Print usage. + fn help(&self, io: &mut Io<'_>) -> Result<()> { + write!(io.out, "{}", help_text())?; + Ok(()) + } + + fn reject_reserved(&self, name: &str) -> Result<()> { + if is_reserved(name) { + Err(Error::ReservedName(name.to_string())) + } else { + Ok(()) + } + } +} + +/// The email of an account, or `unknown` when absent. +fn email_of(account: &crate::model::Account) -> String { + if account.email.is_empty() { + "unknown".to_string() + } else { + account.email.clone() + } +} + +/// Create an empty file at `path` when it does not already exist. +fn touch(path: &Path) -> Result<()> { + if !path.exists() { + fs::write(path, "")?; + } + Ok(()) +} + +/// Recursively copy the contents of `src` into `dst`. +fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<()> { + fs::create_dir_all(dst)?; + for entry in fs::read_dir(src)? { + let entry = entry?; + let from = entry.path(); + let to = dst.join(entry.file_name()); + if entry.file_type()?.is_dir() { + copy_dir_recursive(&from, &to)?; + } else { + fs::copy(&from, &to)?; + } + } + Ok(()) +} + +/// The `ccswitch help` usage text. +#[must_use] +pub fn help_text() -> String { + let lines = [ + "ccswitch — switch between multiple Claude Code accounts", + "", + "usage:", + " ccswitch [args...] switch to and start a claude session", + " ccswitch use switch to without launching claude", + " ccswitch add sign in to a new account and save it as ", + " ccswitch save save the current account as ", + " ccswitch isolate run a concurrent session isolated to ", + " ccswitch seed [dir] seed the shared isolate memory from ~/.claude", + " ccswitch search [scope] fuzzy-pick a past session (via csx) and resume it", + " ccswitch list | ls list saved profiles (* marks the active one)", + " ccswitch current | whoami show the active account", + " ccswitch rm delete a saved profile", + " ccswitch completions print a completion script (bash|zsh|fish|...)", + " ccswitch help show this help", + "", + "profiles live in $CCSWITCH_HOME (default ~/.claude/accounts).", + "isolated profiles live in $CCSWITCH_ISOLATE_HOME (default ~/.claude/profiles).", + ]; + let mut text = lines.join("\n"); + text.push('\n'); + text +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + use std::cell::RefCell; + use std::path::PathBuf; + use std::sync::atomic::{AtomicU64, Ordering}; + + // ---- fakes ------------------------------------------------------------- + + struct FakeCreds { + blob: RefCell>, + acct: Option, + } + + impl FakeCreds { + fn with(blob: Option<&str>, acct: Option<&str>) -> Self { + Self { + blob: RefCell::new(blob.map(str::to_string)), + acct: acct.map(str::to_string), + } + } + } + + impl CredentialStore for FakeCreds { + fn read(&self) -> Result> { + Ok(self.blob.borrow().clone()) + } + fn write(&self, blob: &str, _acct: &str) -> Result<()> { + *self.blob.borrow_mut() = Some(blob.to_string()); + Ok(()) + } + fn account_attr(&self) -> Result> { + Ok(self.acct.clone()) + } + } + + /// A recorded `exec` call: program, args, and extra environment. + type ExecCall = (String, Vec, Vec<(String, String)>); + + #[derive(Default)] + struct FakeSystem { + login_ok: bool, + login_err: bool, + running: bool, + has_csx: bool, + has_fzf: bool, + confirm_yes: bool, + confirm_err: bool, + current: Option>, + current_err: bool, + sessions: Vec, + sessions_err: bool, + pick: Option, + pick_err: bool, + symlink_err: bool, + exec_err: bool, + links: RefCell>, + execs: RefCell>, + sessions_scope: RefCell>, + } + + impl System for FakeSystem { + fn claude_login(&self) -> Result { + if self.login_err { + return Err(Error::Invalid("spawn".to_string())); + } + Ok(self.login_ok) + } + fn command_exists(&self, program: &str) -> bool { + (program == "csx" && self.has_csx) || (program == "fzf" && self.has_fzf) + } + fn claude_is_running(&self) -> bool { + self.running + } + fn make_symlink(&self, target: &Path, link: &Path) -> Result<()> { + if self.symlink_err { + return Err(Error::Invalid("symlink".to_string())); + } + self.links + .borrow_mut() + .push((target.to_path_buf(), link.to_path_buf())); + // Actually create it so downstream planning sees a symlink. + #[cfg(unix)] + { + let _ = std::fs::remove_file(link); + std::os::unix::fs::symlink(target, link)?; + } + Ok(()) + } + fn confirm(&self, _prompt: &str) -> Result { + if self.confirm_err { + return Err(Error::Invalid("confirm".to_string())); + } + Ok(self.confirm_yes) + } + fn csx_current(&self) -> Result> { + if self.current_err { + return Err(Error::Invalid("csx".to_string())); + } + Ok(self.current.clone().unwrap_or_default()) + } + fn csx_sessions(&self, scope: &[String]) -> Result> { + *self.sessions_scope.borrow_mut() = scope.to_vec(); + if self.sessions_err { + return Err(Error::Invalid("csx".to_string())); + } + Ok(self.sessions.clone()) + } + fn fzf_pick(&self, _rows: &str, _preview: &str) -> Result> { + if self.pick_err { + return Err(Error::Invalid("fzf".to_string())); + } + Ok(self.pick.clone()) + } + fn exec(&self, program: &str, args: &[String], envs: &[(String, String)]) -> Result<()> { + if self.exec_err { + return Err(Error::Invalid("exec".to_string())); + } + self.execs + .borrow_mut() + .push((program.to_string(), args.to_vec(), envs.to_vec())); + Ok(()) + } + } + + // ---- harness ----------------------------------------------------------- + + fn temp_dir() -> PathBuf { + static COUNTER: AtomicU64 = AtomicU64::new(0); + let base = std::env::temp_dir().join(format!( + "ccswitch-cli-{}-{}", + std::process::id(), + COUNTER.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&base).unwrap(); + base + } + + fn config_json(acct: &str, org: &str, email: &str, org_name: &str) -> Value { + json!({ + "numStartups": 2, + "userID": "uid", + "oauthAccount": { + "accountUuid": acct, + "organizationUuid": org, + "emailAddress": email, + "organizationName": org_name + } + }) + } + + fn write_config(dir: &Path, value: &Value) -> PathBuf { + let path = dir.join(".claude.json"); + fs::write(&path, serde_json::to_string_pretty(value).unwrap()).unwrap(); + path + } + + struct Bufs { + out: Vec, + err: Vec, + } + + impl Bufs { + fn new() -> Self { + Self { + out: Vec::new(), + err: Vec::new(), + } + } + fn io(&mut self) -> Io<'_> { + Io { + out: &mut self.out, + err: &mut self.err, + } + } + fn out(&self) -> String { + String::from_utf8(self.out.clone()).unwrap() + } + fn err(&self) -> String { + String::from_utf8(self.err.clone()).unwrap() + } + } + + fn paths_for(dir: &Path) -> Paths { + Paths { + config: dir.join(".claude.json"), + isolate_base: dir.join("profiles"), + seed_default: dir.join("home-claude"), + } + } + + // ---- pure helpers ------------------------------------------------------ + + #[test] + fn reserved_words_are_rejected() { + assert!(is_reserved("list")); + assert!(is_reserved("help")); + assert!(!is_reserved("dev")); + } + + #[test] + fn path_resolution_prefers_env_then_defaults() { + let home = Path::new("/home/u"); + assert_eq!( + ccswitch_home(None, home), + PathBuf::from("/home/u/.claude/accounts") + ); + assert_eq!( + ccswitch_home(Some(String::new()), home), + PathBuf::from("/home/u/.claude/accounts") + ); + assert_eq!( + ccswitch_home(Some("/custom".to_string()), home), + PathBuf::from("/custom") + ); + assert_eq!( + isolate_home(None, home), + PathBuf::from("/home/u/.claude/profiles") + ); + assert_eq!( + isolate_home(Some("/iso".to_string()), home), + PathBuf::from("/iso") + ); + assert_eq!(config_path(home), PathBuf::from("/home/u/.claude.json")); + assert_eq!(claude_dir(home), PathBuf::from("/home/u/.claude")); + } + + #[test] + fn plan_link_distinguishes_states() { + let dir = temp_dir(); + assert_eq!(plan_link(&dir.join("free")), LinkPlan::Create); + let file = dir.join("file"); + fs::write(&file, "x").unwrap(); + assert_eq!(plan_link(&file), LinkPlan::SkipExists); + #[cfg(unix)] + { + let link = dir.join("link"); + std::os::unix::fs::symlink(&file, &link).unwrap(); + assert_eq!(plan_link(&link), LinkPlan::Replace); + } + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn shared_is_seeded_detects_each_source() { + let dir = temp_dir(); + assert!(!shared_is_seeded(&dir)); + // Empty files/dirs do not count. + fs::write(dir.join("history.jsonl"), "").unwrap(); + fs::write(dir.join("CLAUDE.md"), "").unwrap(); + fs::create_dir_all(dir.join("projects")).unwrap(); + assert!(!shared_is_seeded(&dir)); + // A non-empty history counts. + fs::write(dir.join("history.jsonl"), "line").unwrap(); + assert!(shared_is_seeded(&dir)); + + let dir2 = temp_dir(); + fs::write(dir2.join("CLAUDE.md"), "notes").unwrap(); + assert!(shared_is_seeded(&dir2)); + + let dir3 = temp_dir(); + fs::create_dir_all(dir3.join("projects").join("p")).unwrap(); + assert!(shared_is_seeded(&dir3)); + + fs::remove_dir_all(&dir).unwrap(); + fs::remove_dir_all(&dir2).unwrap(); + fs::remove_dir_all(&dir3).unwrap(); + } + + #[test] + fn tool_flag_value_reads_override() { + assert_eq!( + tool_flag_value(&["--tool".to_string(), "codex".to_string()]), + Some("codex".to_string()) + ); + assert_eq!(tool_flag_value(&["--tool".to_string()]), None); + assert_eq!(tool_flag_value(&["--foo".to_string()]), None); + } + + #[test] + fn parse_session_rows_projects_fields() { + let json = br#"[ + {"session_id":"s1","tool":"claude-code","project_name":"proj","git_branch":"main","msg_count":5}, + {"session_id":"s2"} + ]"#; + let rows = parse_session_rows(json).unwrap(); + assert_eq!(rows[0], "s1\tclaude-code proj main (5 msgs)"); + assert_eq!(rows[1], "s2\t- - - (0 msgs)"); + } + + #[test] + fn parse_session_rows_rejects_non_array() { + assert!(parse_session_rows(b"not json").is_err()); + } + + #[test] + fn parse_current_tool_reads_first_entry() { + assert_eq!( + parse_current_tool(br#"[{"tool":"codex"}]"#), + Some("codex".to_string()) + ); + assert_eq!(parse_current_tool(br#"[{"tool":""}]"#), None); + assert_eq!(parse_current_tool(b"[]"), None); + assert_eq!(parse_current_tool(b"nope"), None); + assert_eq!(parse_current_tool(br#"[{}]"#), None); + } + + #[test] + fn help_text_lists_commands() { + let text = help_text(); + assert!(text.contains("ccswitch ")); + assert!(text.contains("completions")); + assert!(text.ends_with('\n')); + } + + // ---- clap parsing ------------------------------------------------------ + + /// Parse `args` (without the leading binary name) into a [`Command`]. + fn parse(args: &[&str]) -> Command { + let mut argv = vec!["ccswitch"]; + argv.extend_from_slice(args); + parse_from(argv).unwrap() + } + + #[test] + fn parse_no_args_is_help() { + assert_eq!(parse(&[]), Command::Help); + } + + #[test] + fn parse_add_with_and_without_force() { + assert_eq!( + parse(&["add", "dev"]), + Command::Add { + name: "dev".to_string(), + force: false + } + ); + assert_eq!( + parse(&["add", "dev", "--force"]), + Command::Add { + name: "dev".to_string(), + force: true + } + ); + } + + #[test] + fn parse_save_with_and_without_force() { + assert_eq!( + parse(&["save", "dev"]), + Command::Save { + name: "dev".to_string(), + force: false + } + ); + assert_eq!( + parse(&["save", "dev", "--force"]), + Command::Save { + name: "dev".to_string(), + force: true + } + ); + } + + #[test] + fn parse_use() { + assert_eq!( + parse(&["use", "dev"]), + Command::Use { + name: "dev".to_string() + } + ); + } + + #[test] + fn parse_list_and_ls_alias() { + assert_eq!(parse(&["list"]), Command::List); + assert_eq!(parse(&["ls"]), Command::List); + } + + #[test] + fn parse_current_and_whoami_alias() { + assert_eq!(parse(&["current"]), Command::Current); + assert_eq!(parse(&["whoami"]), Command::Current); + } + + #[test] + fn parse_rm_and_aliases() { + for word in ["rm", "remove", "delete"] { + assert_eq!( + parse(&[word, "dev"]), + Command::Rm { + name: "dev".to_string() + } + ); + } + } + + #[test] + fn parse_isolate_with_name_args_and_alias() { + assert_eq!( + parse(&["isolate", "work", "--verbose", "-p"]), + Command::Isolate { + name: Some("work".to_string()), + args: vec!["--verbose".to_string(), "-p".to_string()], + } + ); + assert_eq!( + parse(&["iso"]), + Command::Isolate { + name: None, + args: vec![], + } + ); + } + + #[test] + fn parse_seed_with_and_without_dir() { + assert_eq!(parse(&["seed"]), Command::Seed { dir: None }); + assert_eq!( + parse(&["seed", "/src"]), + Command::Seed { + dir: Some("/src".to_string()) + } + ); + } + + #[test] + fn parse_search_and_alias_with_scope() { + assert_eq!( + parse(&["search", "--tool", "codex"]), + Command::Search { + scope: vec!["--tool".to_string(), "codex".to_string()], + } + ); + assert_eq!(parse(&["s"]), Command::Search { scope: vec![] }); + } + + #[test] + fn parse_completions_for_each_shell() { + let cases = [ + ("bash", Shell::Bash), + ("zsh", Shell::Zsh), + ("fish", Shell::Fish), + ("powershell", Shell::PowerShell), + ("elvish", Shell::Elvish), + ]; + for (word, shell) in cases { + assert_eq!( + parse(&["completions", word]), + Command::Completions { shell } + ); + } + } + + #[test] + fn parse_bare_name_and_args() { + assert_eq!( + parse(&["prod"]), + Command::Bare { + name: "prod".to_string(), + args: vec![], + } + ); + assert_eq!( + parse(&["prod", "--resume", "abc"]), + Command::Bare { + name: "prod".to_string(), + args: vec!["--resume".to_string(), "abc".to_string()], + } + ); + } + + #[test] + fn parse_help_word_is_help() { + assert_eq!(parse(&["help"]), Command::Help); + } + + #[test] + fn parse_help_and_version_flags_error() { + assert_eq!( + parse_from(["ccswitch", "--help"]).unwrap_err().kind(), + clap::error::ErrorKind::DisplayHelp + ); + assert_eq!( + parse_from(["ccswitch", "--version"]).unwrap_err().kind(), + clap::error::ErrorKind::DisplayVersion + ); + } + + #[test] + fn parse_unknown_flag_before_subcommand_errors() { + assert!(parse_from(["ccswitch", "--nope"]).is_err()); + } + + // ---- completion generation --------------------------------------------- + + #[test] + fn generate_completions_emits_shell_appropriate_scripts() { + let cases: [(Shell, &str); 5] = [ + (Shell::Bash, "complete -F"), + (Shell::Zsh, "#compdef ccswitch"), + (Shell::Fish, "complete -c ccswitch"), + (Shell::PowerShell, "Register-ArgumentCompleter"), + (Shell::Elvish, "edit:completion"), + ]; + for (shell, marker) in cases { + let mut buf: Vec = Vec::new(); + generate_completions(shell, &mut buf); + let script = String::from_utf8(buf).unwrap(); + assert!(!script.is_empty(), "{shell:?} produced no output"); + assert!( + script.contains(marker), + "{shell:?} script missing {marker:?}:\n{script}" + ); + assert!(script.contains("ccswitch")); + } + } + + #[test] + fn dispatch_completions_writes_script_to_stdout() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(None, None); + let system = FakeSystem::default(); + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + app.dispatch(&mut bufs.io(), Command::Completions { shell: Shell::Fish }) + .unwrap(); + assert!(bufs.out().contains("complete -c ccswitch")); + fs::remove_dir_all(&dir).unwrap(); + } + + // ---- add --------------------------------------------------------------- + + fn app_env<'a>( + system: &'a FakeSystem, + creds: &'a FakeCreds, + store: &'a Store, + dir: &Path, + ) -> App<'a> { + App::new(system, creds, store, paths_for(dir), TokenScope::PerAccount) + } + + #[test] + fn add_logs_in_then_saves() { + let dir = temp_dir(); + write_config(&dir, &config_json("A", "O", "a@example.com", "Org A")); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(Some("BLOB"), Some("attr")); + let system = FakeSystem { + login_ok: true, + ..Default::default() + }; + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + app.dispatch( + &mut bufs.io(), + Command::Add { + name: "dev".to_string(), + force: false, + }, + ) + .unwrap(); + assert!(bufs.out().contains("signing in as 'dev'")); + assert!(bufs.out().contains("saved profile 'dev' (a@example.com)")); + assert!(store.contains("dev")); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn add_reserved_name_errors() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(Some("BLOB"), None); + let system = FakeSystem::default(); + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + assert!(matches!( + app.dispatch( + &mut bufs.io(), + Command::Add { + name: "list".to_string(), + force: false + } + ), + Err(Error::ReservedName(_)) + )); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn add_existing_without_force_errors_before_login() { + let dir = temp_dir(); + write_config(&dir, &config_json("A", "O", "a@x", "Org")); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(Some("BLOB"), None); + let system = FakeSystem { + login_ok: true, + ..Default::default() + }; + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + app.dispatch( + &mut bufs.io(), + Command::Add { + name: "dev".to_string(), + force: false, + }, + ) + .unwrap(); + // Second add without force fails and does not attempt login. + let err = app + .dispatch( + &mut bufs.io(), + Command::Add { + name: "dev".to_string(), + force: false, + }, + ) + .unwrap_err(); + assert!(matches!(err, Error::Invalid(m) if m.contains("already exists"))); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn add_force_overwrites_existing() { + let dir = temp_dir(); + write_config(&dir, &config_json("A", "O", "a@x", "Org")); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(Some("BLOB"), None); + let system = FakeSystem { + login_ok: true, + ..Default::default() + }; + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + app.save(&mut bufs.io(), "dev", false).unwrap(); + *creds.blob.borrow_mut() = Some("BLOB2".to_string()); + app.dispatch( + &mut bufs.io(), + Command::Add { + name: "dev".to_string(), + force: true, + }, + ) + .unwrap(); + assert_eq!(store.load_credentials("dev").unwrap(), "BLOB2"); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn add_login_failure_saves_nothing() { + let dir = temp_dir(); + write_config(&dir, &config_json("A", "O", "a@x", "Org")); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(Some("BLOB"), None); + let system = FakeSystem { + login_ok: false, + ..Default::default() + }; + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + let err = app + .dispatch( + &mut bufs.io(), + Command::Add { + name: "dev".to_string(), + force: false, + }, + ) + .unwrap_err(); + assert!(matches!(err, Error::Invalid(m) if m.contains("login did not complete"))); + assert!(!store.contains("dev")); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn add_login_spawn_error_propagates() { + let dir = temp_dir(); + write_config(&dir, &config_json("A", "O", "a@x", "Org")); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(Some("BLOB"), None); + let system = FakeSystem { + login_err: true, + ..Default::default() + }; + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + assert!(app + .dispatch( + &mut bufs.io(), + Command::Add { + name: "dev".to_string(), + force: false + } + ) + .is_err()); + fs::remove_dir_all(&dir).unwrap(); + } + + // ---- save -------------------------------------------------------------- + + #[test] + fn save_reserved_name_errors() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(Some("BLOB"), None); + let system = FakeSystem::default(); + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + assert!(matches!( + app.dispatch( + &mut bufs.io(), + Command::Save { + name: "use".to_string(), + force: false + } + ), + Err(Error::ReservedName(_)) + )); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn save_unknown_email_prints_unknown() { + let dir = temp_dir(); + write_config( + &dir, + &json!({ "oauthAccount": { "accountUuid": "A" }, "userID": "u" }), + ); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(Some("BLOB"), None); + let system = FakeSystem::default(); + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + app.dispatch( + &mut bufs.io(), + Command::Save { + name: "dev".to_string(), + force: false, + }, + ) + .unwrap(); + assert!(bufs.out().contains("saved profile 'dev' (unknown)")); + fs::remove_dir_all(&dir).unwrap(); + } + + // ---- use / bare -------------------------------------------------------- + + fn seed_profile(store: &Store, name: &str, acct: &str, org: &str, email: &str) { + store + .save_profile( + name, + "TOKEN", + &json!({ + "oauthAccount": { + "accountUuid": acct, + "organizationUuid": org, + "emailAddress": email, + "organizationName": "Org" + }, + "userID": "uid", + "keychain_account": "attr" + }), + ) + .unwrap(); + } + + #[test] + fn use_switches_and_warns_when_running() { + let dir = temp_dir(); + write_config(&dir, &config_json("B", "OB", "b@x", "Org B")); + let store = Store::new(dir.join("accounts")); + seed_profile(&store, "dev", "A", "OA", "a@example.com"); + let creds = FakeCreds::with(Some("LIVE"), Some("attr")); + let system = FakeSystem { + running: true, + ..Default::default() + }; + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + app.dispatch( + &mut bufs.io(), + Command::Use { + name: "dev".to_string(), + }, + ) + .unwrap(); + assert!(bufs.err().contains("warning: a running 'claude'")); + assert!(bufs.out().contains("switched to 'dev' (a@example.com)")); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn use_missing_profile_errors() { + let dir = temp_dir(); + write_config(&dir, &config_json("B", "OB", "b@x", "Org B")); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(Some("LIVE"), None); + let system = FakeSystem::default(); + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + assert!(matches!( + app.dispatch( + &mut bufs.io(), + Command::Use { + name: "ghost".to_string() + } + ), + Err(Error::ProfileNotFound(_)) + )); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn bare_switches_then_execs_claude() { + let dir = temp_dir(); + write_config(&dir, &config_json("B", "OB", "b@x", "Org B")); + let store = Store::new(dir.join("accounts")); + seed_profile(&store, "dev", "A", "OA", "a@x"); + let creds = FakeCreds::with(Some("LIVE"), Some("attr")); + let system = FakeSystem::default(); + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + app.dispatch( + &mut bufs.io(), + Command::Bare { + name: "dev".to_string(), + args: vec!["--resume".to_string()], + }, + ) + .unwrap(); + let execs = system.execs.borrow(); + assert_eq!(execs[0].0, "claude"); + assert_eq!(execs[0].1, vec!["--resume".to_string()]); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn bare_does_not_exec_when_switch_fails() { + let dir = temp_dir(); + write_config(&dir, &config_json("B", "OB", "b@x", "Org B")); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(Some("LIVE"), None); + let system = FakeSystem::default(); + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + assert!(app + .dispatch( + &mut bufs.io(), + Command::Bare { + name: "ghost".to_string(), + args: vec![] + } + ) + .is_err()); + assert!(system.execs.borrow().is_empty()); + fs::remove_dir_all(&dir).unwrap(); + } + + // ---- list / current / rm ---------------------------------------------- + + #[test] + fn list_marks_active_and_shows_orgs() { + let dir = temp_dir(); + write_config(&dir, &config_json("A", "OA", "a@x", "Org A")); + let store = Store::new(dir.join("accounts")); + seed_profile(&store, "dev", "A", "OA", "a@example.com"); + // A profile with no org name to hit the no-org branch. + store + .save_profile( + "plain", + "T", + &json!({ "oauthAccount": { "accountUuid": "Z", "emailAddress": "z@x" }, "userID": "u" }), + ) + .unwrap(); + let creds = FakeCreds::with(Some("LIVE"), None); + let system = FakeSystem::default(); + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + app.dispatch(&mut bufs.io(), Command::List).unwrap(); + let out = bufs.out(); + assert!(out.contains("* dev")); + assert!(out.contains("a@example.com (Org)")); + assert!(out.contains(" plain")); + assert!(out.contains("z@x")); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn list_without_config_marks_nothing() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + seed_profile(&store, "dev", "A", "OA", "a@x"); + let creds = FakeCreds::with(Some("LIVE"), None); + let system = FakeSystem::default(); + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + app.dispatch(&mut bufs.io(), Command::List).unwrap(); + assert!(!bufs.out().contains("* dev")); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn list_empty_store_hints() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(Some("LIVE"), None); + let system = FakeSystem::default(); + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + app.dispatch(&mut bufs.io(), Command::List).unwrap(); + assert!(bufs.out().contains("no profiles yet")); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn list_propagates_store_error() { + let dir = temp_dir(); + // Root is a file → list errors. + let file_root = dir.join("file"); + fs::write(&file_root, "x").unwrap(); + let store = Store::new(&file_root); + let creds = FakeCreds::with(Some("LIVE"), None); + let system = FakeSystem::default(); + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + assert!(app.dispatch(&mut bufs.io(), Command::List).is_err()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn current_shows_email_and_org() { + let dir = temp_dir(); + write_config(&dir, &config_json("A", "OA", "a@example.com", "Org A")); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(Some("LIVE"), None); + let system = FakeSystem::default(); + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + app.dispatch(&mut bufs.io(), Command::Current).unwrap(); + assert_eq!(bufs.out(), "a@example.com (Org A)\n"); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn current_without_org_shows_email_only() { + let dir = temp_dir(); + write_config(&dir, &json!({ "oauthAccount": { "emailAddress": "a@x" } })); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(Some("LIVE"), None); + let system = FakeSystem::default(); + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + app.dispatch(&mut bufs.io(), Command::Current).unwrap(); + assert_eq!(bufs.out(), "a@x\n"); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn current_without_config_errors() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(Some("LIVE"), None); + let system = FakeSystem::default(); + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + assert!(matches!( + app.dispatch(&mut bufs.io(), Command::Current), + Err(Error::Invalid(m)) if m.contains("not found") + )); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn rm_removes_and_reports() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + seed_profile(&store, "dev", "A", "OA", "a@x"); + let creds = FakeCreds::with(Some("LIVE"), None); + let system = FakeSystem::default(); + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + app.dispatch( + &mut bufs.io(), + Command::Rm { + name: "dev".to_string(), + }, + ) + .unwrap(); + assert!(bufs.out().contains("removed profile 'dev'")); + assert!(!store.contains("dev")); + assert!(matches!( + app.dispatch( + &mut bufs.io(), + Command::Rm { + name: "dev".to_string() + } + ), + Err(Error::ProfileNotFound(_)) + )); + fs::remove_dir_all(&dir).unwrap(); + } + + // ---- help -------------------------------------------------------------- + + #[test] + fn help_prints_usage() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(None, None); + let system = FakeSystem::default(); + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + app.dispatch(&mut bufs.io(), Command::Help).unwrap(); + assert!(bufs + .out() + .contains("switch between multiple Claude Code accounts")); + fs::remove_dir_all(&dir).unwrap(); + } + + // ---- isolate ----------------------------------------------------------- + + fn seed_shared(base: &Path) { + let shared = base.join("shared"); + fs::create_dir_all(shared.join("projects")).unwrap(); + fs::write(shared.join("history.jsonl"), "seeded").unwrap(); + } + + #[test] + fn isolate_links_and_execs_when_seeded() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let base = dir.join("profiles"); + seed_shared(&base); + let creds = FakeCreds::with(None, None); + let system = FakeSystem::default(); + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + app.dispatch( + &mut bufs.io(), + Command::Isolate { + name: Some("work".to_string()), + args: vec!["--verbose".to_string()], + }, + ) + .unwrap(); + assert!(bufs.out().contains("launching isolated 'work'")); + // Three symlinks created; claude exec'd with the config-dir env. + assert_eq!(system.links.borrow().len(), 3); + let execs = system.execs.borrow(); + assert_eq!(execs[0].0, "claude"); + assert_eq!(execs[0].1, vec!["--verbose".to_string()]); + assert_eq!(execs[0].2[0].0, "CLAUDE_CONFIG_DIR"); + assert!(execs[0].2[0].1.ends_with("work")); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn isolate_unseeded_confirm_yes_launches() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(None, None); + let system = FakeSystem { + confirm_yes: true, + ..Default::default() + }; + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + app.dispatch( + &mut bufs.io(), + Command::Isolate { + name: Some("work".to_string()), + args: vec![], + }, + ) + .unwrap(); + assert!(bufs.err().contains("shared isolate memory is empty")); + assert_eq!(system.execs.borrow().len(), 1); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn isolate_unseeded_confirm_no_aborts() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(None, None); + let system = FakeSystem { + confirm_yes: false, + ..Default::default() + }; + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + let err = app + .dispatch( + &mut bufs.io(), + Command::Isolate { + name: Some("work".to_string()), + args: vec![], + }, + ) + .unwrap_err(); + assert!(matches!(err, Error::Invalid(m) if m.contains("aborted"))); + assert!(system.execs.borrow().is_empty()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn isolate_confirm_error_propagates() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(None, None); + let system = FakeSystem { + confirm_err: true, + ..Default::default() + }; + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + assert!(app + .dispatch( + &mut bufs.io(), + Command::Isolate { + name: Some("work".to_string()), + args: vec![] + } + ) + .is_err()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn isolate_reserved_name_errors() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(None, None); + let system = FakeSystem::default(); + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + for name in ["shared", "list"] { + assert!(matches!( + app.dispatch( + &mut bufs.io(), + Command::Isolate { + name: Some(name.to_string()), + args: vec![] + } + ), + Err(Error::ReservedName(_)) + )); + } + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn isolate_symlink_error_propagates() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let base = dir.join("profiles"); + seed_shared(&base); + let creds = FakeCreds::with(None, None); + let system = FakeSystem { + symlink_err: true, + ..Default::default() + }; + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + assert!(app + .dispatch( + &mut bufs.io(), + Command::Isolate { + name: Some("work".to_string()), + args: vec![] + } + ) + .is_err()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn isolate_skips_existing_non_symlink_entry() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let base = dir.join("profiles"); + seed_shared(&base); + // Pre-create a real (non-symlink) projects dir in the profile. + let profile = base.join("work"); + fs::create_dir_all(profile.join("projects")).unwrap(); + let creds = FakeCreds::with(None, None); + let system = FakeSystem::default(); + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + app.dispatch( + &mut bufs.io(), + Command::Isolate { + name: Some("work".to_string()), + args: vec![], + }, + ) + .unwrap(); + assert!(bufs.err().contains("is not a symlink")); + // Only the two non-conflicting entries were linked. + assert_eq!(system.links.borrow().len(), 2); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn isolate_replaces_existing_symlink() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let base = dir.join("profiles"); + seed_shared(&base); + let app_system = FakeSystem::default(); + let creds = FakeCreds::with(None, None); + let app = app_env(&app_system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + // First run creates the links. + app.dispatch( + &mut bufs.io(), + Command::Isolate { + name: Some("work".to_string()), + args: vec![], + }, + ) + .unwrap(); + // Second run sees existing symlinks and replaces them. + app.dispatch( + &mut bufs.io(), + Command::Isolate { + name: Some("work".to_string()), + args: vec![], + }, + ) + .unwrap(); + assert_eq!(app_system.links.borrow().len(), 6); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn isolate_no_name_lists_isolates() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let base = dir.join("profiles"); + seed_shared(&base); + // A valid isolate (projects is a symlink) and noise entries. + let work = base.join("work"); + fs::create_dir_all(&work).unwrap(); + #[cfg(unix)] + std::os::unix::fs::symlink(base.join("shared/projects"), work.join("projects")).unwrap(); + fs::create_dir_all(base.join("notlinked")).unwrap(); + fs::write(base.join("loose"), "x").unwrap(); + let creds = FakeCreds::with(None, None); + let system = FakeSystem::default(); + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + app.dispatch( + &mut bufs.io(), + Command::Isolate { + name: None, + args: vec![], + }, + ) + .unwrap(); + let out = bufs.out(); + assert!(out.contains("isolated profiles in")); + assert!(out.contains(" work")); + assert!(!out.contains("notlinked")); + assert!(out.contains("usage: ccswitch isolate")); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn isolate_no_name_none_yet_when_base_absent() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(None, None); + let system = FakeSystem::default(); + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + app.dispatch( + &mut bufs.io(), + Command::Isolate { + name: None, + args: vec![], + }, + ) + .unwrap(); + assert!(bufs.out().contains("(none yet)")); + fs::remove_dir_all(&dir).unwrap(); + } + + // ---- seed -------------------------------------------------------------- + + #[test] + fn seed_copies_all_sources() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let src = dir.join("home-claude"); + fs::create_dir_all(src.join("projects").join("p")).unwrap(); + fs::write(src.join("CLAUDE.md"), "notes").unwrap(); + fs::write(src.join("history.jsonl"), "h").unwrap(); + fs::write(src.join("projects").join("p").join("t.jsonl"), "t").unwrap(); + let creds = FakeCreds::with(None, None); + let system = FakeSystem::default(); + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + app.dispatch(&mut bufs.io(), Command::Seed { dir: None }) + .unwrap(); + let shared = dir.join("profiles").join("shared"); + assert_eq!( + fs::read_to_string(shared.join("CLAUDE.md")).unwrap(), + "notes" + ); + assert!(shared.join("projects").join("p").join("t.jsonl").exists()); + assert!(bufs.out().contains("done — isolate profiles now share")); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn seed_from_explicit_dir_with_nothing_reports_nothing() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let src = dir.join("empty-src"); + fs::create_dir_all(&src).unwrap(); + let creds = FakeCreds::with(None, None); + let system = FakeSystem::default(); + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + app.dispatch( + &mut bufs.io(), + Command::Seed { + dir: Some(src.to_string_lossy().into_owned()), + }, + ) + .unwrap(); + assert!(bufs.out().contains("nothing to seed")); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn seed_missing_source_errors() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(None, None); + let system = FakeSystem::default(); + let app = app_env(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + // Default source (~/.claude stand-in) does not exist. + assert!(matches!( + app.dispatch(&mut bufs.io(), Command::Seed { dir: None }), + Err(Error::Invalid(m)) if m.contains("not found") + )); + fs::remove_dir_all(&dir).unwrap(); + } + + // ---- search ------------------------------------------------------------ + + fn search_app<'a>( + system: &'a FakeSystem, + creds: &'a FakeCreds, + store: &'a Store, + dir: &Path, + ) -> App<'a> { + app_env(system, creds, store, dir) + } + + #[test] + fn search_requires_csx() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(None, None); + let system = FakeSystem::default(); + let app = search_app(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + assert!(matches!( + app.dispatch(&mut bufs.io(), Command::Search { scope: vec![] }), + Err(Error::Invalid(m)) if m.contains("csx not found") + )); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn search_requires_fzf() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(None, None); + let system = FakeSystem { + has_csx: true, + ..Default::default() + }; + let app = search_app(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + assert!(matches!( + app.dispatch(&mut bufs.io(), Command::Search { scope: vec![] }), + Err(Error::Invalid(m)) if m.contains("fzf not found") + )); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn search_default_tool_prepends_scope_and_resumes_claude() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(None, None); + let system = FakeSystem { + has_csx: true, + has_fzf: true, + current: Some(br#"[{"tool":"claude-code"}]"#.to_vec()), + sessions: br#"[{"session_id":"s1","tool":"claude-code","msg_count":3}]"#.to_vec(), + pick: Some("s1\tclaude-code p b (3 msgs)".to_string()), + ..Default::default() + }; + let app = search_app(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + app.dispatch(&mut bufs.io(), Command::Search { scope: vec![] }) + .unwrap(); + // Scope was prefixed with the discovered tool. + assert_eq!( + *system.sessions_scope.borrow(), + vec!["--tool".to_string(), "claude-code".to_string()] + ); + let execs = system.execs.borrow(); + assert_eq!(execs[0].0, "claude"); + assert_eq!(execs[0].1, vec!["--resume".to_string(), "s1".to_string()]); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn search_explicit_tool_codex_resumes_codex() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(None, None); + let system = FakeSystem { + has_csx: true, + has_fzf: true, + sessions: br#"[{"session_id":"x9","tool":"codex","msg_count":1}]"#.to_vec(), + pick: Some("x9\tcodex p b (1 msgs)".to_string()), + ..Default::default() + }; + let app = search_app(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + app.dispatch( + &mut bufs.io(), + Command::Search { + scope: vec!["--tool".to_string(), "codex".to_string()], + }, + ) + .unwrap(); + // Explicit scope passed through untouched. + assert_eq!( + *system.sessions_scope.borrow(), + vec!["--tool".to_string(), "codex".to_string()] + ); + let execs = system.execs.borrow(); + assert_eq!(execs[0].0, "codex"); + assert_eq!(execs[0].1, vec!["resume".to_string(), "x9".to_string()]); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn search_unknown_tool_errors() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(None, None); + let system = FakeSystem { + has_csx: true, + has_fzf: true, + sessions: br#"[{"session_id":"z","msg_count":1}]"#.to_vec(), + pick: Some("z\t...".to_string()), + ..Default::default() + }; + let app = search_app(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + let err = app + .dispatch( + &mut bufs.io(), + Command::Search { + scope: vec!["--tool".to_string(), "weird".to_string()], + }, + ) + .unwrap_err(); + assert!(matches!(err, Error::Invalid(m) if m.contains("don't know how to resume"))); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn search_no_tool_defaults_to_claude() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(None, None); + // csx current fails → no default tool; scope passes through empty. + let system = FakeSystem { + has_csx: true, + has_fzf: true, + current_err: true, + sessions: br#"[{"session_id":"s","msg_count":1}]"#.to_vec(), + pick: Some("s\t...".to_string()), + ..Default::default() + }; + let app = search_app(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + app.dispatch(&mut bufs.io(), Command::Search { scope: vec![] }) + .unwrap(); + assert!(system.sessions_scope.borrow().is_empty()); + assert_eq!(system.execs.borrow()[0].0, "claude"); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn search_no_sessions_errors() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(None, None); + let system = FakeSystem { + has_csx: true, + has_fzf: true, + current_err: true, + sessions: b"[]".to_vec(), + ..Default::default() + }; + let app = search_app(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + assert!(matches!( + app.dispatch(&mut bufs.io(), Command::Search { scope: vec![] }), + Err(Error::Invalid(m)) if m.contains("no sessions matched") + )); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn search_cancelled_pick_is_ok() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(None, None); + let system = FakeSystem { + has_csx: true, + has_fzf: true, + current_err: true, + sessions: br#"[{"session_id":"s","msg_count":1}]"#.to_vec(), + pick: None, + ..Default::default() + }; + let app = search_app(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + app.dispatch(&mut bufs.io(), Command::Search { scope: vec![] }) + .unwrap(); + assert!(system.execs.borrow().is_empty()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn search_empty_id_is_ok() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(None, None); + let system = FakeSystem { + has_csx: true, + has_fzf: true, + current_err: true, + sessions: br#"[{"session_id":"s","msg_count":1}]"#.to_vec(), + pick: Some("\tlabel-only".to_string()), + ..Default::default() + }; + let app = search_app(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + app.dispatch(&mut bufs.io(), Command::Search { scope: vec![] }) + .unwrap(); + assert!(system.execs.borrow().is_empty()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn search_sessions_spawn_error_propagates() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(None, None); + let system = FakeSystem { + has_csx: true, + has_fzf: true, + current_err: true, + sessions_err: true, + ..Default::default() + }; + let app = search_app(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + assert!(app + .dispatch(&mut bufs.io(), Command::Search { scope: vec![] }) + .is_err()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn search_fzf_error_propagates() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(None, None); + let system = FakeSystem { + has_csx: true, + has_fzf: true, + current_err: true, + sessions: br#"[{"session_id":"s","msg_count":1}]"#.to_vec(), + pick_err: true, + ..Default::default() + }; + let app = search_app(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + assert!(app + .dispatch(&mut bufs.io(), Command::Search { scope: vec![] }) + .is_err()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn search_exec_failure_propagates() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(None, None); + let system = FakeSystem { + has_csx: true, + has_fzf: true, + current_err: true, + sessions: br#"[{"session_id":"s","msg_count":1}]"#.to_vec(), + pick: Some("s\tlabel".to_string()), + exec_err: true, + ..Default::default() + }; + let app = search_app(&system, &creds, &store, &dir); + let mut bufs = Bufs::new(); + assert!(app + .dispatch(&mut bufs.io(), Command::Search { scope: vec![] }) + .is_err()); + fs::remove_dir_all(&dir).unwrap(); + } + + // ---- output-write failures -------------------------------------------- + // + // Every message goes out through a fallible writer; these drive the error + // arm of each `writeln!` by failing on a marker substring. + + /// A writer that errors on any chunk containing `marker`. + struct FailOn { + marker: &'static str, + } + + impl Write for FailOn { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if std::str::from_utf8(buf).is_ok_and(|s| s.contains(self.marker)) { + return Err(std::io::Error::other("write failed")); + } + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + /// Run `command` with `out`/`err` writers that fail on the given markers, + /// asserting the write error surfaces. + fn assert_write_error( + app: &App<'_>, + out_marker: &'static str, + err_marker: &'static str, + command: Command, + ) { + let mut out = FailOn { marker: out_marker }; + let mut err = FailOn { marker: err_marker }; + let mut io = Io { + out: &mut out, + err: &mut err, + }; + assert!(app.dispatch(&mut io, command).is_err()); + } + + #[test] + fn fail_on_writer_flush_is_a_noop() { + let mut w = FailOn { marker: "x" }; + assert!(w.flush().is_ok()); + } + + #[test] + fn write_errors_surface_from_out_messages() { + let dir = temp_dir(); + write_config(&dir, &config_json("A", "OA", "OrgMarker@x", "OrgMarker")); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(Some("BLOB"), Some("attr")); + let system = FakeSystem { + login_ok: true, + ..Default::default() + }; + let base = dir.join("profiles"); + seed_shared(&base); + let seed_src = dir.join("home-claude"); + fs::create_dir_all(&seed_src).unwrap(); + fs::write(seed_src.join("CLAUDE.md"), "notes").unwrap(); + let app = app_env(&system, &creds, &store, &dir); + + // add — the "signing in" banner. + assert_write_error( + &app, + "signing in as", + "\0", + Command::Add { + name: "dev".to_string(), + force: false, + }, + ); + // current — email/org line. + assert_write_error(&app, "OrgMarker", "\0", Command::Current); + // list (empty) — the hint line. + assert_write_error(&app, "no profiles yet", "\0", Command::List); + // isolate — the "launching" banner (shared is seeded, so no prompt). + assert_write_error( + &app, + "launching isolated", + "\0", + Command::Isolate { + name: Some("work".to_string()), + args: vec![], + }, + ); + // seed — the initial "seeding shared memory" line. + assert_write_error( + &app, + "seeding shared memory", + "\0", + Command::Seed { dir: None }, + ); + // seed — the closing "done" line (earlier lines pass through). + assert_write_error(&app, "done — isolate", "\0", Command::Seed { dir: None }); + + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn write_errors_surface_from_list_org_row() { + let dir = temp_dir(); + write_config(&dir, &config_json("A", "OA", "a@x", "Org A")); + let store = Store::new(dir.join("accounts")); + seed_profile(&store, "dev", "A", "OA", "a@x"); + let creds = FakeCreds::with(Some("LIVE"), None); + let system = FakeSystem::default(); + let app = app_env(&system, &creds, &store, &dir); + // The profile row carries org "Org", so failing on it hits the org branch. + assert_write_error(&app, "Org", "\0", Command::List); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn write_errors_surface_from_err_messages() { + let dir = temp_dir(); + write_config(&dir, &config_json("B", "OB", "b@x", "Org B")); + let store = Store::new(dir.join("accounts")); + seed_profile(&store, "dev", "A", "OA", "a@x"); + let creds = FakeCreds::with(Some("LIVE"), Some("attr")); + let system = FakeSystem { + running: true, + ..Default::default() + }; + let app = app_env(&system, &creds, &store, &dir); + // use — the "a running claude" warning goes to err. + assert_write_error( + &app, + "\0", + "warning: a running", + Command::Use { + name: "dev".to_string(), + }, + ); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn write_errors_surface_from_isolate_warnings() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let creds = FakeCreds::with(None, None); + let system = FakeSystem { + confirm_yes: true, + ..Default::default() + }; + let app = app_env(&system, &creds, &store, &dir); + // First warning line to err (memory empty). + assert_write_error( + &app, + "\0", + "shared isolate memory is empty", + Command::Isolate { + name: Some("work".to_string()), + args: vec![], + }, + ); + // Second warning line to err (first passes through). + assert_write_error( + &app, + "\0", + "history or CLAUDE.md", + Command::Isolate { + name: Some("work".to_string()), + args: vec![], + }, + ); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn write_errors_surface_from_skip_symlink_warning() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let base = dir.join("profiles"); + seed_shared(&base); + // Pre-create a non-symlink projects dir so link_into warns to err. + fs::create_dir_all(base.join("work").join("projects")).unwrap(); + let creds = FakeCreds::with(None, None); + let system = FakeSystem::default(); + let app = app_env(&system, &creds, &store, &dir); + assert_write_error( + &app, + "\0", + "is not a symlink", + Command::Isolate { + name: Some("work".to_string()), + args: vec![], + }, + ); + fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/src/cli_shim.rs b/src/cli_shim.rs new file mode 100644 index 0000000..72bb890 --- /dev/null +++ b/src/cli_shim.rs @@ -0,0 +1,192 @@ +//! Real process-spawning adapter and program entry point. +//! +//! Side-effecting implementation of the [`crate::cli::System`] port: launching +//! `claude`, `csx`, and `fzf`, creating symlinks, prompting on the terminal, +//! and replacing the current process via `exec`. This file also owns the +//! real-environment wiring in [`run`] (argv parsing, `$HOME`/`$CCSWITCH_*` +//! resolution, and building the platform stores). It contains no decision +//! logic — every branch of behavior lives in [`crate::cli`] — and is excluded +//! from coverage. + +use crate::cli::{self, App, Io, Paths, System}; +use crate::creds_shim::platform_store; +use crate::error::{Error, Result}; +use crate::store::{Store, TokenScope}; +use std::io::{BufRead, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Command as Proc, Stdio}; + +/// The real system adapter. +struct RealSystem; + +impl System for RealSystem { + fn claude_login(&self) -> Result { + Ok(Proc::new("claude") + .args(["auth", "login"]) + .status()? + .success()) + } + + fn command_exists(&self, program: &str) -> bool { + std::env::var_os("PATH").is_some_and(|paths| { + std::env::split_paths(&paths).any(|dir| dir.join(program).is_file()) + }) + } + + fn claude_is_running(&self) -> bool { + Proc::new("pgrep") + .args(["-x", "claude"]) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .map(|s| s.success()) + .unwrap_or(false) + } + + fn make_symlink(&self, target: &Path, link: &Path) -> Result<()> { + #[cfg(unix)] + { + let _ = std::fs::remove_file(link); + std::os::unix::fs::symlink(target, link)?; + Ok(()) + } + #[cfg(not(unix))] + { + let _ = (target, link); + Err(Error::Invalid( + "symlinks unsupported on this platform".to_string(), + )) + } + } + + fn confirm(&self, prompt: &str) -> Result { + let mut stderr = std::io::stderr(); + write!(stderr, "{prompt}")?; + stderr.flush()?; + let mut line = String::new(); + std::io::stdin().lock().read_line(&mut line)?; + let answer = line.trim().to_ascii_lowercase(); + Ok(answer == "y" || answer == "yes") + } + + fn csx_current(&self) -> Result> { + Ok(Proc::new("csx") + .args(["current", "--json"]) + .output()? + .stdout) + } + + fn csx_sessions(&self, scope: &[String]) -> Result> { + Ok(Proc::new("csx") + .args(["sessions", "--json"]) + .args(scope) + .output()? + .stdout) + } + + fn fzf_pick(&self, rows: &str, preview: &str) -> Result> { + let mut child = Proc::new("fzf") + .args([ + "--with-nth=2..", + "--delimiter=\t", + "--preview", + preview, + "--preview-window=right,60%,wrap", + "--prompt=session> ", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn()?; + child + .stdin + .take() + .ok_or_else(|| Error::Invalid("fzf stdin unavailable".to_string()))? + .write_all(rows.as_bytes())?; + let output = child.wait_with_output()?; + if !output.status.success() { + return Ok(None); + } + let picked = String::from_utf8_lossy(&output.stdout) + .trim_end() + .to_string(); + if picked.is_empty() { + Ok(None) + } else { + Ok(Some(picked)) + } + } + + fn exec(&self, program: &str, args: &[String], envs: &[(String, String)]) -> Result<()> { + #[cfg(unix)] + { + use std::os::unix::process::CommandExt; + let mut cmd = Proc::new(program); + cmd.args(args); + for (key, value) in envs { + cmd.env(key, value); + } + Err(cmd.exec().into()) + } + #[cfg(not(unix))] + { + let status = Proc::new(program) + .args(args) + .envs(envs.iter().cloned()) + .status()?; + if status.success() { + Ok(()) + } else { + Err(Error::Invalid(format!("{program} exited with failure"))) + } + } + } +} + +/// The home directory, falling back to the current directory. +fn home_dir() -> PathBuf { + std::env::var_os("HOME").map_or_else(|| PathBuf::from("."), PathBuf::from) +} + +/// Program entry point: parse arguments, resolve the environment, and dispatch. +/// +/// # Errors +/// +/// Returns an error if the selected subcommand fails. +pub fn run() -> anyhow::Result<()> { + let command = match cli::parse_from(std::env::args_os()) { + Ok(command) => command, + Err(err) => err.exit(), + }; + + let home = home_dir(); + let claude = cli::claude_dir(&home); + let store = Store::new(cli::ccswitch_home( + std::env::var("CCSWITCH_HOME").ok(), + &home, + )); + let creds = platform_store(claude.clone()); + let paths = Paths { + config: cli::config_path(&home), + isolate_base: cli::isolate_home(std::env::var("CCSWITCH_ISOLATE_HOME").ok(), &home), + seed_default: claude, + }; + let system = RealSystem; + let app = App::new( + &system, + creds.as_ref(), + &store, + paths, + TokenScope::PerAccount, + ); + + let stdout = std::io::stdout(); + let stderr = std::io::stderr(); + let mut out = stdout.lock(); + let mut err = stderr.lock(); + let mut io = Io { + out: &mut out, + err: &mut err, + }; + app.dispatch(&mut io, command)?; + Ok(()) +} diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..15722c9 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,294 @@ +//! Reading and splicing the Claude Code `~/.claude.json` configuration file. +//! +//! Claude Code keeps a large amount of unrelated state in `~/.claude.json` +//! alongside the signed-in identity (`oauthAccount` and `userID`). To switch +//! accounts we must swap only that identity in and out while leaving every +//! other key untouched. All of that is plain-file JSON manipulation under a +//! caller-provided path, so it lives here and is unit-tested against a +//! temporary file with no shim. + +use crate::creds::set_permissions_600; +use crate::error::Result; +use crate::model::Account; +use serde_json::{json, Value}; +use std::fs; +use std::path::{Path, PathBuf}; + +/// The two config keys that make up a Claude Code identity snapshot. +const IDENTITY_KEYS: [&str; 2] = ["oauthAccount", "userID"]; + +/// Load `~/.claude.json` from `path` as a JSON value. +/// +/// # Errors +/// +/// Returns an error if the file is missing or is not valid JSON. +pub fn load(path: &Path) -> Result { + let text = fs::read_to_string(path)?; + let value = serde_json::from_str(&text)?; + Ok(value) +} + +/// Extract the identity snapshot (`{oauthAccount, userID}`) from a loaded +/// config value. Missing keys are captured as JSON `null` so the shape is +/// stable. +#[must_use] +pub fn extract_identity(config: &Value) -> Value { + json!({ + "oauthAccount": config.get("oauthAccount").cloned().unwrap_or(Value::Null), + "userID": config.get("userID").cloned().unwrap_or(Value::Null), + }) +} + +/// Splice a saved identity snapshot back into `config`, replacing only the +/// identity keys and leaving every other key untouched. A key absent from +/// `identity` leaves the corresponding config key unchanged; a non-object +/// config is left as-is. +pub fn splice_identity(config: &mut Value, identity: &Value) { + let Some(obj) = config.as_object_mut() else { + return; + }; + for key in IDENTITY_KEYS { + if let Some(value) = identity.get(key) { + obj.insert(key.to_string(), value.clone()); + } + } +} + +/// Read the account identity (accountUuid, organizationUuid, emailAddress, +/// organizationName) out of a loaded config value. +#[must_use] +pub fn account_of(config: &Value) -> Account { + match config.get("oauthAccount") { + Some(value) => serde_json::from_value(value.clone()).unwrap_or_default(), + None => Account::default(), + } +} + +/// The `.ccswitch.bak` backup path for a config file. +#[must_use] +fn backup_path(config_path: &Path) -> PathBuf { + let mut name = config_path.as_os_str().to_owned(); + name.push(".ccswitch.bak"); + PathBuf::from(name) +} + +/// The `.ccswitch.tmp` scratch path used for atomic writes. +#[must_use] +fn temp_path(config_path: &Path) -> PathBuf { + let mut name = config_path.as_os_str().to_owned(); + name.push(".ccswitch.tmp"); + PathBuf::from(name) +} + +/// Patch the identity in the config file at `config_path` with `identity`, +/// preserving all other keys. +/// +/// The existing file is backed up to `.ccswitch.bak` first, and the new +/// contents are written atomically via a sibling temp file that is renamed +/// into place. +/// +/// # Errors +/// +/// Returns an error if the config cannot be read, backed up, or written. +pub fn patch(config_path: &Path, identity: &Value) -> Result<()> { + let mut config = load(config_path)?; + fs::copy(config_path, backup_path(config_path))?; + splice_identity(&mut config, identity); + let text = serde_json::to_string_pretty(&config)?; + let tmp = temp_path(config_path); + fs::write(&tmp, text.as_bytes())?; + set_permissions_600(&tmp)?; + fs::rename(&tmp, config_path)?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn temp_dir() -> PathBuf { + use std::sync::atomic::{AtomicU64, Ordering}; + static COUNTER: AtomicU64 = AtomicU64::new(0); + let base = std::env::temp_dir().join(format!( + "ccswitch-config-{}-{}", + std::process::id(), + COUNTER.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&base).unwrap(); + base + } + + fn sample_config() -> Value { + json!({ + "numStartups": 7, + "userID": "user-old", + "oauthAccount": { + "accountUuid": "acct-old", + "organizationUuid": "org-old", + "emailAddress": "old@example.com", + "organizationName": "Old Org" + }, + "projects": { "/tmp/foo": { "allowedTools": [] } } + }) + } + + #[test] + fn load_reads_json() { + let dir = temp_dir(); + let path = dir.join(".claude.json"); + fs::write(&path, sample_config().to_string()).unwrap(); + let loaded = load(&path).unwrap(); + assert_eq!(loaded["numStartups"], json!(7)); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn load_missing_file_errors() { + let dir = temp_dir(); + let path = dir.join(".claude.json"); + assert!(load(&path).is_err()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn load_invalid_json_errors() { + let dir = temp_dir(); + let path = dir.join(".claude.json"); + fs::write(&path, "{not json").unwrap(); + assert!(load(&path).is_err()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn extract_identity_pulls_both_keys() { + let identity = extract_identity(&sample_config()); + assert_eq!(identity["userID"], json!("user-old")); + assert_eq!( + identity["oauthAccount"]["emailAddress"], + json!("old@example.com") + ); + } + + #[test] + fn extract_identity_defaults_missing_keys_to_null() { + let identity = extract_identity(&json!({ "numStartups": 1 })); + assert_eq!(identity["oauthAccount"], Value::Null); + assert_eq!(identity["userID"], Value::Null); + } + + #[test] + fn splice_replaces_identity_and_preserves_others() { + let mut config = sample_config(); + let identity = json!({ + "userID": "user-new", + "oauthAccount": { + "accountUuid": "acct-new", + "organizationUuid": "org-new", + "emailAddress": "new@example.com", + "organizationName": "New Org" + } + }); + splice_identity(&mut config, &identity); + assert_eq!(config["userID"], json!("user-new")); + assert_eq!(config["oauthAccount"]["accountUuid"], json!("acct-new")); + // Unrelated keys survive untouched. + assert_eq!(config["numStartups"], json!(7)); + assert_eq!(config["projects"]["/tmp/foo"]["allowedTools"], json!([])); + } + + #[test] + fn splice_leaves_config_key_when_identity_key_absent() { + let mut config = sample_config(); + let identity = json!({ "userID": "user-new" }); + splice_identity(&mut config, &identity); + assert_eq!(config["userID"], json!("user-new")); + // oauthAccount was not in identity, so it is left as it was. + assert_eq!(config["oauthAccount"]["accountUuid"], json!("acct-old")); + } + + #[test] + fn splice_ignores_non_object_config() { + let mut config = Value::Null; + splice_identity(&mut config, &json!({ "userID": "x" })); + assert_eq!(config, Value::Null); + } + + #[test] + fn account_of_reads_all_four_fields() { + let account = account_of(&sample_config()); + assert_eq!(account.account_uuid, "acct-old"); + assert_eq!(account.org_uuid, "org-old"); + assert_eq!(account.email, "old@example.com"); + assert_eq!(account.org, "Old Org"); + assert_eq!(account.key(), "acct-old|org-old"); + } + + #[test] + fn account_of_missing_oauth_is_default() { + let account = account_of(&json!({ "numStartups": 1 })); + assert_eq!(account, Account::default()); + } + + #[test] + fn account_of_malformed_oauth_is_default() { + let account = account_of(&json!({ "oauthAccount": "not-an-object" })); + assert_eq!(account, Account::default()); + } + + #[test] + fn patch_round_trips_identity_and_backs_up() { + let dir = temp_dir(); + let path = dir.join(".claude.json"); + fs::write(&path, sample_config().to_string()).unwrap(); + + let identity = extract_identity(&json!({ + "userID": "user-new", + "oauthAccount": { + "accountUuid": "acct-new", + "organizationUuid": "org-new", + "emailAddress": "new@example.com", + "organizationName": "New Org" + } + })); + patch(&path, &identity).unwrap(); + + let patched = load(&path).unwrap(); + assert_eq!(patched["userID"], json!("user-new")); + assert_eq!( + patched["oauthAccount"]["emailAddress"], + json!("new@example.com") + ); + // Unrelated keys preserved through the atomic rewrite. + assert_eq!(patched["numStartups"], json!(7)); + + // A backup of the pre-patch file exists and holds the old identity. + let backup = load(&backup_path(&path)).unwrap(); + assert_eq!(backup["userID"], json!("user-old")); + + // The temp scratch file was renamed away, not left behind. + assert!(!temp_path(&path).exists()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn patch_missing_file_errors_before_backup() { + let dir = temp_dir(); + let path = dir.join(".claude.json"); + assert!(patch(&path, &json!({ "userID": "x" })).is_err()); + assert!(!backup_path(&path).exists()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[cfg(unix)] + #[test] + fn patch_sets_owner_only_permissions() { + use std::os::unix::fs::PermissionsExt; + let dir = temp_dir(); + let path = dir.join(".claude.json"); + fs::write(&path, sample_config().to_string()).unwrap(); + patch(&path, &extract_identity(&sample_config())).unwrap(); + let mode = fs::metadata(&path).unwrap().permissions().mode(); + assert_eq!(mode & 0o777, 0o600); + fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/src/creds.rs b/src/creds.rs new file mode 100644 index 0000000..f701918 --- /dev/null +++ b/src/creds.rs @@ -0,0 +1,266 @@ +//! Credential port: reading and writing the Claude Code OAuth credential +//! blob from the platform store. +//! +//! The [`CredentialStore`] trait and all decision logic (path selection, +//! empty handling) live here, together with the file-based implementation +//! used on Linux and Windows. The real macOS Keychain adapter, which shells +//! out to the `security` binary, lives in [`crate::creds_shim`] and is +//! excluded from coverage. + +use crate::error::Result; +use std::fs; +use std::io::ErrorKind; +use std::path::{Path, PathBuf}; + +/// Abstraction over the platform credential store holding the Claude Code +/// OAuth credential blob. +pub trait CredentialStore { + /// Return the stored credential blob, or `None` when no credential is + /// present (missing or empty). + /// + /// # Errors + /// + /// Returns an error if the store cannot be read. + fn read(&self) -> Result>; + + /// Write `blob` into the store under account attribute `acct`. + /// + /// The `acct` attribute is only meaningful for the macOS Keychain; the + /// file store ignores it. + /// + /// # Errors + /// + /// Returns an error if the store cannot be written. + fn write(&self, blob: &str, acct: &str) -> Result<()>; + + /// Return the account attribute the credential is stored under, or + /// `None` when the store does not track one (the file store). + /// + /// # Errors + /// + /// Returns an error if the store cannot be queried. + fn account_attr(&self) -> Result>; +} + +/// File-based credential store: keeps the blob in +/// `/.credentials.json`. +/// +/// This is the fallback used on every platform other than macOS. It is pure +/// filesystem I/O under a configurable directory, so it is unit-testable +/// against a temporary directory without a shim. +#[derive(Debug, Clone)] +pub struct FileStore { + dir: PathBuf, +} + +impl FileStore { + /// Create a store rooted at `config_dir`. + pub fn new(config_dir: impl Into) -> Self { + Self { + dir: config_dir.into(), + } + } + + /// The path of the credential file this store reads and writes. + #[must_use] + pub fn path(&self) -> PathBuf { + self.dir.join(".credentials.json") + } +} + +impl CredentialStore for FileStore { + fn read(&self) -> Result> { + match fs::read_to_string(self.path()) { + Ok(blob) if blob.trim().is_empty() => Ok(None), + Ok(blob) => Ok(Some(blob)), + Err(err) if err.kind() == ErrorKind::NotFound => Ok(None), + Err(err) => Err(err.into()), + } + } + + fn write(&self, blob: &str, _acct: &str) -> Result<()> { + fs::create_dir_all(&self.dir)?; + let path = self.path(); + fs::write(&path, blob)?; + set_permissions_600(&path)?; + Ok(()) + } + + fn account_attr(&self) -> Result> { + Ok(None) + } +} + +/// Tighten a file's permissions to owner read/write only. +#[cfg(unix)] +pub(crate) fn set_permissions_600(path: &Path) -> Result<()> { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(path, fs::Permissions::from_mode(0o600))?; + Ok(()) +} + +/// No-op on platforms without Unix permission bits. +#[cfg(not(unix))] +pub(crate) fn set_permissions_600(_path: &Path) -> Result<()> { + Ok(()) +} + +/// Tighten a directory's permissions to owner access only. +#[cfg(unix)] +pub(crate) fn set_permissions_700(path: &Path) -> Result<()> { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(path, fs::Permissions::from_mode(0o700))?; + Ok(()) +} + +/// No-op on platforms without Unix permission bits. +#[cfg(not(unix))] +pub(crate) fn set_permissions_700(_path: &Path) -> Result<()> { + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn temp_dir() -> PathBuf { + use std::sync::atomic::{AtomicU64, Ordering}; + static COUNTER: AtomicU64 = AtomicU64::new(0); + let base = std::env::temp_dir().join(format!( + "ccswitch-creds-{}-{}", + std::process::id(), + COUNTER.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&base).unwrap(); + base + } + + #[test] + fn path_is_credentials_json_under_dir() { + let store = FileStore::new("/some/config/dir"); + assert_eq!( + store.path(), + PathBuf::from("/some/config/dir/.credentials.json") + ); + } + + #[test] + fn read_missing_file_is_none() { + let dir = temp_dir(); + let store = FileStore::new(&dir); + assert_eq!(store.read().unwrap(), None); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn read_empty_file_is_none() { + let dir = temp_dir(); + let store = FileStore::new(&dir); + fs::write(store.path(), " \n").unwrap(); + assert_eq!(store.read().unwrap(), None); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn write_then_read_round_trips() { + let dir = temp_dir(); + let store = FileStore::new(&dir); + store.write("{\"token\":\"abc\"}", "ignored").unwrap(); + assert_eq!( + store.read().unwrap().as_deref(), + Some("{\"token\":\"abc\"}") + ); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn write_creates_missing_parent_directory() { + let dir = temp_dir(); + let nested = dir.join("deep/nested/config"); + let store = FileStore::new(&nested); + store.write("blob", "").unwrap(); + assert!(nested.join(".credentials.json").exists()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[cfg(unix)] + #[test] + fn write_sets_owner_only_permissions() { + use std::os::unix::fs::PermissionsExt; + let dir = temp_dir(); + let store = FileStore::new(&dir); + store.write("blob", "").unwrap(); + let mode = fs::metadata(store.path()).unwrap().permissions().mode(); + assert_eq!(mode & 0o777, 0o600); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn read_propagates_unexpected_error() { + let dir = temp_dir(); + let store = FileStore::new(&dir); + // Make the credential path a directory so reading it as a string + // fails with an error other than "not found". + fs::create_dir_all(store.path()).unwrap(); + assert!(store.read().is_err()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn write_fails_when_dir_uncreatable() { + // A directory nested under a regular file cannot be created. + let dir = temp_dir(); + let blocker = dir.join("blocker"); + fs::write(&blocker, "x").unwrap(); + let store = FileStore::new(blocker.join("sub")); + assert!(store.write("blob", "").is_err()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn write_fails_when_target_is_directory() { + let dir = temp_dir(); + let store = FileStore::new(&dir); + // The credential path is a directory, so writing the blob fails. + fs::create_dir_all(store.path()).unwrap(); + assert!(store.write("blob", "").is_err()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[cfg(unix)] + #[test] + fn set_permissions_error_on_missing_path() { + let dir = temp_dir(); + let missing = dir.join("nope"); + assert!(set_permissions_600(&missing).is_err()); + assert!(set_permissions_700(&missing).is_err()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn account_attr_is_none_for_file_store() { + let store = FileStore::new("/anywhere"); + assert_eq!(store.account_attr().unwrap(), None); + } + + #[cfg(unix)] + #[test] + fn set_permissions_700_tightens_directory() { + use std::os::unix::fs::PermissionsExt; + let dir = temp_dir(); + let nested = dir.join("locked"); + fs::create_dir_all(&nested).unwrap(); + set_permissions_700(&nested).unwrap(); + let mode = fs::metadata(&nested).unwrap().permissions().mode(); + assert_eq!(mode & 0o777, 0o700); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn store_is_debuggable_and_cloneable() { + let store = FileStore::new("/x"); + let cloned = store.clone(); + assert_eq!(store.path(), cloned.path()); + assert!(format!("{store:?}").contains("FileStore")); + } +} diff --git a/src/creds_shim.rs b/src/creds_shim.rs new file mode 100644 index 0000000..f499e22 --- /dev/null +++ b/src/creds_shim.rs @@ -0,0 +1,104 @@ +//! Real credential-store adapter (macOS `security` binary). +//! +//! Side-effecting implementation of the [`crate::creds`] port. This is the +//! only place in the crate that runs the `security` binary, and it is +//! excluded from coverage. It contains no decision logic: platform selection +//! is a single `cfg` switch and each method is a thin wrapper over one +//! `security` invocation. + +use crate::creds::CredentialStore; +#[cfg(not(target_os = "macos"))] +use crate::creds::FileStore; +#[cfg(target_os = "macos")] +use crate::error::Error; +use crate::error::Result; +use std::path::PathBuf; + +/// Service name under which Claude Code stores its OAuth credential. +#[cfg(target_os = "macos")] +const SERVICE: &str = "Claude Code-credentials"; + +/// Select the credential store for the current platform: the macOS Keychain +/// when available, otherwise the file-based fallback rooted at `config_dir`. +#[must_use] +pub fn platform_store(config_dir: PathBuf) -> Box { + #[cfg(target_os = "macos")] + { + let _ = config_dir; + Box::new(KeychainStore) + } + #[cfg(not(target_os = "macos"))] + { + Box::new(FileStore::new(config_dir)) + } +} + +/// macOS Keychain credential store backed by the `security` binary. +#[cfg(target_os = "macos")] +pub struct KeychainStore; + +#[cfg(target_os = "macos")] +impl CredentialStore for KeychainStore { + fn read(&self) -> Result> { + use std::process::Command; + let output = Command::new("security") + .args(["find-generic-password", "-s", SERVICE, "-w"]) + .output()?; + if !output.status.success() { + return Ok(None); + } + let blob = String::from_utf8_lossy(&output.stdout) + .trim_end_matches('\n') + .to_string(); + if blob.is_empty() { + Ok(None) + } else { + Ok(Some(blob)) + } + } + + fn write(&self, blob: &str, acct: &str) -> Result<()> { + use std::process::Command; + let acct = if acct.is_empty() { + std::env::var("USER").unwrap_or_default() + } else { + acct.to_string() + }; + let _ = Command::new("security") + .args(["delete-generic-password", "-s", SERVICE]) + .output(); + let status = Command::new("security") + .args([ + "add-generic-password", + "-U", + "-a", + &acct, + "-s", + SERVICE, + "-w", + blob, + ]) + .status()?; + if status.success() { + Ok(()) + } else { + Err(Error::Invalid("failed to write credential".to_string())) + } + } + + fn account_attr(&self) -> Result> { + use std::process::Command; + let output = Command::new("security") + .args(["find-generic-password", "-s", SERVICE, "-g"]) + .output()?; + let text = String::from_utf8_lossy(&output.stderr); + for line in text.lines() { + if let Some(rest) = line.trim().strip_prefix("\"acct\"=\"") { + if let Some(acct) = rest.strip_suffix('"') { + return Ok(Some(acct.to_string())); + } + } + } + Ok(None) + } +} diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..99b8f1e --- /dev/null +++ b/src/error.rs @@ -0,0 +1,67 @@ +//! Error types shared across the crate. + +use thiserror::Error; + +/// Errors produced by `ccswitch` operations. +#[derive(Debug, Error)] +pub enum Error { + /// A profile name was not found in the store. + #[error("profile '{0}' not found")] + ProfileNotFound(String), + + /// A profile name collides with a reserved subcommand word. + #[error("'{0}' is a reserved word, pick another profile name")] + ReservedName(String), + + /// A required input was missing or empty. + #[error("{0}")] + Invalid(String), + + /// A wrapped I/O error. + #[error(transparent)] + Io(#[from] std::io::Error), + + /// A wrapped JSON (de)serialization error. + #[error(transparent)] + Json(#[from] serde_json::Error), +} + +/// Convenience result alias used throughout the crate. +pub type Result = std::result::Result; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn displays_domain_variants() { + assert_eq!( + Error::ProfileNotFound("dev".to_string()).to_string(), + "profile 'dev' not found" + ); + assert_eq!( + Error::ReservedName("list".to_string()).to_string(), + "'list' is a reserved word, pick another profile name" + ); + assert_eq!( + Error::Invalid("bad input".to_string()).to_string(), + "bad input" + ); + } + + #[test] + fn wraps_io_errors() { + let io = std::io::Error::new(std::io::ErrorKind::NotFound, "missing"); + let err: Error = io.into(); + assert!(format!("{err:?}").starts_with("Io")); + assert!(err.to_string().contains("missing")); + } + + #[test] + fn wraps_json_errors() { + let json_err = serde_json::from_str::("not json").unwrap_err(); + let err: Error = json_err.into(); + assert!(format!("{err:?}").starts_with("Json")); + assert!(!err.to_string().is_empty()); + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..c7fb783 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,20 @@ +//! `ccswitch` — switch between multiple Claude Code accounts. +//! +//! This crate is organized with a ports-and-adapters layout: every real +//! operating-system or network side effect lives behind a trait whose +//! concrete implementation is in a `*_shim.rs` file (excluded from coverage), +//! while all decision logic lives in the plain modules and is unit-tested +//! with fakes. + +pub mod cli; +pub mod cli_shim; +pub mod config; +pub mod creds; +pub mod creds_shim; +pub mod error; +pub mod model; +pub mod store; +pub mod switch; + +pub use error::{Error, Result}; +pub use model::{Account, Profile}; diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..05ecd22 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,5 @@ +//! Thin binary entry point that delegates to the CLI adapter. + +fn main() -> anyhow::Result<()> { + ccswitch::cli_shim::run() +} diff --git a/src/model.rs b/src/model.rs new file mode 100644 index 0000000..90dfb1e --- /dev/null +++ b/src/model.rs @@ -0,0 +1,134 @@ +//! Core data types describing Claude Code accounts and saved profiles. + +use serde::{Deserialize, Serialize}; + +/// Identity of a single Claude Code account within an organization. +/// +/// A login can span multiple organizations, so an account is uniquely +/// identified by the pair (`account_uuid`, `org_uuid`). +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Account { + /// Stable per-user account identifier (`oauthAccount.accountUuid`). + #[serde(rename = "accountUuid", default)] + pub account_uuid: String, + + /// Organization identifier (`oauthAccount.organizationUuid`). + #[serde(rename = "organizationUuid", default)] + pub org_uuid: String, + + /// Account email address (`oauthAccount.emailAddress`). + #[serde(rename = "emailAddress", default)] + pub email: String, + + /// Human-readable organization name (`oauthAccount.organizationName`). + #[serde(rename = "organizationName", default)] + pub org: String, +} + +impl Account { + /// The identity key used to compare two accounts for equality when + /// deciding whether a profile is the currently active one. + #[must_use] + pub fn key(&self) -> String { + format!("{}|{}", self.account_uuid, self.org_uuid) + } +} + +/// Metadata persisted alongside a saved profile's credentials. +/// +/// Mirrors the `account.json` file written for each profile: the account +/// identity, the Claude Code `userID`, and the keychain account attribute +/// used to restore the credential on macOS. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Profile { + /// The account identity for this profile. + #[serde(rename = "oauthAccount")] + pub account: Account, + + /// Claude Code's opaque user identifier. + #[serde(rename = "userID", default, skip_serializing_if = "Option::is_none")] + pub user_id: Option, + + /// The macOS keychain account attribute the credential was stored under. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub keychain_account: Option, +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sample_account() -> Account { + Account { + account_uuid: "acct-123".to_string(), + org_uuid: "org-456".to_string(), + email: "person@example.com".to_string(), + org: "Example Org".to_string(), + } + } + + #[test] + fn account_key_joins_identity() { + assert_eq!(sample_account().key(), "acct-123|org-456"); + } + + #[test] + fn account_round_trips_via_claude_field_names() { + let json = r#"{ + "accountUuid": "acct-123", + "organizationUuid": "org-456", + "emailAddress": "person@example.com", + "organizationName": "Example Org" + }"#; + let parsed: Account = serde_json::from_str(json).unwrap(); + assert_eq!(parsed, sample_account()); + + let reserialized = serde_json::to_string(&parsed).unwrap(); + let reparsed: Account = serde_json::from_str(&reserialized).unwrap(); + assert_eq!(reparsed, parsed); + } + + #[test] + fn account_defaults_missing_fields() { + let parsed: Account = serde_json::from_str("{}").unwrap(); + assert_eq!(parsed.key(), "|"); + assert!(parsed.email.is_empty()); + assert!(parsed.org.is_empty()); + } + + #[test] + fn account_is_debuggable_and_cloneable() { + let account = sample_account(); + let cloned = account.clone(); + assert_eq!(account, cloned); + assert!(format!("{account:?}").contains("acct-123")); + } + + #[test] + fn profile_round_trips() { + let profile = Profile { + account: sample_account(), + user_id: Some("user-789".to_string()), + keychain_account: Some("login".to_string()), + }; + let json = serde_json::to_string(&profile).unwrap(); + let parsed: Profile = serde_json::from_str(&json).unwrap(); + assert_eq!(parsed, profile); + assert!(format!("{profile:?}").contains("user-789")); + } + + #[test] + fn profile_omits_absent_optionals() { + let profile = Profile { + account: sample_account(), + user_id: None, + keychain_account: None, + }; + let json = serde_json::to_string(&profile).unwrap(); + assert!(!json.contains("userID")); + assert!(!json.contains("keychain_account")); + + let parsed: Profile = serde_json::from_str(&json).unwrap(); + assert_eq!(parsed, profile); + } +} diff --git a/src/store.rs b/src/store.rs new file mode 100644 index 0000000..d9da9fa --- /dev/null +++ b/src/store.rs @@ -0,0 +1,715 @@ +//! The on-disk profile store: enumerating, saving, and removing profiles +//! under the accounts directory (`$CCSWITCH_HOME`, default +//! `~/.claude/accounts`). +//! +//! Each profile is a directory holding two files: +//! +//! * `credentials.json` — the raw Claude Code OAuth credential blob, exactly +//! as read from the platform credential store. +//! * `account.json` — the identity snapshot `{oauthAccount, userID, +//! keychain_account}` spliced out of `~/.claude.json`. The full +//! `oauthAccount` object is preserved verbatim as JSON so that restoring a +//! profile carries back every field (organizationUuid, tiers, onboarding +//! flags, …), not just the handful this crate keys on. +//! +//! This is plain-file I/O under a configurable root, so it is unit-tested +//! against a temporary directory with no shim. + +use crate::config; +use crate::creds::{set_permissions_600, set_permissions_700}; +use crate::error::{Error, Result}; +use crate::model::Account; +use serde_json::Value; +use std::fs; +use std::io::ErrorKind; +use std::path::{Path, PathBuf}; + +/// File name of the credential blob within a profile directory. +pub const CREDENTIALS_FILE: &str = "credentials.json"; + +/// File name of the identity snapshot within a profile directory. +pub const ACCOUNT_FILE: &str = "account.json"; + +/// How broadly a single, rotating OAuth credential is shared. +/// +/// This is the knob that fixes the auth-loss bug: the Claude Code refresh +/// token rotates per *account*, shared across every organization a login can +/// see. Keying a stored credential by the full `(account, org)` pair — as the +/// original tool did — means two profiles for the same login but different +/// orgs each believe they own a separate token, when in truth there is one. +/// The first refresh under either org rotates the shared token and strands the +/// sibling with a dead one. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TokenScope { + /// One rotating credential per login, shared across all of its orgs. + /// Profiles are grouped by `accountUuid` alone. + PerAccount, + /// One credential per `(accountUuid, organizationUuid)` pair. + PerAccountOrg, +} + +impl TokenScope { + /// The key grouping profiles that share one credential under this scope. + #[must_use] + pub fn token_key(self, account: &Account) -> String { + match self { + TokenScope::PerAccount => account.account_uuid.clone(), + TokenScope::PerAccountOrg => account.key(), + } + } + + /// Whether `account` carries enough identity to select a token group. + /// + /// An all-empty identity (no `accountUuid`, no `organizationUuid`) matches + /// nothing, so credential propagation is skipped rather than blindly + /// overwriting every profile. + #[must_use] + pub fn identifies(self, account: &Account) -> bool { + match self { + TokenScope::PerAccount => !account.account_uuid.is_empty(), + TokenScope::PerAccountOrg => { + !account.account_uuid.is_empty() || !account.org_uuid.is_empty() + } + } + } +} + +/// A profile loaded from disk: its credential blob and identity snapshot. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StoredProfile { + /// The raw OAuth credential blob (`credentials.json`). + pub credentials: String, + /// The identity snapshot object (`account.json`). + pub account: Value, +} + +impl StoredProfile { + /// The account identity keyed on, parsed out of the snapshot. + #[must_use] + pub fn account(&self) -> Account { + config::account_of(&self.account) + } + + /// The `{oauthAccount, userID}` slice to splice back into `~/.claude.json`. + #[must_use] + pub fn identity(&self) -> Value { + config::extract_identity(&self.account) + } + + /// The keychain account attribute the credential should be restored under. + #[must_use] + pub fn keychain_account(&self) -> String { + self.account + .get("keychain_account") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string() + } +} + +/// A profile listed by name alongside its parsed identity. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ProfileSummary { + /// The profile's directory name. + pub name: String, + /// The account identity read from its `account.json`. + pub account: Account, +} + +/// The profile store rooted at a single directory. +#[derive(Debug, Clone)] +pub struct Store { + root: PathBuf, +} + +impl Store { + /// Create a store rooted at `root` (the `$CCSWITCH_HOME` directory). + pub fn new(root: impl Into) -> Self { + Self { root: root.into() } + } + + /// The store's root directory. + #[must_use] + pub fn root(&self) -> &Path { + &self.root + } + + /// The directory holding profile `name`. + #[must_use] + pub fn profile_dir(&self, name: &str) -> PathBuf { + self.root.join(name) + } + + fn credentials_path(&self, name: &str) -> PathBuf { + self.profile_dir(name).join(CREDENTIALS_FILE) + } + + fn account_path(&self, name: &str) -> PathBuf { + self.profile_dir(name).join(ACCOUNT_FILE) + } + + /// Whether a profile directory named `name` already exists. + #[must_use] + pub fn contains(&self, name: &str) -> bool { + self.profile_dir(name).exists() + } + + /// Create the profile directory (and the root) with owner-only perms. + fn ensure_dir(&self, name: &str) -> Result { + let dir = self.profile_dir(name); + fs::create_dir_all(&dir)?; + set_permissions_700(&self.root)?; + set_permissions_700(&dir)?; + Ok(dir) + } + + /// Write only the credential blob of profile `name`. + /// + /// # Errors + /// + /// Returns an error if the directory or file cannot be created/written. + pub fn write_credentials(&self, name: &str, blob: &str) -> Result<()> { + self.ensure_dir(name)?; + let path = self.credentials_path(name); + fs::write(&path, blob)?; + set_permissions_600(&path)?; + Ok(()) + } + + /// Write only the identity snapshot of profile `name`. + /// + /// # Errors + /// + /// Returns an error if the directory or file cannot be created/written. + pub fn write_account(&self, name: &str, account: &Value) -> Result<()> { + self.ensure_dir(name)?; + let path = self.account_path(name); + let text = serde_json::to_string_pretty(account)?; + fs::write(&path, text)?; + set_permissions_600(&path)?; + Ok(()) + } + + /// Save both files of a profile in one step. + /// + /// # Errors + /// + /// Returns an error if either file cannot be written. + pub fn save_profile(&self, name: &str, blob: &str, account: &Value) -> Result<()> { + self.write_credentials(name, blob)?; + self.write_account(name, account)?; + Ok(()) + } + + /// Load profile `name`, both files. + /// + /// # Errors + /// + /// Returns [`Error::ProfileNotFound`] when no such directory exists, or + /// [`Error::Invalid`] when the directory is missing one of its two files. + pub fn load(&self, name: &str) -> Result { + if !self.contains(name) { + return Err(Error::ProfileNotFound(name.to_string())); + } + let credentials = self.load_credentials(name)?; + let account_text = read_required(&self.account_path(name), name)?; + let account = serde_json::from_str(&account_text)?; + Ok(StoredProfile { + credentials, + account, + }) + } + + /// Load just the credential blob of profile `name`. + /// + /// # Errors + /// + /// Returns [`Error::ProfileNotFound`] when the directory is absent, or + /// [`Error::Invalid`] when the directory exists without a credential file. + pub fn load_credentials(&self, name: &str) -> Result { + if !self.contains(name) { + return Err(Error::ProfileNotFound(name.to_string())); + } + read_required(&self.credentials_path(name), name) + } + + /// List every saved profile (directories with an `account.json`), sorted + /// by name. + /// + /// # Errors + /// + /// Returns an error if the root cannot be read (other than being absent, + /// which yields an empty list) or a snapshot is not valid JSON. + pub fn list(&self) -> Result> { + let entries = match fs::read_dir(&self.root) { + Ok(entries) => entries, + Err(err) if err.kind() == ErrorKind::NotFound => return Ok(Vec::new()), + Err(err) => return Err(err.into()), + }; + let mut out = Vec::new(); + for entry in entries { + let entry = entry?; + if !entry.file_type()?.is_dir() { + continue; + } + let name = entry.file_name().to_string_lossy().into_owned(); + let account_text = match fs::read_to_string(self.account_path(&name)) { + Ok(text) => text, + Err(err) if err.kind() == ErrorKind::NotFound => continue, + Err(err) => return Err(err.into()), + }; + let snapshot: Value = serde_json::from_str(&account_text)?; + out.push(ProfileSummary { + name, + account: config::account_of(&snapshot), + }); + } + out.sort_by(|a, b| a.name.cmp(&b.name)); + Ok(out) + } + + /// Every profile that shares a rotating credential with `active` under + /// `scope`. + /// + /// With [`TokenScope::PerAccount`] this returns *all* profiles of the same + /// login regardless of org — the set that must be kept in lockstep so a + /// rotation under one org does not strand the others. An identity that + /// does not [`TokenScope::identifies`] anything yields an empty list. + /// + /// # Errors + /// + /// Returns an error if the store cannot be listed. + pub fn profiles_sharing_token( + &self, + active: &Account, + scope: TokenScope, + ) -> Result> { + if !scope.identifies(active) { + return Ok(Vec::new()); + } + let key = scope.token_key(active); + Ok(self + .list()? + .into_iter() + .filter(|summary| { + scope.identifies(&summary.account) && scope.token_key(&summary.account) == key + }) + .collect()) + } + + /// Remove profile `name` and all of its files. + /// + /// # Errors + /// + /// Returns [`Error::ProfileNotFound`] when no such directory exists. + pub fn remove(&self, name: &str) -> Result<()> { + if !self.contains(name) { + return Err(Error::ProfileNotFound(name.to_string())); + } + fs::remove_dir_all(self.profile_dir(name))?; + Ok(()) + } +} + +/// Read a file that a profile is required to have, mapping a missing file to +/// an "incomplete profile" error rather than a bare I/O error. +fn read_required(path: &Path, name: &str) -> Result { + match fs::read_to_string(path) { + Ok(text) => Ok(text), + Err(err) if err.kind() == ErrorKind::NotFound => { + Err(Error::Invalid(format!("profile '{name}' is incomplete"))) + } + Err(err) => Err(err.into()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn temp_dir() -> PathBuf { + use std::sync::atomic::{AtomicU64, Ordering}; + static COUNTER: AtomicU64 = AtomicU64::new(0); + let base = std::env::temp_dir().join(format!( + "ccswitch-store-{}-{}", + std::process::id(), + COUNTER.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&base).unwrap(); + base + } + + fn account_snapshot(acct: &str, org: &str, email: &str) -> Value { + json!({ + "oauthAccount": { + "accountUuid": acct, + "organizationUuid": org, + "emailAddress": email, + "organizationName": "Org", + "organizationRole": "admin" + }, + "userID": "user-hash", + "keychain_account": "login-attr" + }) + } + + #[test] + fn token_scope_keys_group_by_scope() { + let account = Account { + account_uuid: "A".to_string(), + org_uuid: "O".to_string(), + ..Account::default() + }; + assert_eq!(TokenScope::PerAccount.token_key(&account), "A"); + assert_eq!(TokenScope::PerAccountOrg.token_key(&account), "A|O"); + } + + #[test] + fn token_scope_identifies_requires_identity() { + let empty = Account::default(); + assert!(!TokenScope::PerAccount.identifies(&empty)); + assert!(!TokenScope::PerAccountOrg.identifies(&empty)); + + let only_org = Account { + org_uuid: "O".to_string(), + ..Account::default() + }; + assert!(!TokenScope::PerAccount.identifies(&only_org)); + assert!(TokenScope::PerAccountOrg.identifies(&only_org)); + + let with_acct = Account { + account_uuid: "A".to_string(), + ..Account::default() + }; + assert!(TokenScope::PerAccount.identifies(&with_acct)); + assert!(TokenScope::PerAccountOrg.identifies(&with_acct)); + } + + #[test] + fn token_scope_is_copy_and_debuggable() { + let scope = TokenScope::PerAccount; + let copied = scope; + assert_eq!(scope, copied); + assert!(format!("{scope:?}").contains("PerAccount")); + } + + #[test] + fn paths_are_under_root() { + let store = Store::new("/root"); + assert_eq!(store.root(), Path::new("/root")); + assert_eq!(store.profile_dir("dev"), PathBuf::from("/root/dev")); + assert_eq!( + store.credentials_path("dev"), + PathBuf::from("/root/dev/credentials.json") + ); + assert_eq!( + store.account_path("dev"), + PathBuf::from("/root/dev/account.json") + ); + } + + #[test] + fn store_is_cloneable_and_debuggable() { + let store = Store::new("/root"); + let cloned = store.clone(); + assert_eq!(store.root(), cloned.root()); + assert!(format!("{store:?}").contains("Store")); + } + + #[test] + fn save_then_load_round_trips_both_files() { + let dir = temp_dir(); + let store = Store::new(&dir); + let snapshot = account_snapshot("A", "O", "a@example.com"); + store.save_profile("dev", "BLOB", &snapshot).unwrap(); + + assert!(store.contains("dev")); + let loaded = store.load("dev").unwrap(); + assert_eq!(loaded.credentials, "BLOB"); + assert_eq!(loaded.account, snapshot); + // The full oauthAccount object is preserved, not just keyed fields. + assert_eq!( + loaded.account["oauthAccount"]["organizationRole"], + json!("admin") + ); + assert_eq!(loaded.account().account_uuid, "A"); + assert_eq!(loaded.identity()["userID"], json!("user-hash")); + assert_eq!(loaded.keychain_account(), "login-attr"); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn stored_profile_keychain_account_defaults_empty() { + let profile = StoredProfile { + credentials: "x".to_string(), + account: json!({ "oauthAccount": {} }), + }; + assert_eq!(profile.keychain_account(), ""); + assert_eq!( + profile, + StoredProfile { + credentials: "x".to_string(), + account: json!({ "oauthAccount": {} }), + } + ); + } + + #[cfg(unix)] + #[test] + fn saved_files_and_dirs_have_tight_permissions() { + use std::os::unix::fs::PermissionsExt; + let dir = temp_dir(); + let store = Store::new(&dir); + store + .save_profile("dev", "BLOB", &account_snapshot("A", "O", "a@x")) + .unwrap(); + let mode = |p: PathBuf| fs::metadata(p).unwrap().permissions().mode() & 0o777; + assert_eq!(mode(store.profile_dir("dev")), 0o700); + assert_eq!(mode(store.credentials_path("dev")), 0o600); + assert_eq!(mode(store.account_path("dev")), 0o600); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn load_missing_profile_is_not_found() { + let dir = temp_dir(); + let store = Store::new(&dir); + assert!(matches!( + store.load("ghost"), + Err(Error::ProfileNotFound(name)) if name == "ghost" + )); + assert!(matches!( + store.load_credentials("ghost"), + Err(Error::ProfileNotFound(_)) + )); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn list_unreadable_root_errors() { + // A root that is a file (not a directory) surfaces a read_dir error + // other than "not found". + let dir = temp_dir(); + let file_root = dir.join("iam-a-file"); + fs::write(&file_root, "x").unwrap(); + let store = Store::new(&file_root); + assert!(store.list().is_err()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn list_unreadable_account_errors() { + // An account.json that is a directory fails to read as a string with + // an error other than "not found". + let dir = temp_dir(); + let store = Store::new(&dir); + fs::create_dir_all(store.account_path("dev")).unwrap(); + assert!(store.list().is_err()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn load_credentials_unreadable_file_errors() { + // A credentials.json that is a directory hits the non-NotFound arm of + // the required-file reader. + let dir = temp_dir(); + let store = Store::new(&dir); + fs::create_dir_all(store.credentials_path("dev")).unwrap(); + // Give it an account.json so the directory counts as a profile. + store + .write_account("dev", &account_snapshot("A", "O", "a@x")) + .unwrap(); + assert!(store.load_credentials("dev").is_err()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn load_incomplete_profile_errors() { + let dir = temp_dir(); + let store = Store::new(&dir); + // Directory exists with only the account file, no credentials. + store + .write_account("dev", &account_snapshot("A", "O", "a@x")) + .unwrap(); + assert!(matches!( + store.load_credentials("dev"), + Err(Error::Invalid(msg)) if msg.contains("incomplete") + )); + assert!(matches!(store.load("dev"), Err(Error::Invalid(_)))); + + // And with only credentials, no account file. + let store2 = Store::new(dir.join("other")); + store2.write_credentials("dev", "BLOB").unwrap(); + assert!(matches!(store2.load("dev"), Err(Error::Invalid(_)))); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn load_malformed_account_json_errors() { + let dir = temp_dir(); + let store = Store::new(&dir); + store.write_credentials("dev", "blob").unwrap(); + fs::write(store.account_path("dev"), "{not json").unwrap(); + assert!(store.load("dev").is_err()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn write_fails_when_directory_uncreatable() { + // Rooting the store under a regular file makes the profile directory + // impossible to create. + let dir = temp_dir(); + let blocker = dir.join("blocker"); + fs::write(&blocker, "x").unwrap(); + let store = Store::new(&blocker); + assert!(store.write_credentials("dev", "blob").is_err()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn write_credentials_fails_when_target_is_directory() { + let dir = temp_dir(); + let store = Store::new(&dir); + fs::create_dir_all(store.credentials_path("dev")).unwrap(); + assert!(store.write_credentials("dev", "blob").is_err()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn write_account_fails_when_target_is_directory() { + let dir = temp_dir(); + let store = Store::new(&dir); + fs::create_dir_all(store.account_path("dev")).unwrap(); + assert!(store.write_account("dev", &json!({})).is_err()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn list_empty_root_is_empty() { + let dir = temp_dir(); + let missing = dir.join("nope"); + let store = Store::new(&missing); + assert!(store.list().unwrap().is_empty()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn list_skips_non_dirs_and_dirs_without_account() { + let dir = temp_dir(); + let store = Store::new(&dir); + store + .save_profile("bravo", "b", &account_snapshot("B", "O", "b@x")) + .unwrap(); + store + .save_profile("alpha", "a", &account_snapshot("A", "O", "a@x")) + .unwrap(); + // A stray file at the root is not a profile. + fs::write(dir.join("loose.txt"), "junk").unwrap(); + // A directory without an account.json is not a profile. + fs::create_dir_all(dir.join("half")).unwrap(); + + let names: Vec = store.list().unwrap().into_iter().map(|s| s.name).collect(); + assert_eq!(names, vec!["alpha".to_string(), "bravo".to_string()]); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn list_malformed_account_json_errors() { + let dir = temp_dir(); + let store = Store::new(&dir); + fs::create_dir_all(store.profile_dir("dev")).unwrap(); + fs::write(store.account_path("dev"), "{not json").unwrap(); + assert!(store.list().is_err()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn profiles_sharing_token_groups_by_account_under_per_account() { + let dir = temp_dir(); + let store = Store::new(&dir); + // Two orgs of one login, plus an unrelated account. + store + .save_profile("orga", "t", &account_snapshot("A", "O1", "a@x")) + .unwrap(); + store + .save_profile("orgb", "t", &account_snapshot("A", "O2", "a@x")) + .unwrap(); + store + .save_profile("other", "t", &account_snapshot("Z", "O9", "z@x")) + .unwrap(); + + let active = Account { + account_uuid: "A".to_string(), + org_uuid: "O1".to_string(), + ..Account::default() + }; + + let per_account: Vec = store + .profiles_sharing_token(&active, TokenScope::PerAccount) + .unwrap() + .into_iter() + .map(|s| s.name) + .collect(); + assert_eq!(per_account, vec!["orga".to_string(), "orgb".to_string()]); + + let per_org: Vec = store + .profiles_sharing_token(&active, TokenScope::PerAccountOrg) + .unwrap() + .into_iter() + .map(|s| s.name) + .collect(); + assert_eq!(per_org, vec!["orga".to_string()]); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn profiles_sharing_token_empty_identity_matches_nothing() { + let dir = temp_dir(); + let store = Store::new(&dir); + store + .save_profile("orga", "t", &account_snapshot("A", "O1", "a@x")) + .unwrap(); + let empty = Account::default(); + assert!(store + .profiles_sharing_token(&empty, TokenScope::PerAccount) + .unwrap() + .is_empty()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn remove_deletes_profile() { + let dir = temp_dir(); + let store = Store::new(&dir); + store + .save_profile("dev", "t", &account_snapshot("A", "O", "a@x")) + .unwrap(); + assert!(store.contains("dev")); + store.remove("dev").unwrap(); + assert!(!store.contains("dev")); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn remove_missing_profile_is_not_found() { + let dir = temp_dir(); + let store = Store::new(&dir); + assert!(matches!( + store.remove("ghost"), + Err(Error::ProfileNotFound(_)) + )); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn profile_summary_is_debuggable_and_cloneable() { + let summary = ProfileSummary { + name: "dev".to_string(), + account: Account::default(), + }; + let cloned = summary.clone(); + assert_eq!(summary, cloned); + assert!(format!("{summary:?}").contains("dev")); + } +} diff --git a/src/switch.rs b/src/switch.rs new file mode 100644 index 0000000..5031d94 --- /dev/null +++ b/src/switch.rs @@ -0,0 +1,625 @@ +//! Account-switching orchestration: tying the credential store, the +//! `~/.claude.json` config, and the profile store together to save and +//! activate profiles. +//! +//! This is pure decision logic composed over the [`crate::creds`], +//! [`crate::config`], and [`crate::store`] ports, so it is unit-tested with a +//! fake credential store and temp directories — no real Keychain or process +//! spawning involved. +//! +//! ## The auth-loss fix +//! +//! The Claude Code OAuth refresh token rotates per **account**, shared across +//! every organization a single login can operate in (org selection is +//! client-side state in `~/.claude.json`, not part of the credential). The +//! original tool re-snapshotted the live credential into only the one profile +//! whose `(accountUuid, organizationUuid)` matched the live config. So two +//! profiles for the same login but different orgs each held their own copy of +//! the one shared token; the first refresh under either org rotated the shared +//! token and left the sibling profile holding a dead one — a delayed forced +//! re-login. +//! +//! [`Switcher`] closes that gap: before switching away it re-snapshots the +//! live credential into **every** profile that shares the outgoing account's +//! token, as selected by the configured [`TokenScope`]. Under +//! [`TokenScope::PerAccount`] that is all same-login profiles regardless of +//! org, so a rotation under any org keeps every sibling current. + +use crate::config; +use crate::creds::CredentialStore; +use crate::error::{Error, Result}; +use crate::model::Account; +use crate::store::{Store, TokenScope}; +use serde_json::{json, Value}; +use std::path::{Path, PathBuf}; + +/// Orchestrates saving and activating profiles over the three ports. +pub struct Switcher<'a> { + creds: &'a dyn CredentialStore, + store: &'a Store, + config_path: PathBuf, + scope: TokenScope, +} + +impl<'a> Switcher<'a> { + /// Build a switcher over a credential store, a profile store, the path to + /// `~/.claude.json`, and the token-sharing scope that drives the fix. + pub fn new( + creds: &'a dyn CredentialStore, + store: &'a Store, + config_path: impl Into, + scope: TokenScope, + ) -> Self { + Self { + creds, + store, + config_path: config_path.into(), + scope, + } + } + + /// The `~/.claude.json` path this switcher operates on. + #[must_use] + pub fn config_path(&self) -> &Path { + &self.config_path + } + + /// Snapshot the live account into profile `name`. + /// + /// Reads the active credential blob, the keychain account attribute, and + /// the `{oauthAccount, userID}` identity out of `~/.claude.json`, and + /// writes them into the profile. + /// + /// If a profile of that name already exists this errors unless `force` is + /// set, in which case it is overwritten (the `--force` behavior). + /// + /// # Errors + /// + /// Returns [`Error::Invalid`] when the profile exists and `force` is + /// false, or when there is no active credential to snapshot; propagates + /// config-read and store-write errors otherwise. + pub fn save(&self, name: &str, force: bool) -> Result { + if self.store.contains(name) && !force { + return Err(Error::Invalid(format!( + "profile '{name}' already exists (pass --force to overwrite)" + ))); + } + let blob = self.creds.read()?.ok_or_else(|| { + Error::Invalid("no active credential found — sign in with 'claude' first".to_string()) + })?; + let config = config::load(&self.config_path)?; + let snapshot = self.identity_snapshot(&config)?; + self.store.save_profile(name, &blob, &snapshot)?; + Ok(config::account_of(&config)) + } + + /// Activate profile `name` as the current account. + /// + /// First re-snapshots the outgoing account (its token may have rotated) + /// into every profile that shares its token, then restores `name`'s + /// credential into the platform store and splices its identity into + /// `~/.claude.json`. + /// + /// # Errors + /// + /// Returns [`Error::ProfileNotFound`] / [`Error::Invalid`] when the target + /// profile is missing or incomplete; propagates credential, config, and + /// store errors otherwise. + pub fn activate(&self, name: &str) -> Result { + // Validate the target up front so a missing/incomplete profile fails + // before we touch any live state. + let target = self.store.load(name)?; + + // Re-snapshot the outgoing account before overwriting it. This may + // update `name`'s own credential file too, when it shares the outgoing + // account's token — which is exactly what we want. + self.sync_current()?; + + // Restore the credential. Re-read it from the store so we pick up any + // rotation `sync_current` just propagated into this profile. + let blob = self.store.load_credentials(name)?; + self.creds.write(&blob, &target.keychain_account())?; + + // Splice this profile's identity (incl. organizationUuid) into + // ~/.claude.json, preserving all unrelated keys. + config::patch(&self.config_path, &target.identity())?; + Ok(target.account()) + } + + /// Re-snapshot the live account's credential into every profile that + /// shares its token, and refresh the identity of the exact profile it maps + /// to. Silently does nothing when there is no config, no live identity, or + /// no active credential. + /// + /// # Errors + /// + /// Propagates store-write errors. + pub fn sync_current(&self) -> Result<()> { + let Ok(config) = config::load(&self.config_path) else { + return Ok(()); + }; + let active = config::account_of(&config); + if !self.scope.identifies(&active) { + return Ok(()); + } + let Some(blob) = self.creds.read()? else { + return Ok(()); + }; + let live_snapshot = self.identity_snapshot(&config)?; + let active_key = active.key(); + + for shared in self.store.profiles_sharing_token(&active, self.scope)? { + // Every sibling gets the freshly rotated credential... + self.store.write_credentials(&shared.name, &blob)?; + // ...but only the profile whose (account, org) *is* the live one + // gets its identity snapshot refreshed. A sibling for a different + // org must keep its own organizationUuid. + if shared.account.key() == active_key { + self.store.write_account(&shared.name, &live_snapshot)?; + } + } + Ok(()) + } + + /// Build the `{oauthAccount, userID, keychain_account}` snapshot stored in + /// a profile's `account.json` from a loaded config and the current + /// keychain account attribute. + fn identity_snapshot(&self, config: &Value) -> Result { + let keychain_account = self.creds.account_attr()?.unwrap_or_default(); + let mut snapshot = config::extract_identity(config); + if let Some(obj) = snapshot.as_object_mut() { + obj.insert("keychain_account".to_string(), json!(keychain_account)); + } + Ok(snapshot) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::RefCell; + use std::fs; + use std::path::PathBuf; + + /// In-memory fake of the platform credential store. + struct FakeCredentialStore { + blob: RefCell>, + acct: Option, + fail_read: bool, + fail_write: bool, + fail_acct: bool, + } + + impl FakeCredentialStore { + fn with(blob: Option<&str>, acct: Option<&str>) -> Self { + Self { + blob: RefCell::new(blob.map(str::to_string)), + acct: acct.map(str::to_string), + fail_read: false, + fail_write: false, + fail_acct: false, + } + } + } + + impl CredentialStore for FakeCredentialStore { + fn read(&self) -> Result> { + if self.fail_read { + return Err(Error::Invalid("read failed".to_string())); + } + Ok(self.blob.borrow().clone()) + } + + fn write(&self, blob: &str, _acct: &str) -> Result<()> { + if self.fail_write { + return Err(Error::Invalid("write failed".to_string())); + } + *self.blob.borrow_mut() = Some(blob.to_string()); + Ok(()) + } + + fn account_attr(&self) -> Result> { + if self.fail_acct { + return Err(Error::Invalid("account_attr failed".to_string())); + } + Ok(self.acct.clone()) + } + } + + fn temp_dir() -> PathBuf { + use std::sync::atomic::{AtomicU64, Ordering}; + static COUNTER: AtomicU64 = AtomicU64::new(0); + let base = std::env::temp_dir().join(format!( + "ccswitch-switch-{}-{}", + std::process::id(), + COUNTER.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&base).unwrap(); + base + } + + fn config_json(acct: &str, org: &str, email: &str, user: &str) -> Value { + json!({ + "numStartups": 3, + "userID": user, + "oauthAccount": { + "accountUuid": acct, + "organizationUuid": org, + "emailAddress": email, + "organizationName": "Org", + "organizationRole": "admin", + "profileFetchedAt": "yesterday" + }, + "projects": { "/x": { "allowedTools": [] } } + }) + } + + fn write_config(dir: &Path, value: &Value) -> PathBuf { + let path = dir.join(".claude.json"); + fs::write(&path, serde_json::to_string_pretty(value).unwrap()).unwrap(); + path + } + + // ---- save -------------------------------------------------------------- + + #[test] + fn save_new_profile_snapshots_live_state() { + let dir = temp_dir(); + let config = write_config(&dir, &config_json("A", "O1", "a@example.com", "uid-1")); + let store = Store::new(dir.join("accounts")); + let creds = FakeCredentialStore::with(Some("BLOB-1"), Some("login-attr")); + let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccount); + + let account = switcher.save("orga", false).unwrap(); + assert_eq!(account.email, "a@example.com"); + assert_eq!(switcher.config_path(), config); + + let loaded = store.load("orga").unwrap(); + assert_eq!(loaded.credentials, "BLOB-1"); + assert_eq!(loaded.keychain_account(), "login-attr"); + assert_eq!(loaded.account().org_uuid, "O1"); + assert_eq!(loaded.account.get("userID").unwrap(), &json!("uid-1")); + // The full oauthAccount is preserved, not just keyed fields. + assert_eq!( + loaded.account["oauthAccount"]["profileFetchedAt"], + json!("yesterday") + ); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn save_existing_without_force_errors() { + let dir = temp_dir(); + let config = write_config(&dir, &config_json("A", "O1", "a@x", "uid-1")); + let store = Store::new(dir.join("accounts")); + let creds = FakeCredentialStore::with(Some("BLOB-1"), None); + let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccount); + + switcher.save("orga", false).unwrap(); + let err = switcher.save("orga", false).unwrap_err(); + assert!(matches!(err, Error::Invalid(msg) if msg.contains("already exists"))); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn save_existing_with_force_overwrites() { + let dir = temp_dir(); + let config = write_config(&dir, &config_json("A", "O1", "a@x", "uid-1")); + let store = Store::new(dir.join("accounts")); + let creds = FakeCredentialStore::with(Some("BLOB-1"), None); + let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccount); + switcher.save("orga", false).unwrap(); + + // A newer credential arrives; force overwrites the stored snapshot. + *creds.blob.borrow_mut() = Some("BLOB-2".to_string()); + switcher.save("orga", true).unwrap(); + assert_eq!(store.load("orga").unwrap().credentials, "BLOB-2"); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn save_without_credential_errors() { + let dir = temp_dir(); + let config = write_config(&dir, &config_json("A", "O1", "a@x", "uid-1")); + let store = Store::new(dir.join("accounts")); + let creds = FakeCredentialStore::with(None, None); + let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccount); + let err = switcher.save("orga", false).unwrap_err(); + assert!(matches!(err, Error::Invalid(msg) if msg.contains("no active credential"))); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn save_propagates_credential_read_error() { + let dir = temp_dir(); + let config = write_config(&dir, &config_json("A", "O1", "a@x", "uid-1")); + let store = Store::new(dir.join("accounts")); + let mut creds = FakeCredentialStore::with(Some("BLOB"), None); + creds.fail_read = true; + let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccount); + assert!(switcher.save("orga", false).is_err()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn save_propagates_account_attr_error() { + let dir = temp_dir(); + let config = write_config(&dir, &config_json("A", "O1", "a@x", "uid-1")); + let store = Store::new(dir.join("accounts")); + let mut creds = FakeCredentialStore::with(Some("BLOB"), None); + creds.fail_acct = true; + let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccount); + assert!(switcher.save("orga", false).is_err()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn save_missing_config_errors() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let creds = FakeCredentialStore::with(Some("BLOB"), None); + let switcher = Switcher::new( + &creds, + &store, + dir.join(".claude.json"), + TokenScope::PerAccount, + ); + assert!(switcher.save("orga", false).is_err()); + fs::remove_dir_all(&dir).unwrap(); + } + + // ---- activate ---------------------------------------------------------- + + #[test] + fn activate_restores_credential_and_identity() { + let dir = temp_dir(); + // Live account is B/OB; we switch to a saved A/OA profile. + let config = write_config(&dir, &config_json("B", "OB", "b@example.com", "uid-b")); + let store = Store::new(dir.join("accounts")); + let creds = FakeCredentialStore::with(Some("LIVE-B"), Some("attr-b")); + let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccount); + + // Seed a saved profile for a different account. + store + .save_profile( + "orga", + "TOKEN-A", + &json!({ + "oauthAccount": { + "accountUuid": "A", + "organizationUuid": "OA", + "emailAddress": "a@example.com", + "organizationName": "Org A" + }, + "userID": "uid-a", + "keychain_account": "attr-a" + }), + ) + .unwrap(); + + let account = switcher.activate("orga").unwrap(); + assert_eq!(account.email, "a@example.com"); + + // Credential store now holds profile A's token. + assert_eq!(creds.blob.borrow().as_deref(), Some("TOKEN-A")); + // Config identity was spliced to A/OA, unrelated keys preserved. + let patched = config::load(&config).unwrap(); + assert_eq!(patched["oauthAccount"]["accountUuid"], json!("A")); + assert_eq!(patched["oauthAccount"]["organizationUuid"], json!("OA")); + assert_eq!(patched["userID"], json!("uid-a")); + assert_eq!(patched["numStartups"], json!(3)); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn activate_missing_profile_errors_without_touching_state() { + let dir = temp_dir(); + let config = write_config(&dir, &config_json("A", "OA", "a@x", "uid-a")); + let store = Store::new(dir.join("accounts")); + let creds = FakeCredentialStore::with(Some("LIVE"), None); + let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccount); + assert!(matches!( + switcher.activate("ghost"), + Err(Error::ProfileNotFound(_)) + )); + // Live credential untouched. + assert_eq!(creds.blob.borrow().as_deref(), Some("LIVE")); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn activate_propagates_credential_write_error() { + let dir = temp_dir(); + let config = write_config(&dir, &config_json("B", "OB", "b@x", "uid-b")); + let store = Store::new(dir.join("accounts")); + store + .save_profile( + "orga", + "TOKEN-A", + &json!({ + "oauthAccount": { "accountUuid": "A", "organizationUuid": "OA" }, + "userID": "uid-a", + "keychain_account": "attr-a" + }), + ) + .unwrap(); + let mut creds = FakeCredentialStore::with(Some("LIVE-B"), Some("attr-b")); + creds.fail_write = true; + let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccount); + assert!(switcher.activate("orga").is_err()); + fs::remove_dir_all(&dir).unwrap(); + } + + // ---- the rotation fix -------------------------------------------------- + + #[test] + fn rotated_token_propagates_to_all_sibling_org_profiles() { + let dir = temp_dir(); + // Two profiles: same account A, different orgs O1 and O2. + // Active account is A/O1; both were saved with the same original token. + let config = write_config(&dir, &config_json("A", "O1", "a@example.com", "uid-a")); + let store = Store::new(dir.join("accounts")); + + let snap = |org: &str| { + json!({ + "oauthAccount": { + "accountUuid": "A", + "organizationUuid": org, + "emailAddress": "a@example.com", + "organizationName": org + }, + "userID": "uid-a", + "keychain_account": "attr-a" + }) + }; + store.save_profile("orga", "R-OLD", &snap("O1")).unwrap(); + store.save_profile("orgb", "R-OLD", &snap("O2")).unwrap(); + + // The live credential has since rotated (claude ran under O1). + let creds = FakeCredentialStore::with(Some("R-NEW"), Some("attr-a")); + let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccount); + + // Switch to the sibling org profile. + switcher.activate("orgb").unwrap(); + + // THE FIX: both same-account profiles now hold the rotated token, not + // just the one matching the live (account, org) key. + assert_eq!(store.load_credentials("orga").unwrap(), "R-NEW"); + assert_eq!(store.load_credentials("orgb").unwrap(), "R-NEW"); + + // orga keeps its own org identity (not overwritten with O2's live one). + assert_eq!(store.load("orga").unwrap().account().org_uuid, "O1"); + + // The credential restored into the live store is the current token, so + // switching to orgb does not force a re-login. + assert_eq!(creds.blob.borrow().as_deref(), Some("R-NEW")); + + // And switching back to orga also restores the live token — no + // re-login there either. + switcher.activate("orga").unwrap(); + assert_eq!(creds.blob.borrow().as_deref(), Some("R-NEW")); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn per_account_org_scope_isolates_credential_to_exact_profile() { + let dir = temp_dir(); + let config = write_config(&dir, &config_json("A", "O1", "a@x", "uid-a")); + let store = Store::new(dir.join("accounts")); + let snap = |org: &str| { + json!({ + "oauthAccount": { "accountUuid": "A", "organizationUuid": org }, + "userID": "uid-a", + "keychain_account": "attr-a" + }) + }; + store.save_profile("orga", "R-OLD", &snap("O1")).unwrap(); + store.save_profile("orgb", "R-OLD", &snap("O2")).unwrap(); + + let creds = FakeCredentialStore::with(Some("R-NEW"), Some("attr-a")); + // Under the stricter (buggy) scope, only the exact match is synced. + let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccountOrg); + switcher.sync_current().unwrap(); + + assert_eq!(store.load_credentials("orga").unwrap(), "R-NEW"); + // orgb is NOT updated — this is the stranding the PerAccount fix cures. + assert_eq!(store.load_credentials("orgb").unwrap(), "R-OLD"); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn sync_current_refreshes_identity_of_exact_match() { + let dir = temp_dir(); + // Live identity has advanced (new profileFetchedAt) vs the snapshot. + let config = write_config(&dir, &config_json("A", "O1", "a@example.com", "uid-a")); + let store = Store::new(dir.join("accounts")); + store + .save_profile( + "orga", + "R-OLD", + &json!({ + "oauthAccount": { + "accountUuid": "A", + "organizationUuid": "O1", + "profileFetchedAt": "stale" + }, + "userID": "uid-a", + "keychain_account": "attr-a" + }), + ) + .unwrap(); + let creds = FakeCredentialStore::with(Some("R-NEW"), Some("attr-a")); + let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccount); + switcher.sync_current().unwrap(); + + let refreshed = store.load("orga").unwrap(); + assert_eq!(refreshed.credentials, "R-NEW"); + assert_eq!( + refreshed.account["oauthAccount"]["profileFetchedAt"], + json!("yesterday") + ); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn sync_current_no_config_is_noop() { + let dir = temp_dir(); + let store = Store::new(dir.join("accounts")); + let creds = FakeCredentialStore::with(Some("R-NEW"), None); + let switcher = Switcher::new( + &creds, + &store, + dir.join(".claude.json"), + TokenScope::PerAccount, + ); + switcher.sync_current().unwrap(); + assert!(store.list().unwrap().is_empty()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn sync_current_empty_identity_is_noop() { + let dir = temp_dir(); + let config = write_config(&dir, &json!({ "numStartups": 1 })); + let store = Store::new(dir.join("accounts")); + store + .save_profile("orga", "R-OLD", &json!({ "oauthAccount": {} })) + .unwrap(); + let creds = FakeCredentialStore::with(Some("R-NEW"), None); + let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccount); + switcher.sync_current().unwrap(); + assert_eq!(store.load_credentials("orga").unwrap(), "R-OLD"); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn sync_current_no_live_credential_is_noop() { + let dir = temp_dir(); + let config = write_config(&dir, &config_json("A", "O1", "a@x", "uid-a")); + let store = Store::new(dir.join("accounts")); + store + .save_profile( + "orga", + "R-OLD", + &json!({ "oauthAccount": { "accountUuid": "A", "organizationUuid": "O1" } }), + ) + .unwrap(); + let creds = FakeCredentialStore::with(None, None); + let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccount); + switcher.sync_current().unwrap(); + assert_eq!(store.load_credentials("orga").unwrap(), "R-OLD"); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn sync_current_propagates_credential_read_error() { + let dir = temp_dir(); + let config = write_config(&dir, &config_json("A", "O1", "a@x", "uid-a")); + let store = Store::new(dir.join("accounts")); + let mut creds = FakeCredentialStore::with(Some("R-NEW"), None); + creds.fail_read = true; + let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccount); + assert!(switcher.sync_current().is_err()); + fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/tests/smoke.rs b/tests/smoke.rs new file mode 100644 index 0000000..6852a01 --- /dev/null +++ b/tests/smoke.rs @@ -0,0 +1,21 @@ +//! Smoke test: the crate's public pure helpers behave as documented. + +use ccswitch::cli; +use std::path::Path; + +#[test] +fn help_text_and_reserved_words_are_public() { + assert!(cli::help_text().contains("ccswitch ")); + assert!(cli::is_reserved("list")); + assert!(!cli::is_reserved("dev")); +} + +#[test] +fn default_paths_resolve_under_home() { + let home = Path::new("/home/example"); + assert_eq!( + cli::ccswitch_home(None, home), + home.join(".claude").join("accounts") + ); + assert_eq!(cli::config_path(home), home.join(".claude.json")); +}