From 9f034b6815ede7d139c13f9107f27371d51c2d01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hermann=20R=C3=B6sch?= Date: Wed, 11 Nov 2026 15:50:33 -0500 Subject: [PATCH] fix(claude-as): --add keeps only the login it asked for, and --tidy repairs the homes retries left --add signed in straight into ~/.claude-. When the browser signed in another account, or the sign-in was left unfinished, that home stayed behind under the wrong name, and each retry made the next one: -2, -3, -4. One machine ended up with its team account in -3, beside two homes holding the personal account and one holding nothing. - --add signs in in a staging folder and names the home only once the login is that email. Anything else leaves nothing behind. A second organization of one email is ~/.claude--, never a number. - --tidy [--dry-run] archives signed-out and duplicate homes (history kept, credentials deleted, not revoked) and renames misnamed ones after their login, with the macOS Keychain item named after the path. A name without an email (~/.claude-work) stays. A home a running process holds is never archived; it is renamed only when its login is a .credentials.json, and the running sessions follow a link at the old path, dropped by a later --tidy. - Session records follow a renamed or archived home, so -r resumes in the right place. - --check names a misnamed or duplicate home and the command that fixes it. Tests: 31 new or rewritten bats cases (102 in claude-as.bats, all passing, also under macOS bash 3.2). Smoke-tested on guty-arm64-rig: the four retries became ~/.claude (personal) and ~/.claude-hermann.g.rosch@tafitech.io (team), with six live sessions running on through the link. Co-Authored-By: Claude Opus 5.5 --- bin/claude-as | 337 ++++++++++++++++--- docs/how-to-use-multiple-accounts.md | 40 ++- tests/claude-as.bats | 473 ++++++++++++++++++++++++++- 3 files changed, 795 insertions(+), 55 deletions(-) diff --git a/bin/claude-as b/bin/claude-as index 1aff486..ebf9e4f 100755 --- a/bin/claude-as +++ b/bin/claude-as @@ -26,8 +26,11 @@ # claude-as --host-alias the machine's short name in session names # claude-as --move [opts] every Claude session in this machine's herdr # continues as that account (see --move below) -# claude-as --add [args] new home for an account, then sign it in -# claude-as --check every home: login, links, shared history +# claude-as --add [args] sign an account in; its home is named after it +# once the login is known to be that email +# claude-as --tidy [--dry-run] one home per account, named after it: archives +# signed-out and duplicate homes, renames the rest +# claude-as --check every home: login, name, links, shared history # claude-as --relink link shared items a home is missing # # The email is matched whole, in any case; never a part of one, which a later @@ -38,7 +41,13 @@ # With CLAUDE_AS set, a first argument that is a claude option runs as it. # A session resumed by id runs as the account it last ran as, which # hooks/session-account.sh records; naming another account asks first. -# --add passes [args] to `claude auth login` (for example --sso). +# --add passes [args] to `claude auth login` (for example --sso). The login is +# made in a staging folder: a browser signed in to another account, or a +# sign-in left unfinished, leaves no home behind. A home is ~/.claude-, +# or ~/.claude-- for another organization of that email. +# --tidy archives into $XDG_STATE_HOME/claude-as/removed (credentials deleted, +# history kept) and leaves alone a home a running Claude Code still uses; a +# renamed home in use keeps its old path as a link until a later --tidy. # # --move [--pane ] [--dry-run] [--force] [--wait ] # moves each Claude session herdr runs on this machine to that account, in its @@ -359,6 +368,8 @@ last_home() { done < <(homes) fi [[ -n ${last} ]] || return 0 + # A home --tidy renamed while the session ran left a link in its place. + [[ -L ${last} ]] && last=$(readlink "${last}") while IFS= read -r home; do if [[ ${home} == "${last}" ]]; then printf '%s\n' "${home}" @@ -597,59 +608,294 @@ link_shared() { done } +state_dir="${XDG_STATE_HOME:-${HOME}/.local/state}/claude-as" +# The login being signed in by --add, discarded unless it is kept. +adding="" +# Homes a --tidy --dry-run would archive: their names count as free. +freed="" + +sha256() { + if command -v sha256sum >/dev/null 2>&1; then sha256sum; else shasum -a 256; fi | cut -d' ' -f1 +} + +# Claude Code names a home's Keychain login after the home's path, so a home +# that moves must carry it; a .credentials.json login (Linux, or a Keychain +# locked over SSH) moves with the folder. +secret_service() { + if [[ $1 == "${HOME}/.claude" ]]; then + printf 'Claude Code-credentials\n' + else + printf 'Claude Code-credentials-%s\n' "$(printf '%s' "$1" | sha256 | cut -c1-8)" + fi +} + +keychain() { [[ $(uname -s) == Darwin ]] && command -v security >/dev/null 2>&1; } + +# Moves 's Keychain login to . The secret goes to security(1) on +# stdin: a command line is readable by every process of the machine. +# Status 1: there may be one, but the Keychain is locked. +carry_secret() { + local from to secret quoted rc=0 user=${USER:-$(id -un)} + keychain || return 0 + from=$(secret_service "$1") + to=$(secret_service "$2") + secret=$(security find-generic-password -s "${from}" -a "${user}" -w 2>/dev/null) || rc=$? + # 44: no such item, so nothing to carry; anything else: locked or refused. + case ${rc} in + 0) ;; + 44) return 0 ;; + *) return 1 ;; + esac + quoted=${secret//\\/\\\\} + quoted=${quoted//\"/\\\"} + printf 'add-generic-password -U -s "%s" -a "%s" -w "%s"\n' "${to}" "${user}" "${quoted}" \ + | security -i >/dev/null 2>&1 || return 1 + security delete-generic-password -s "${from}" -a "${user}" >/dev/null 2>&1 || true +} + +# Whether 's login is a Keychain item. Reading an item's attributes works +# while the Keychain is locked; reading its secret does not. +keychain_login() { + keychain && security find-generic-password -s "$(secret_service "$1")" -a "${USER:-$(id -un)}" >/dev/null 2>&1 +} + +drop_secret() { + keychain || return 0 + security delete-generic-password -s "$(secret_service "$1")" -a "${USER:-$(id -un)}" >/dev/null 2>&1 || true +} + +# Homes a running process has as CLAUDE_CONFIG_DIR. pgrep matches names, not +# environments, so ps(1) it is (BSD and procps alike). +live_homes() { + # shellcheck disable=SC2009 + ps eww -A -o command= 2>/dev/null | grep -oE '(^| )CLAUDE_CONFIG_DIR=[^ ]+' \ + | sed -e 's/^ //' -e 's/^CLAUDE_CONFIG_DIR=//' -e 's:/*$::' | sort -u || true +} + +in_use() { live_homes | grep -qxF -- "$1"; } + +# "herdr (3427), kdeconnectd (76969) and 2 more": who holds . A process +# that is not Claude Code still hands it to everything it starts. +users_of() { + local pid name list="" n=0 + # shellcheck disable=SC2009 + while read -r pid; do + n=$((n + 1)) + ((n <= 2)) || continue + name=$(ps -p "${pid}" -o comm= 2>/dev/null) + list+="${list:+, }${name##*/} (${pid})" + done < <(ps eww -A -o pid=,command= 2>/dev/null | grep -F -- " CLAUDE_CONFIG_DIR=$1 " | awk '{ print $1 }') + ((n > 2)) && list+=" and $((n - 2)) more" + printf '%s\n' "${list:-a running process}" +} + +signed_in() { + (cd / && in_home "$1" auth status --json /dev/null || true) \ + | jq -e '.loggedIn == true' >/dev/null 2>&1 +} + +# Where a home signed in as // belongs: ~/.claude-, +# else with the org slug, else the id; may already be it. +# A path that exists is never reused. +home_for() { + local home=$1 base want + base="${HOME}/.claude-$(lower "$2")" + for want in "${base}" "${base}-$(slug "$3" 24)" "${base}-$(lower "${4:0:8}")"; do + [[ ${want} != "${base}-" ]] || continue + if [[ ${want} == "${home}" ]] || ! [[ -e ${want} || -L ${want} ]] || grep -qxF -- "${want}" <<<"${freed}"; then + printf '%s\n' "${want}" + return 0 + fi + done + [[ -n ${home} ]] || return 1 + printf '%s\n' "${home}" +} + +# A name without an email (~/.claude-work) is the user's choice and stays; +# one with an email is claude-as's, so it must be that login's own. +chosen_name() { [[ ${1##*/} != *@* ]]; } + +# The record of which home each session ran in follows a home that moved. +retarget_ledger() { + [[ -r ${ledger} ]] || return 0 + awk -F'\t' -v OFS='\t' -v from="$1" -v to="$2" '$2 == from { $2 = to } { print }' \ + "${ledger}" >"${ledger}.$$" && mv "${ledger}.$$" "${ledger}" +} + +# Moves to with its login, undone unless it is still signed in. +# A session running in follows a link, so its one .credentials.json is +# shared; a Keychain login cannot be, and relocate() is not called for it. +relocate() { + local from=$1 to=$2 live=0 + in_use "${from}" && live=1 + mv "${from}" "${to}" || return 1 + carry_secret "${from}" "${to}" \ + || printf 'claude-as: the Keychain is locked; %s keeps its Keychain login\n' "$(short "${from}")" >&2 + ((live)) && ln -s "${to}" "${from}" + if ! signed_in "${to}"; then + [[ -L ${from} ]] && rm "${from}" + carry_secret "${to}" "${from}" || true + mv "${to}" "${from}" + return 1 + fi + retarget_ledger "${from}" "${to}" + if ((live)); then + printf 'renamed %s -> %s (running sessions use it through a link)\n' "$(short "${from}")" "$(short "${to}")" + else + printf 'renamed %s -> %s\n' "$(short "${from}")" "$(short "${to}")" + fi +} + +# Archives , keeping its history but not its login. The token is deleted +# here, not revoked: another home of the account may share the grant. +retire() { + local home=$1 dest + dest="${state_dir}/removed/${home##*/}-$(date +%Y%m%dT%H%M%S)" + mkdir -p "${state_dir}/removed" + chmod 700 "${state_dir}/removed" + drop_secret "${home}" + rm -f "${home}/.credentials.json" + mv "${home}" "${dest}" + # Its sessions resume as the home of the same account that stays, if any. + retarget_ledger "${home}" "${3:-${dest}}" + printf 'archived %s -> %s (%s)\n' "$(short "${home}")" "$(short "${dest}")" "$2" +} + +discard_adding() { + [[ -n ${adding} && -d ${adding} ]] || return 0 + drop_secret "${adding}" + rm -rf "${adding}" + adding="" +} + add() { - local email=$1 home base n=1 line + local email=$1 home got org plan uuid other oemail ouuid shift # The home and its account file are the account's alone. umask 077 [[ ${email} =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$ ]] || die "'${email}' is not an email" 2 [[ -d ${shared} ]] || die "$(short "${shared}") does not exist; run claude once first" - while IFS=$'\037' read -r home line _; do - if [[ $(lower "${line}") == "$(lower "${email}")" ]]; then - printf '%s is signed in already: %s\n' "${email}" "$(accounts_of "${home}")" - printf 'Signing in again, for another of its organizations: pick it in the browser.\n' - fi - done < <(accounts) - base="${HOME}/.claude-$(lower "${email}")" - home=${base} - while [[ -e ${home} ]]; do - n=$((n + 1)) - home="${base}-${n}" - done - mkdir -p "${home}" - chmod 700 "${home}" - link_shared "${home}" + # Signed in in a staging folder and named only once known to be : + # a browser on another account, or an unfinished sign-in, leaves nothing. + mkdir -p "${state_dir}" + adding=$(mktemp -d "${state_dir}/adding.XXXXXX") + trap discard_adding EXIT + trap 'exit 130' INT TERM HUP + link_shared "${adding}" >/dev/null # Skip the first-run wizard and keep the folders already trusted: the # account changes, the person and the machine do not. jq '{hasCompletedOnboarding: true, projects: ((.projects // {}) | with_entries(select(.value.hasTrustDialogAccepted == true) | .value = {hasTrustDialogAccepted: true}))}' "$(account_file "${shared}")" \ - >"$(account_file "${home}")" 2>/dev/null \ - || jq -n '{hasCompletedOnboarding: true}' >"$(account_file "${home}")" - chmod 600 "$(account_file "${home}")" - printf 'Signing in %s in %s\n' "${email}" "$(short "${home}")" - (cd / && in_home "${home}" auth login --email "${email}" "$@") \ - || die "sign-in did not finish; run it again: claude-as --add ${email}" - added "${home}" "${email}" -} - -# What the new login turned out to be, and why it may not work as hoped. -added() { - local home=$1 email=$2 got org plan uuid other oemail ouuid - IFS=$'\037' read -r _ got org plan uuid < <(CLAUDE_AS_HOMES=${home} accounts) + >"$(account_file "${adding}")" 2>/dev/null \ + || jq -n '{hasCompletedOnboarding: true}' >"$(account_file "${adding}")" + chmod 600 "$(account_file "${adding}")" + printf 'Signing in %s\n' "${email}" + (cd / && in_home "${adding}" auth login --email "${email}" "$@") \ + || die "sign-in did not finish; nothing was kept. Run it again: claude-as --add ${email}" + IFS=$'\037' read -r _ got org plan uuid < <(CLAUDE_AS_HOMES=${adding} accounts) [[ $(lower "${got}") == "$(lower "${email}")" ]] \ - || die "signed in as '${got:-nobody}', not ${email}; sign in again: CLAUDE_CONFIG_DIR=$(short "${home}") claude auth login" + || die "the browser signed in '${got:-nobody}', not ${email}; nothing was kept. Sign out of ${got:-it} in the browser, or use a private window, and run it again" while IFS=$'\037' read -r other oemail _ _ ouuid; do - [[ ${other} != "${home}" && -n ${uuid} && ${ouuid} == "${uuid}" && - $(lower "${oemail}") == "$(lower "${email}")" ]] \ - && printf 'note: %s is the same account and organization as %s\n' "$(short "${home}")" "$(short "${other}")" + if [[ -n ${uuid} && ${ouuid} == "${uuid}" && $(lower "${oemail}") == "$(lower "${email}")" ]]; then + printf '%s is this account and organization already; nothing new was kept\n' "$(short "${other}")" + exit 0 + fi done < <(accounts) + home=$(home_for "" "${email}" "${org}" "${uuid}") || die "no free name for ${email} in ~/.claude-${email}*; run claude-as --tidy" + relocate "${adding}" "${home}" >/dev/null || die "the new login did not survive the move to $(short "${home}"); nothing was kept" + adding="" + trap - EXIT INT TERM HUP case ${plan} in free* | "") printf 'warning: %s has no paid plan; Claude Code needs Pro, Max, Team or Enterprise\n' "${email}" >&2 ;; esac + printf 'Signed in %s in %s\n' "${email}" "$(short "${home}")" printf 'Ready: claude-as %s\n' "$(name_of "${home}")" } +# archive (signed out, or the same account and org as an earlier home in +# , "/\t" lines) or keep. An unknown org id is no +# proof of a duplicate. +tidy_plan() { + local home=$1 email=$2 uuid=$4 kept=$5 key twin + key="$(lower "${email}")/${uuid}" + twin=$(awk -F'\t' -v k="${key}" '$1 == k { print $2; exit }' <<<"${kept}") + if ! signed_in "${home}"; then + printf 'archive\tnot signed in\t\n' + elif [[ -n ${email} && -n ${uuid} && -n ${twin} ]]; then + printf 'archive\tthe same account and organization as %s\t%s\n' "$(short "${twin}")" "${twin}" + else + printf 'keep\t%s\t%s\n' "${key}" "${home}" + fi +} + +# --tidy [--dry-run]: one home per account, named after it. Signed-out and +# duplicate homes are archived, never deleted; misnamed ones renamed with +# their login. A home a running session uses is left alone. +tidy() { + local dry=0 link to home email org plan uuid action why twin kept="" keep_homes="" want changed=0 held=0 + case ${1:-} in + "") ;; + --dry-run) dry=1 ;; + *) die "usage: claude-as --tidy [--dry-run]" 2 ;; + esac + for link in "${HOME}"/.claude-*; do + to=$(readlink "${link}" 2>/dev/null) || continue + [[ ${to} == "${HOME}"/.claude-* && -d ${to} ]] || continue + in_use "${link}" && continue + changed=1 + if ((dry)); then + printf 'would drop %s: a link no running session uses\n' "$(short "${link}")" + else + # A session's hook may have recorded the link since the rename. + rm "${link}" + retarget_ledger "${link}" "${to}" + printf 'dropped %s: a link no running session uses\n' "$(short "${link}")" + fi + done + while IFS=$'\037' read -r home email org plan uuid; do + IFS=$'\t' read -r action why twin <<<"$(tidy_plan "${home}" "${email}" "${org}" "${uuid}" "${kept}")" + if [[ ${action} == keep ]]; then + kept+="${why}"$'\t'"${twin}"$'\n' + keep_homes+="${home}"$'\n' + continue + fi + [[ ${home} == "${shared}" ]] && continue + if in_use "${home}"; then + printf 'left alone %s: %s, but %s still holds it; run --tidy once it ends\n' \ + "$(short "${home}")" "${why}" "$(users_of "${home}")" + held=1 + continue + fi + changed=1 + if ((dry)); then + freed+="${home}"$'\n' + printf 'would archive %s (%s)\n' "$(short "${home}")" "${why}" + else + retire "${home}" "${why}" "${twin}" + fi + done < <(accounts) + while IFS=$'\037' read -r home email org plan uuid; do + if [[ ${home} == "${shared}" ]] || chosen_name "${home}"; then continue; fi + want=$(home_for "${home}" "${email}" "${org}" "${uuid}") + [[ ${want} != "${home}" ]] || continue + if in_use "${home}" && keychain_login "${home}"; then + printf 'left alone %s: should be %s, but %s holds its Keychain login; run --tidy once it ends\n' \ + "$(short "${home}")" "$(short "${want}")" "$(users_of "${home}")" + held=1 + continue + fi + changed=1 + if ((dry)); then + printf 'would rename %s -> %s\n' "$(short "${home}")" "$(short "${want}")" + elif ! relocate "${home}" "${want}"; then + printf 'left alone %s: its login did not survive the move to %s\n' "$(short "${home}")" "$(short "${want}")" + held=1 + fi + done < <(while IFS= read -r home; do [[ -z ${home} ]] || CLAUDE_AS_HOMES=${home} accounts; done <<<"${keep_homes}") + ((changed || held)) || printf 'nothing to tidy: one home per account, each named after it\n' +} + # A transcript only the shared projects folder holds: a home that can resume # it sees the shared history. Claude Code refuses to resume it without a # prompt, before any model call, so the check costs no usage, and the @@ -674,7 +920,7 @@ canary_gone() { } check() { - local problems=0 home email org plan uuid status out name src dst managed version + local problems=0 home email org plan uuid status out name src dst managed version kept="" want canary # Claude Code gives each home its own Keychain entry from 2.1.144 on. if [[ $(uname -s) == Darwin ]]; then @@ -693,8 +939,19 @@ check() { status=$(cd / && in_home "${home}" auth status --json /dev/null || true) if jq -e '.loggedIn == true' <<<"${status}" >/dev/null 2>&1; then printf ' ok signed in\n' + if [[ -n ${uuid} ]] && grep -qxF -- "$(lower "${email}")/${uuid}" <<<"${kept}"; then + printf ' FAIL the same account and organization as another home: claude-as --tidy archives it\n' + problems=$((problems + 1)) + elif [[ ${home} != "${shared}" ]] && ! chosen_name "${home}"; then + want=$(home_for "${home}" "${email}" "${org}" "${uuid}") + if [[ ${want} != "${home}" ]]; then + printf ' FAIL not named after %s: claude-as --tidy renames it to %s\n' "${email}" "$(short "${want}")" + problems=$((problems + 1)) + fi + fi + kept+="$(lower "${email}")/${uuid}"$'\n' else - printf ' FAIL not signed in: claude-as --add \n' + printf ' FAIL not signed in: claude-as --add signs one in, claude-as --tidy archives it\n' problems=$((problems + 1)) fi if [[ ${home} != "${shared}" ]]; then @@ -1084,6 +1341,10 @@ case ${1:-} in add "$@" ;; --check) check ;; + --tidy) + shift + tidy "$@" + ;; --move) [[ -n ${2:-} && ${2} != -* ]] || die "usage: claude-as --move [--pane ] [--dry-run] [--force] [--wait ]" 2 shift diff --git a/docs/how-to-use-multiple-accounts.md b/docs/how-to-use-multiple-accounts.md index 8f899e9..5de52cc 100644 --- a/docs/how-to-use-multiple-accounts.md +++ b/docs/how-to-use-multiple-accounts.md @@ -27,11 +27,17 @@ builds on that: claude-as --add you@example.com ``` -This creates the home and opens Claude Code's own sign-in for that email. On a -machine without a browser, open the printed link elsewhere and paste the code -back. Use a private browser window when the browser is signed in to another -Claude account. Arguments after the email go to `claude auth login`, for -example `--sso` for an Enterprise login. +This opens Claude Code's own sign-in for that email. On a machine without a +browser, open the printed link elsewhere and paste the code back. Arguments +after the email go to `claude auth login`, for example `--sso` for an +Enterprise login. + +The sign-in happens in a staging folder. The home gets its name, +`~/.claude-you@example.com`, only once the login is known to be that email. If +the browser signs in another account, or the sign-in is left unfinished, +nothing is kept: sign out of the other account in the browser, or use a +private window, and run it again. A second organization of the same email gets +`~/.claude-you@example.com-`. No home is ever named `-2` or `-3`. Each account signs in once per machine. Never copy a credentials file between machines: Claude Code rotates the token, so both copies stop working. @@ -178,10 +184,30 @@ On another machine, run it there: `ssh claude-as --move other@example.com ## Check every account ```bash -claude-as --check # signed in, links in place, sees the shared history -claude-as --relink # link what a home is missing; anything else is left alone +claude-as --check # signed in, named after its login, links in place, sees the shared history +claude-as --relink # link what a home is missing; anything else is left alone +claude-as --tidy --dry-run # what --tidy would do +claude-as --tidy # one home per account, each named after it ``` +`--tidy` repairs homes that older versions of `claude-as` left behind: + +- A home that is not signed in, or that holds the same account and + organization as an earlier one, is archived to + `~/.local/state/claude-as/removed/`. Its prompt history is kept, and its + credentials are deleted (not revoked, so the home that stays remains signed + in). Sessions recorded there resume in the home that stays. +- A home whose name holds another email, or a retry number such as `-3`, is + renamed after its login, along with its Keychain entry on macOS. +- A name without an email, such as `~/.claude-work`, is your own choice and + stays. +- A home a running session uses is never archived. It is renamed only when its + login is the home's `.credentials.json` (Linux, or macOS over SSH): the + session goes on through a link at the old path, and a later `--tidy` drops + the link once the session ends. A Keychain login cannot be shared that way, + so that home is left alone until its sessions end. `claude-as --move` ends + and resumes them for you. + `--check` makes no model request. It writes a small canary session to the shared history and asks each home to find it, so a Claude Code release that stops reading linked history shows up as a failure. The probes run outside the diff --git a/tests/claude-as.bats b/tests/claude-as.bats index e459fec..d89c7b6 100644 --- a/tests/claude-as.bats +++ b/tests/claude-as.bats @@ -25,6 +25,58 @@ setup() { echo '{}' >"${HOME}/.claude/settings.json" echo 'shared prompt' >"${HOME}/.claude/history.jsonl" stub_claude + stub_ps +} + +# ps: one process per home in STUB_LIVE (colon-separated) runs with it as its +# CLAUDE_CONFIG_DIR, as `ps eww` shows a process's environment. +stub_ps() { + stub_bin ps <<'EOF' +if [[ $1 == -p ]]; then + echo /opt/bin/claude + exit 0 +fi +IFS=: read -ra live <<<"${STUB_LIVE:-}" +n=100 +for h in "${live[@]}"; do + n=$((n + 1)) + [[ $* == *pid=* ]] && printf '%s ' "$n" + [[ -n $h ]] && printf '/usr/bin/claude --resume x TERM=xterm CLAUDE_CONFIG_DIR=%s HOME=/h\n' "$h" +done +exit 0 +EOF +} + +# security: a Keychain in $HOME/keychain/; argv goes to $HOME/security.argv +# and stdin to $HOME/security.stdin, so a test sees what a process listing would. +# STUB_KEYCHAIN_LOCKED=1 answers as a Keychain locked over SSH does (status 36). +stub_security() { + stub_bin security <<'EOF' +printf '%s\n' "$*" >>"$HOME/security.argv" +kc=$HOME/keychain +mkdir -p "$kc" +[[ -z ${STUB_KEYCHAIN_LOCKED:-} ]] || exit 36 +svc="" +args=("$@") +for ((i = 0; i < ${#args[@]}; i++)); do [[ ${args[i]} == -s ]] && svc=${args[i + 1]}; done +case $1 in + find-generic-password) [[ -f $kc/$svc ]] || exit 44; cat "$kc/$svc" ;; + delete-generic-password) [[ -f $kc/$svc ]] || exit 44; rm "$kc/$svc" ;; + -i) + line=$(cat) + printf '%s\n' "$line" >>"$HOME/security.stdin" + svc=$(sed -E 's/.* -s "([^"]*)".*/\1/' <<<"$line") + secret=$(sed -E 's/.* -w "(.*)"$/\1/' <<<"$line" | sed -e 's/\\"/"/g' -e 's/\\\\/\\/g') + printf '%s' "$secret" >"$kc/$svc" + ;; +esac +EOF + stub_bin uname 'echo Darwin' +} + +# The Keychain service Claude Code names after a home's path. +service_of() { + printf 'Claude Code-credentials-%s' "$(printf '%s' "$1" | { sha256sum 2>/dev/null || shasum -a 256; } | cut -c1-8)" } # The stub: `auth status` and `auth login` act on the home it is given; @@ -45,6 +97,8 @@ if [[ $1 == auth && $2 == status ]]; then fi if [[ $1 == auth && $2 == login ]]; then printf 'login %s\n' "${*:3}" >>"$HOME/logins" + [[ -z ${STUB_LOGIN_FAIL:-} ]] || exit 1 + printf '{"token": "for %s"}' "${STUB_EMAIL:-$4}" >"$home/.credentials.json" jq --arg e "${STUB_EMAIL:-$4}" --arg t "${STUB_TYPE:-claude_pro}" --arg o "${STUB_ORG:-Org}" \ '.oauthAccount = {emailAddress: $e, organizationType: $t, organizationName: $o, organizationUuid: ($o + "-id")}' \ "$acct" >"$acct.tmp" && cat "$acct.tmp" >"$acct" && rm "$acct.tmp" @@ -269,7 +323,8 @@ two_accounts() { [ "$(readlink "${h}/${name}")" = "${HOME}/.claude/${name}" ] done [ ! -e "${h}/history.jsonl" ] - [ ! -e "${h}/.credentials.json" ] + # Its own login, never a copy of the shared home's. + [ "$(cat "${h}/.credentials.json")" = '{"token": "for New@Home.example"}' ] jq -e '.hasCompletedOnboarding == true' "${h}/.claude.json" jq -e '.projects == {"/repo": {"hasTrustDialogAccepted": true}}' "${h}/.claude.json" jq -e '.oauthAccount.emailAddress == "New@Home.example"' "${h}/.claude.json" @@ -280,21 +335,52 @@ two_accounts() { [[ ${output} == *"home=${h} args=--dangerously-skip-permissions -p hi"* ]] } -@test "--add never reuses a folder that exists" { +@test "--add never reuses a folder that exists, and never numbers a retry" { account "${HOME}/.claude" me@work.example mkdir -p "${HOME}/.claude-b@x.example" - run "$SCRIPT" --add b@x.example + echo mine >"${HOME}/.claude-b@x.example/notes" + STUB_ORG="Big Co" run "$SCRIPT" --add b@x.example [ "$status" -eq 0 ] - [ -f "${HOME}/.claude-b@x.example-2/.claude.json" ] - [ ! -e "${HOME}/.claude-b@x.example/.claude.json" ] + [ -f "${HOME}/.claude-b@x.example-big-co/.claude.json" ] + [ "$(cat "${HOME}/.claude-b@x.example/notes")" = mine ] + [ ! -e "${HOME}/.claude-b@x.example-2" ] } -@test "--add says when the browser signed in someone else, or a free plan" { +@test "--add keeps nothing when the browser signed in someone else" { account "${HOME}/.claude" me@work.example STUB_EMAIL=other@x.example run "$SCRIPT" --add b@x.example [ "$status" -eq 1 ] - [[ ${output} == *"signed in as 'other@x.example', not b@x.example"* ]] + [[ ${output} == *"the browser signed in 'other@x.example', not b@x.example; nothing was kept"* ]] + [[ ${output} == *"Sign out of other@x.example in the browser, or use a private window"* ]] + [ -z "$(compgen -G "${HOME}/.claude-*" || true)" ] + [ -z "$(compgen -G "${XDG_STATE_HOME}/claude-as/adding.*" || true)" ] +} + +@test "--add keeps nothing when the sign-in does not finish" { + account "${HOME}/.claude" me@work.example + STUB_LOGIN_FAIL=1 run "$SCRIPT" --add b@x.example + [ "$status" -eq 1 ] + [[ ${output} == *"sign-in did not finish; nothing was kept"* ]] + [ -z "$(compgen -G "${HOME}/.claude-*" || true)" ] + [ -z "$(compgen -G "${XDG_STATE_HOME}/claude-as/adding.*" || true)" ] +} + +@test "three failed sign-ins and a good one leave one home, named after the email" { + account "${HOME}/.claude" me@work.example + STUB_EMAIL=me@work.example run "$SCRIPT" --add b@x.example + STUB_LOGIN_FAIL=1 run "$SCRIPT" --add b@x.example + STUB_EMAIL=other@x.example run "$SCRIPT" --add b@x.example + run "$SCRIPT" --add b@x.example + [ "$status" -eq 0 ] + run "$SCRIPT" + [ "$(grep -c 'claude-b@x.example' <<<"${output}")" -eq 1 ] + [[ ${output} == *"b@x.example"*"~/.claude-b@x.example"$'\n'* || ${output} == *"b@x.example"*"~/.claude-b@x.example" ]] +} + +@test "--add warns about a free plan" { + account "${HOME}/.claude" me@work.example STUB_TYPE=claude_free run "$SCRIPT" --add c@x.example + [ "$status" -eq 0 ] [[ ${output} == *"c@x.example has no paid plan"* ]] } @@ -302,12 +388,55 @@ two_accounts() { account "${HOME}/.claude" me@x.example claude_team Acme STUB_ORG=Personal run "$SCRIPT" --add me@x.example [ "$status" -eq 0 ] - [[ ${output} == *"is signed in already"* ]] - [[ ${output} != *"same account and organization"* ]] + [ -f "${HOME}/.claude-me@x.example/.claude.json" ] # Its name tells it apart from the email's other organization. [[ ${output} == *"Ready: claude-as me@x.example/pro"* ]] + STUB_ORG=Third run "$SCRIPT" --add me@x.example + [ -f "${HOME}/.claude-me@x.example-third/.claude.json" ] +} + +@test "--add for an account and organization already here keeps nothing new" { + account "${HOME}/.claude" me@x.example claude_team Acme STUB_ORG=Acme STUB_TYPE=claude_team run "$SCRIPT" --add me@x.example - [[ ${output} == *"is the same account and organization as ~/.claude"* ]] + [ "$status" -eq 0 ] + [[ ${output} == *"~/.claude is this account and organization already; nothing new was kept"* ]] + [ -z "$(compgen -G "${HOME}/.claude-*" || true)" ] +} + +@test "--add moves the login it made with the home: the credentials file" { + account "${HOME}/.claude" me@work.example + run "$SCRIPT" --add b@x.example + [ "$status" -eq 0 ] + [ "$(cat "${HOME}/.claude-b@x.example/.credentials.json")" = '{"token": "for b@x.example"}' ] + [ "$(file_mode "${HOME}/.claude-b@x.example")" = 700 ] +} + +@test "--add on macOS moves the Keychain login, never through a command line" { + account "${HOME}/.claude" me@work.example + stub_security + stub_bin claude <<'EOF' +home=${CLAUDE_CONFIG_DIR:-$HOME/.claude} +if [[ $1 == auth && $2 == login ]]; then + jq --arg e "$4" '.oauthAccount = {emailAddress: $e, organizationType: "claude_pro", organizationName: "Org", organizationUuid: "Org-id"}' \ + "$home/.claude.json" >"$home/j" && mv "$home/j" "$home/.claude.json" + svc="Claude Code-credentials-$(printf '%s' "$home" | { sha256sum 2>/dev/null || shasum -a 256; } | cut -c1-8)" + mkdir -p "$HOME/keychain" + printf '%s' '{"t":"s3cr\"et"}' >"$HOME/keychain/$svc" + exit 0 +fi +if [[ $1 == auth && $2 == status ]]; then + svc="Claude Code-credentials-$(printf '%s' "$home" | { sha256sum 2>/dev/null || shasum -a 256; } | cut -c1-8)" + [[ -f $HOME/keychain/$svc ]] && echo '{"loggedIn": true}' || echo '{"loggedIn": false}' + exit 0 +fi +EOF + run "$SCRIPT" --add b@x.example + [ "$status" -eq 0 ] + local h="${HOME}/.claude-b@x.example" + [ "$(cat "${HOME}/keychain/$(service_of "${h}")")" = '{"t":"s3cr\"et"}' ] + [ "$(find "${HOME}/keychain" -type f | wc -l | tr -d ' ')" -eq 1 ] + ! grep -q 's3cr' "${HOME}/security.argv" + grep -q 's3cr' "${HOME}/security.stdin" } @test "--add refuses what is not an email" { @@ -1129,3 +1258,327 @@ move_setup() { PATH="${STUB_DIR}:/usr/bin:/bin" run "$SCRIPT" --move me@home.example [[ ${output} == *"needs herdr"* ]] } + +# The machine this was found on: a home named for one account that the browser +# signed in as another, a second retry of it, the account itself on a third +# retry, and a fourth whose sign-in was left unfinished. +four_retries() { + account "${HOME}/.claude" me@home.example claude_max Personal + linked_home "${HOME}/.claude-me@work.example" me@home.example claude_max Personal + touch "${HOME}/.claude-me@work.example/.signed-out" + linked_home "${HOME}/.claude-me@work.example-2" me@home.example claude_max Personal + linked_home "${HOME}/.claude-me@work.example-3" me@work.example claude_team Acme + echo '{"token": "work"}' >"${HOME}/.claude-me@work.example-3/.credentials.json" + mkdir -p "${HOME}/.claude-me@work.example-4" + echo '{"hasCompletedOnboarding": true}' >"${HOME}/.claude-me@work.example-4/.claude.json" +} + +@test "--tidy turns four retries into one home per account, each named after it" { + four_retries + echo 'kept prompt' >"${HOME}/.claude-me@work.example-2/history.jsonl" + run "$SCRIPT" --tidy + [ "$status" -eq 0 ] + [[ ${output} == *"archived ~/.claude-me@work.example -> "*"(not signed in)"* ]] + [[ ${output} == *"archived ~/.claude-me@work.example-2 -> "*"(the same account and organization as ~/.claude)"* ]] + [[ ${output} == *"archived ~/.claude-me@work.example-4 -> "*"(not signed in)"* ]] + [[ ${output} == *"renamed ~/.claude-me@work.example-3 -> ~/.claude-me@work.example"* ]] + run "$SCRIPT" + [ "$(grep -c '@' <<<"${output}")" -eq 2 ] + [[ ${output} == *"me@home.example"*"~/.claude"$'\n'* ]] + [[ ${output} == *"me@work.example"*"~/.claude-me@work.example" || ${output} == *"me@work.example"*"~/.claude-me@work.example"$'\n'* ]] + [ "$(cat "${HOME}/.claude-me@work.example/.credentials.json")" = '{"token": "work"}' ] + run "$SCRIPT" me@work.example -p hi + [[ ${output} == *"home=${HOME}/.claude-me@work.example args="* ]] +} + +@test "--tidy archives keep the history and drop the credentials" { + four_retries + echo 'kept prompt' >"${HOME}/.claude-me@work.example-2/history.jsonl" + echo '{"token": "dup"}' >"${HOME}/.claude-me@work.example-2/.credentials.json" + run "$SCRIPT" --tidy + local archived + archived=$(compgen -G "${XDG_STATE_HOME}/claude-as/removed/.claude-me@work.example-2-*") + [ "$(cat "${archived}/history.jsonl")" = 'kept prompt' ] + [ ! -e "${archived}/.credentials.json" ] + [ "$(file_mode "${XDG_STATE_HOME}/claude-as/removed")" = 700 ] + # Its links point into the shared home and still do: nothing shared was moved. + [ "$(readlink "${archived}/projects")" = "${HOME}/.claude/projects" ] + [ -d "${HOME}/.claude/projects" ] +} + +@test "--tidy --dry-run changes nothing and shows the whole plan" { + four_retries + run "$SCRIPT" --tidy --dry-run + [ "$status" -eq 0 ] + [[ ${output} == *"would archive ~/.claude-me@work.example (not signed in)"* ]] + [[ ${output} == *"would archive ~/.claude-me@work.example-2 (the same account and organization as ~/.claude)"* ]] + [[ ${output} == *"would archive ~/.claude-me@work.example-4 (not signed in)"* ]] + # The name an archive would free counts as free. + [[ ${output} == *"would rename ~/.claude-me@work.example-3 -> ~/.claude-me@work.example"* ]] + [ -d "${HOME}/.claude-me@work.example-4" ] && [ -d "${HOME}/.claude-me@work.example-3" ] + [ ! -e "${XDG_STATE_HOME}/claude-as/removed" ] +} + +@test "--tidy a second time has nothing to do" { + four_retries + run "$SCRIPT" --tidy + run "$SCRIPT" --tidy + [ "$status" -eq 0 ] + [ "$output" = "nothing to tidy: one home per account, each named after it" ] +} + +@test "--tidy never touches the shared home, signed in or not" { + account "${HOME}/.claude" me@home.example + touch "${HOME}/.claude/.signed-out" + linked_home "${HOME}/.claude-me@work.example" me@work.example claude_team Acme + run "$SCRIPT" --tidy + [ "$status" -eq 0 ] + [ -f "${HOME}/.claude.json" ] && [ -d "${HOME}/.claude" ] + [[ ${output} == "nothing to tidy"* ]] +} + +@test "--tidy keeps a name the user chose" { + account "${HOME}/.claude" me@home.example + linked_home "${HOME}/.claude-work" me@work.example claude_team Acme + run "$SCRIPT" --tidy + [ "$status" -eq 0 ] + [ -f "${HOME}/.claude-work/.claude.json" ] + [[ ${output} == "nothing to tidy"* ]] +} + +@test "--tidy renames a home named after another email to its own" { + account "${HOME}/.claude" me@home.example + linked_home "${HOME}/.claude-someone@else.example" me@work.example claude_team Acme + run "$SCRIPT" --tidy + [ "$status" -eq 0 ] + [ -f "${HOME}/.claude-me@work.example/.claude.json" ] + [ ! -e "${HOME}/.claude-someone@else.example" ] +} + +@test "--tidy names a second organization of one email after the organization" { + account "${HOME}/.claude" me@home.example + linked_home "${HOME}/.claude-me@work.example" me@work.example claude_team Acme + linked_home "${HOME}/.claude-me@work.example-2" me@work.example claude_pro "Side Gig" + run "$SCRIPT" --tidy + [ "$status" -eq 0 ] + [ -f "${HOME}/.claude-me@work.example/.claude.json" ] + [ -f "${HOME}/.claude-me@work.example-side-gig/.claude.json" ] + run "$SCRIPT" --tidy + [[ ${output} == "nothing to tidy"* ]] +} + +@test "--tidy leaves alone a home a running session uses, when it would archive it" { + four_retries + STUB_LIVE="${HOME}/.claude-me@work.example-4" run "$SCRIPT" --tidy + [ "$status" -eq 0 ] + [[ ${output} == *"left alone ~/.claude-me@work.example-4: not signed in, but claude (101) still holds it; run --tidy once it ends"* ]] + [ -d "${HOME}/.claude-me@work.example-4" ] +} + +@test "--tidy renames a home in use and leaves a link the running sessions follow" { + four_retries + local old="${HOME}/.claude-me@work.example-3" new="${HOME}/.claude-me@work.example" + mkdir -p "${XDG_STATE_HOME}/claude-as" + printf 'aaaaaaaa-0000-4000-8000-000000000001\t%s\t1\n' "${old}" >"${XDG_STATE_HOME}/claude-as/sessions" + STUB_LIVE="${old}" run "$SCRIPT" --tidy + [ "$status" -eq 0 ] + [[ ${output} == *"renamed ~/.claude-me@work.example-3 -> ~/.claude-me@work.example (running sessions use it through a link)"* ]] + [ "$(readlink "${old}")" = "${new}" ] + [ "$(cat "${old}/.credentials.json")" = '{"token": "work"}' ] + grep -qx "aaaaaaaa-0000-4000-8000-000000000001 ${new} 1" "${XDG_STATE_HOME}/claude-as/sessions" + # A link is not a home: the list shows the account once. + run "$SCRIPT" + [ "$(grep -c 'me@work.example' <<<"${output}")" -eq 1 ] +} + +@test "a later --tidy drops the link once no session uses it" { + four_retries + local old="${HOME}/.claude-me@work.example-3" + STUB_LIVE="${old}" run "$SCRIPT" --tidy + STUB_LIVE="${old}" run "$SCRIPT" --tidy + [ -L "${old}" ] + run "$SCRIPT" --tidy + [ "$status" -eq 0 ] + [[ ${output} == *"dropped ~/.claude-me@work.example-3: a link no running session uses"* ]] + [ ! -e "${old}" ] && [ ! -L "${old}" ] + [ -d "${HOME}/.claude-me@work.example" ] +} + +@test "--tidy leaves a link it did not make alone" { + account "${HOME}/.claude" me@home.example + mkdir -p "${HOME}/elsewhere" + ln -s "${HOME}/elsewhere" "${HOME}/.claude-tool" + run "$SCRIPT" --tidy + [ -L "${HOME}/.claude-tool" ] +} + +@test "--tidy undoes a rename the login does not survive" { + account "${HOME}/.claude" me@home.example + linked_home "${HOME}/.claude-me@work.example-3" me@work.example claude_team Acme + stub_bin claude <<'EOF' +home=${CLAUDE_CONFIG_DIR:-$HOME/.claude} +if [[ $1 == auth && $2 == status ]]; then + [[ $home == *-3 ]] && echo '{"loggedIn": true}' || echo '{"loggedIn": false}' + exit 0 +fi +EOF + run "$SCRIPT" --tidy + [ "$status" -eq 0 ] + [[ ${output} == *"left alone ~/.claude-me@work.example-3: its login did not survive the move to ~/.claude-me@work.example"* ]] + [ -f "${HOME}/.claude-me@work.example-3/.claude.json" ] + [ ! -e "${HOME}/.claude-me@work.example" ] +} + +@test "--tidy on macOS carries the Keychain login and deletes an archived one" { + four_retries + stub_security + local old="${HOME}/.claude-me@work.example-3" new="${HOME}/.claude-me@work.example" + mkdir -p "${HOME}/keychain" + printf 'work-secret' >"${HOME}/keychain/$(service_of "${old}")" + printf 'dup-secret' >"${HOME}/keychain/$(service_of "${HOME}/.claude-me@work.example-2")" + run "$SCRIPT" --tidy + [ "$status" -eq 0 ] + [ "$(cat "${HOME}/keychain/$(service_of "${new}")")" = work-secret ] + [ ! -e "${HOME}/keychain/$(service_of "${old}")" ] + [ ! -e "${HOME}/keychain/$(service_of "${HOME}/.claude-me@work.example-2")" ] + ! grep -q secret "${HOME}/security.argv" +} + +@test "--tidy with the Keychain locked says so and still moves a file login" { + four_retries + stub_security + mkdir -p "${HOME}/keychain" + printf 'work-secret' >"${HOME}/keychain/$(service_of "${HOME}/.claude-me@work.example-3")" + STUB_KEYCHAIN_LOCKED=1 run "$SCRIPT" --tidy + [ "$status" -eq 0 ] + [[ ${output} == *"the Keychain is locked; ~/.claude-me@work.example-3 keeps its Keychain login"* ]] + [ "$(cat "${HOME}/.claude-me@work.example/.credentials.json")" = '{"token": "work"}' ] +} + +@test "--tidy refuses an option it does not know" { + account "${HOME}/.claude" me@home.example + run "$SCRIPT" --tidy --yes + [ "$status" -eq 2 ] + [[ ${output} == *"usage: claude-as --tidy [--dry-run]"* ]] +} + +@test "--check names a misnamed and a duplicate home, and the command that fixes them" { + four_retries + run "$SCRIPT" --check + [ "$status" -eq 1 ] + [[ ${output} == *"FAIL the same account and organization as another home: claude-as --tidy archives it"* ]] + [[ ${output} == *"FAIL not named after me@work.example: claude-as --tidy renames it to"* ]] + [[ ${output} == *"FAIL not signed in: claude-as --add signs one in, claude-as --tidy archives it"* ]] +} + +@test "--check passes once --tidy ran" { + four_retries + local h name + for h in "${HOME}"/.claude-*; do + for name in hooks skills settings.json projects; do + [[ -e ${h}/${name} ]] || ln -s "${HOME}/.claude/${name}" "${h}/${name}" + done + done + run "$SCRIPT" --tidy + run "$SCRIPT" --check + [ "$status" -eq 0 ] +} + +@test "a session that ran in a renamed home resumes in its new place" { + four_retries + local id=aaaaaaaa-0000-4000-8000-000000000002 old="${HOME}/.claude-me@work.example-3" + mkdir -p "${XDG_STATE_HOME}/claude-as" "${HOME}/.claude/projects/-x" + echo '{}' >"${HOME}/.claude/projects/-x/${id}.jsonl" + printf '%s\t%s\t1\n' "${id}" "${old}" >"${XDG_STATE_HOME}/claude-as/sessions" + STUB_LIVE="${old}" run "$SCRIPT" --tidy + # The running session's hook writes the old path again; it still resolves. + printf '%s\t%s\t2\n' "${id}" "${old}" >>"${XDG_STATE_HOME}/claude-as/sessions" + run "$SCRIPT" -r "${id}" + [ "$status" -eq 0 ] + [[ ${output} == *"home=${HOME}/.claude-me@work.example args="* ]] + run "$SCRIPT" --where -r "${id}" + [ "$output" = "${HOME}/.claude-me@work.example" ] +} + +@test "--tidy leaves a home in use alone when its login is in the Keychain" { + four_retries + stub_security + local old="${HOME}/.claude-me@work.example-3" + mkdir -p "${HOME}/keychain" + printf 'work-secret' >"${HOME}/keychain/$(service_of "${old}")" + STUB_LIVE="${old}" run "$SCRIPT" --tidy + [ "$status" -eq 0 ] + [[ ${output} == *"left alone ~/.claude-me@work.example-3: should be ~/.claude-me@work.example, but claude (101) holds its Keychain login; run --tidy once it ends"* ]] + [ -d "${old}" ] && [ ! -L "${old}" ] + [ "$(cat "${HOME}/keychain/$(service_of "${old}")")" = work-secret ] + # Once it ends, the next --tidy renames it and carries the login. + run "$SCRIPT" --tidy + [ "$(cat "${HOME}/keychain/$(service_of "${HOME}/.claude-me@work.example")")" = work-secret ] +} + +@test "dropping a link moves session records written through it to the new home" { + four_retries + local id=aaaaaaaa-0000-4000-8000-000000000003 old="${HOME}/.claude-me@work.example-3" + STUB_LIVE="${old}" run "$SCRIPT" --tidy + mkdir -p "${XDG_STATE_HOME}/claude-as" + printf '%s\t%s\t5\n' "${id}" "${old}" >>"${XDG_STATE_HOME}/claude-as/sessions" + run "$SCRIPT" --tidy + [ ! -L "${old}" ] + grep -qx "${id} ${HOME}/.claude-me@work.example 5" "${XDG_STATE_HOME}/claude-as/sessions" +} + +@test "an archived duplicate's sessions resume in the home of the same account that stays" { + four_retries + local id=aaaaaaaa-0000-4000-8000-000000000004 + mkdir -p "${XDG_STATE_HOME}/claude-as" + printf '%s\t%s\t1\n' "${id}" "${HOME}/.claude-me@work.example-2" >"${XDG_STATE_HOME}/claude-as/sessions" + run "$SCRIPT" --tidy + grep -qx "${id} ${HOME}/.claude 1" "${XDG_STATE_HOME}/claude-as/sessions" +} + +@test "--add with every name taken says so instead of moving to nowhere" { + account "${HOME}/.claude" me@work.example + mkdir -p "${HOME}/.claude-b@x.example" "${HOME}/.claude-b@x.example-org" "${HOME}/.claude-b@x.example-org-id" + run "$SCRIPT" --add b@x.example + [ "$status" -eq 1 ] + [[ ${output} == *"no free name for b@x.example"* ]] + [ -z "$(compgen -G "${XDG_STATE_HOME}/claude-as/adding.*" || true)" ] +} + +@test "a login named with its organization takes the plain name once it is free" { + account "${HOME}/.claude" me@home.example + linked_home "${HOME}/.claude-b@x.example" someone@else.example + touch "${HOME}/.claude-b@x.example/.signed-out" + run "$SCRIPT" --add b@x.example + [ -f "${HOME}/.claude-b@x.example-org/.claude.json" ] + run "$SCRIPT" --tidy + [ "$status" -eq 0 ] + [[ ${output} == *"renamed ~/.claude-b@x.example-org -> ~/.claude-b@x.example"* ]] + jq -e '.oauthAccount.emailAddress == "b@x.example"' "${HOME}/.claude-b@x.example/.claude.json" +} + +@test "two organizations of one email without org ids are not duplicates" { + account "${HOME}/.claude" me@home.example + linked_home "${HOME}/.claude-a@x.example" a@x.example + linked_home "${HOME}/.claude-a@x.example-2" a@x.example + local h + for h in "${HOME}/.claude-a@x.example" "${HOME}/.claude-a@x.example-2"; do + jq '.oauthAccount.organizationUuid = ""' "${h}/.claude.json" >"${h}/j" && mv "${h}/j" "${h}/.claude.json" + done + run "$SCRIPT" --tidy + [ "$status" -eq 0 ] + [[ ${output} != *archived* ]] + [ -f "${HOME}/.claude-a@x.example/.claude.json" ] + run "$SCRIPT" + [ "$(grep -c 'a@x.example' <<<"${output}")" -eq 2 ] +} + +@test "--tidy with only held homes left does not claim there is nothing to do" { + four_retries + local two="${HOME}/.claude-me@work.example-2" + STUB_LIVE="${two}:${two}:${two}" run "$SCRIPT" --tidy + STUB_LIVE="${two}:${two}:${two}" run "$SCRIPT" --tidy + [ "$status" -eq 0 ] + [[ ${output} == *"but claude (101), claude (102) and 1 more still holds it"* ]] + [[ ${output} != *"nothing to tidy"* ]] +}