summaryrefslogtreecommitdiffstats
path: root/pkgs/claude-remote.nix
diff options
context:
space:
mode:
Diffstat (limited to 'pkgs/claude-remote.nix')
-rw-r--r--pkgs/claude-remote.nix278
1 files changed, 273 insertions, 5 deletions
diff --git a/pkgs/claude-remote.nix b/pkgs/claude-remote.nix
index 10f94f4..7f62b5b 100644
--- a/pkgs/claude-remote.nix
+++ b/pkgs/claude-remote.nix
@@ -1,15 +1,33 @@
# claude-remote, root's tool for the remotes (claude-remote-control@NAME,
# see configs/claude.nix): list, inspect, start, stop, restart, attach,
-# log; with bash completion.
+# log, rename; with bash completion.
+#
+# Renaming a remote, OLD to NEW:
+# 1. claude-remote rename OLD NEW, as root, from anywhere but OLD itself.
+# It checks first (OLD there and not static, nothing of NEW's there,
+# nothing but OLD's own unit using OLD), stops OLD if it runs (asking,
+# or with --stop), moves its directory, its Claude Code project (with
+# the link to its claude.ai session), its trust, its worktrees and its
+# branches (OLD/* to NEW/*), and starts NEW if OLD ran. A static
+# remote, take out of the configuration first, and deploy.
+# 2. Check NEW: claude-remote inspect NEW, and claude.ai, where its
+# sessions go on (named OLD-..., until new ones). Update what
+# mentions OLD (it says where): ~claude/CLAUDE.md, NEW's own CLAUDE.md,
+# and a static one, the configuration.
+# 3. If something's wrong: claude-remote rename NEW OLD.
+# A rename is all or nothing: if a step fails, it takes back the ones
+# done, and ends where it began. Only if that fails, too, it keeps a
+# copy of ~claude/.claude.json, as it was, which claude-remote list
+# shows, until it's removed.
{ lib, runCommand, writeShellScript, writeText
-, coreutils, findutils, gnugrep, gnused, jq, systemd, tmux
+, coreutils, findutils, gitMinimal, gnugrep, gnused, jq, systemd, tmux, util-linux
# Where remotes started with systemctl are kept, see configs/claude.nix.
, stateDir
}:
let
script = writeShellScript "claude-remote" ''
set -eu
- export PATH=${lib.makeBinPath [ coreutils findutils gnugrep gnused jq systemd tmux ]}
+ export PATH=${lib.makeBinPath [ coreutils findutils gitMinimal gnugrep gnused jq systemd tmux util-linux ]}
# The static remotes: those multi-user.target wants, as the running
# system has it (so changing them doesn't change this script).
static=($(systemctl show --value -p Wants multi-user.target 2>/dev/null |
@@ -27,9 +45,16 @@ let
claude-remote restart NAME
claude-remote attach [NAME] its terminal (tmux; default: main)
claude-remote log NAME [JOURNALCTL-OPTION...]
+ claude-remote rename OLD NEW [--stop]
A remote is claude-remote-control@NAME, working in ~claude/remotes/NAME.
Static ones are started by the system's configuration; others, started
here, are dynamic: they last, across reboots, until stopped here.
+ rename: checks first, and changes nothing unless all's well; stops OLD
+ if it runs (asking first, or with --stop); moves its directory, Claude
+ Code project, trust, worktrees and branches (OLD/* to NEW/*); starts
+ NEW if OLD ran. All or nothing: if a step fails, it takes back those
+ done. rename NEW OLD takes it back. Not for static ones: take them
+ out of the system's configuration first.
EOF
}
die() {
@@ -81,6 +106,229 @@ let
fi
}
+ # Renaming: every step a rename of its own (directory, project,
+ # trust, branches, mark), so that rename NEW OLD takes it all back; and
+ # all or nothing: each step, once done, leaves how to take it back,
+ # and if one fails, those get done, last first.
+ as_claude() {
+ runuser -u claude -- env HOME="$home" "$@"
+ }
+ # The repositories, in ~claude/src (third parties', by their links).
+ repos() {
+ local r
+ for r in "$home"/src/*/; do
+ r=''${r%/}
+ if test -e "$r/.git"; then printf '%s\n' "$r"; fi
+ done
+ }
+ # Processes using PATH... (cwd, root, open files), but a remote's own
+ # (by its unit's cgroup), as "PID COMMAND: FILE".
+ users_of() {
+ local own=$1 a pid l
+ shift
+ local tests=()
+ for a; do tests+=(-o -lname "$a" -o -lname "$a/*"); done
+ find /proc/[0-9]*/cwd /proc/[0-9]*/root /proc/[0-9]*/fd -maxdepth 1 \
+ \( -false "''${tests[@]}" \) -printf '%p %l\n' 2>/dev/null |
+ while read -r pid l; do
+ pid=''${pid#/proc/} pid=''${pid%%/*}
+ if test -n "$own" && grep -qs "/$(unit "$own")" "/proc/$pid/cgroup"; then continue; fi
+ echo "$pid $(tr '\0' ' ' < "/proc/$pid/cmdline" 2>/dev/null | cut -c1-50): $l"
+ done | sort -u
+ }
+ # A JSON file of claude's through jq ARG..., atomically, as claude.
+ jq_in_place() {
+ as_claude "$BASH" -c 'f=$1; shift; jq "$@" "$f" > "$f.rename" && mv "$f.rename" "$f" || { rm -f "$f.rename"; exit 1; }' \
+ jq-in-place "$@"
+ }
+ # The trust (and the rest of the project's entry in ~/.claude.json) of
+ # remote FROM, for remote TO, replacing any TO had.
+ move_trust() {
+ jq_in_place "$home/.claude.json" --arg o "$remotes/$1" --arg n "$remotes/$2" \
+ 'if .projects | has($o) then .projects[$n] = .projects[$o] | del(.projects[$o]) else . end'
+ }
+ # The link to the claude.ai session, in remote NAME's project, for
+ # the directory DIR.
+ point() {
+ local p
+ p=$(project "$1")/bridge-pointer.json
+ if test -f "$p"; then jq_in_place "$p" -c --arg d "$2" '.dir = $d'; fi
+ }
+ # The worktrees "REPO WORKTREE" on stdin, in remote FROM's directory,
+ # repaired, now that it's TO's (but for git's "repair: gitdir
+ # incorrect", what it says goes to stderr, errors included).
+ repair_worktrees() {
+ local r w
+ while read -r r w; do
+ test -n "$r" || continue
+ as_claude git -C "$r" worktree repair "$remotes/$2''${w#"$remotes/$1"}" \
+ 2> >(grep -v '^repair: ' >&2)
+ done
+ }
+ # Undos, for a step that may have gone through, or half, or not:
+ # The directory of remote FROM back, as TO's, if it's FROM's, with the
+ # worktrees in it that were repaired already (those recorded in
+ # FROM's).
+ move_dir_back() {
+ test -e "$remotes/$1" && ! test -e "$remotes/$2" || return 0
+ local wts
+ wts=$(worktrees_below "$remotes/$1")
+ as_claude mv "$remotes/$1" "$remotes/$2"
+ repair_worktrees "$1" "$2" <<< "$wts"
+ }
+ # FROM back to TO, if FROM's there and TO isn't; as claude, with a
+ # third argument, as_claude.
+ move_back() {
+ if test -e "$1" && ! test -e "$2"; then ''${3-} mv "$1" "$2"; fi
+ }
+ # In REPO, the branch FROM back to TO, if there's FROM, and no TO
+ # (as git branch -m can rename it, and still fail, e.g. at a
+ # worktree's HEAD, which renaming it back sets right again).
+ branch_back() {
+ if as_claude git -C "$1" rev-parse -q --verify "refs/heads/$2" >/dev/null &&
+ ! as_claude git -C "$1" rev-parse -q --verify "refs/heads/$3" >/dev/null; then
+ as_claude git -C "$1" branch -m "$2" "$3"
+ fi
+ }
+ # the worktrees the repositories record below DIR, as "REPO WORKTREE"
+ worktrees_below() {
+ local r g w
+ repos | while read -r r; do
+ for g in "$r"/.git/worktrees/*/gitdir; do
+ test -f "$g" || continue
+ w=$(cat "$g") w=''${w%/.git}
+ case $w in "$1"/*) echo "$r $w" ;; esac
+ done
+ done
+ }
+ # After a step: how to take it back (a command line).
+ undoable() {
+ undos+=("$(printf '%q ' "$@")")
+ }
+ # The steps done, taken back, last first, if the rename didn't finish.
+ take_back() {
+ test -z "$finished" || return 0
+ set +e
+ local i failed=
+ echo "claude-remote: rename $old $new failed; taking back what's done" >&2
+ for ((i = ''${#undos[@]} - 1; i >= 0; i--)); do
+ eval "''${undos[i]}" || { failed=1; echo "claude-remote: couldn't take back: ''${undos[i]}" >&2; }
+ done
+ if test -n "$failed"; then
+ echo "claude-remote: not all taken back (see above); ~claude/.claude.json as it was: $backup (claude-remote list shows it, until it's removed)" >&2
+ else
+ rm -f "$backup"
+ echo "claude-remote: all taken back: $old is as it was" >&2
+ fi
+ }
+ do_rename() {
+ # (global, for take_back, which runs on exit)
+ old=$1 new=$2 undos=() finished= backup=
+ local stop=$3 errs=() r n w b sha users active= wts brs
+ test "$(id -u)" = 0 || die "rename: as root"
+ valid "$old" || die "not a remote's name: $old"
+ valid "$new" || die "not a remote's name: $new"
+ test "$old" != "$new" || die "rename: $old is $new already"
+ # Everything first, nothing changed unless all's well.
+ test -d "$remotes/$old" || errs+=("there's no remote $old ($remotes/$old)")
+ if is_static "$old"; then
+ errs+=("$old is static: take it out of the system's configuration first, and deploy")
+ fi
+ if test -e "$remotes/$new"; then errs+=("$remotes/$new is there already"); fi
+ if test -e "$(project "$new")"; then errs+=("$(project "$new") is there already"); fi
+ # (but not an entry in ~/.claude.json alone: a remote writing back
+ # what it read before can bring one back)
+ if is_static "$new"; then errs+=("$new is static (the system's configuration)"); fi
+ if test -e "$state/$new"; then errs+=("$state/$new is there already"); fi
+ case $(active "$new") in inactive | failed | "") ;; *) errs+=("$(unit "$new") is $(active "$new")") ;; esac
+ while read -r r; do
+ n=$(as_claude git -C "$r" for-each-ref --format=x "refs/heads/$new/" | wc -l)
+ test "$n" = 0 || errs+=("$r has $n branches $new/* already")
+ done < <(repos)
+ if grep -qs "/$(unit "$old")" /proc/self/cgroup; then
+ errs+=("this runs in $old: rename it from elsewhere (a root shell, another remote)")
+ fi
+ users=$(users_of "$old" "$remotes/$old" "$(project "$old")")
+ if test -n "$users"; then
+ errs+=("in use, by more than $old itself: $(printf '\n %s' "$users")")
+ fi
+ exec 9> /run/claude-remote-rename.lock
+ flock -n 9 || errs+=("another rename is running")
+ if test ''${#errs[@]} -gt 0; then
+ printf 'claude-remote: rename %s %s: no:\n' "$old" "$new" >&2
+ printf -- '- %s\n' "''${errs[@]}" >&2
+ exit 1
+ fi
+ case $(active "$old") in
+ inactive | failed | "") ;;
+ *)
+ active=1
+ if test -z "$stop"; then
+ test -t 0 || die "rename: $old is running: stop it first, or --stop"
+ read -r -p "$old is running: stop it (which ends its sessions)? [y/N] " n
+ case $n in y | Y | yes) ;; *) die "rename: not stopping $old" ;; esac
+ fi
+ esac
+
+ wts=$(worktrees_below "$remotes/$old")
+ brs=$(repos | while read -r r; do
+ as_claude git -C "$r" for-each-ref --format="$r %(refname:short)" "refs/heads/$old/"
+ done)
+ backup=$(mktemp "''${state%/*}"/rename-backup.XXXXXX.claude.json)
+ cp -a "$home/.claude.json" "$backup"
+ trap take_back EXIT
+
+ # Each step's undo first, which looks at what's there, so that it
+ # takes back a step that went through, or half of one, and leaves
+ # alone what didn't happen.
+ if test -n "$active"; then
+ undoable systemctl start "$(unit "$old")"
+ systemctl stop "$(unit "$old")"
+ users=$(users_of "" "$remotes/$old" "$(project "$old")")
+ test -z "$users" || die "rename: $old still in use, once stopped:$(printf '\n %s' "$users")"
+ fi
+ # a dynamic remote's mark, if a stop didn't end well (else, at the
+ # next boot, OLD would start again, anew)
+ if test -e "$state/$old"; then
+ undoable move_back "$state/$new" "$state/$old"
+ mv "$state/$old" "$state/$new"
+ fi
+ if test -e "$(project "$old")"; then
+ undoable move_back "$(project "$new")" "$(project "$old")" as_claude
+ as_claude mv "$(project "$old")" "$(project "$new")"
+ fi
+ undoable move_dir_back "$new" "$old"
+ as_claude mv "$remotes/$old" "$remotes/$new"
+ repair_worktrees "$old" "$new" <<< "$wts"
+ while read -r r b; do
+ test -n "$r" || continue
+ undoable branch_back "$r" "$new/''${b#"$old"/}" "$b"
+ as_claude git -C "$r" branch -m "$b" "$new/''${b#"$old"/}"
+ done <<< "$brs"
+ undoable move_trust "$new" "$old"
+ move_trust "$old" "$new"
+ undoable point "$new" "$remotes/$old"
+ point "$new" "$remotes/$new"
+ if test -n "$active"; then
+ # the trust again, in case a remote wrote .claude.json since, from
+ # what it had read before
+ move_trust "$old" "$new"
+ undoable systemctl stop "$(unit "$new")"
+ systemctl start "$(unit "$new")"
+ fi
+ finished=1
+ rm -f "$backup"
+
+ echo "renamed $old to $new: $(grep -c . <<< "$wts") worktrees, $(grep -c . <<< "$brs") branches$(test -z "$active" || echo ", and started it")."
+ local mentions
+ mentions=$(grep -lw -- "$old" "$home"/CLAUDE.md "$remotes/$new"/CLAUDE.md 2>/dev/null || :)
+ if test -n "$mentions"; then
+ echo "These mention $old still:"
+ printf ' %s\n' $mentions
+ fi
+ echo "Check $new: claude-remote inspect $new, and claude.ai. To take it back: claude-remote rename $new $old"
+ }
+
cmd=''${1-list}
shift || :
case $cmd in
@@ -89,6 +337,24 @@ let
names | while read -r n; do
printf '%-20s %-8s %-12s %s\n' "$n" "$(kind "$n")" "$(active "$n")" "$(trusted "$n" && echo yes || echo no)"
done
+ # not to be forgotten: copies of ~claude/.claude.json, kept by a
+ # rename that couldn't take back all it had done
+ for n in "''${state%/*}"/rename-backup.*; do
+ if test -e "$n"; then echo "(kept by a rename that failed: $n)"; fi
+ done
+ ;;
+ rename)
+ stop=
+ args=()
+ for a; do
+ case $a in
+ --stop) stop=1 ;;
+ -*) usage >&2; exit 1 ;;
+ *) args+=("$a")
+ esac
+ done
+ test ''${#args[@]} = 2 || { usage >&2; exit 1; }
+ do_rename "''${args[0]}" "''${args[1]}" "$stop"
;;
inspect)
name_arg "''${1-}"
@@ -147,12 +413,14 @@ let
_claude_remote() {
local cur=''${COMP_WORDS[COMP_CWORD]}
if [ "$COMP_CWORD" -eq 1 ]; then
- COMPREPLY=($(compgen -W "list inspect start stop restart attach log help" -- "$cur"))
+ COMPREPLY=($(compgen -W "list inspect start stop restart attach log rename help" -- "$cur"))
elif [ "$COMP_CWORD" -eq 2 ]; then
case ''${COMP_WORDS[1]} in
- inspect | start | stop | restart | attach | log)
+ inspect | start | stop | restart | attach | log | rename)
COMPREPLY=($(compgen -W "$(claude-remote names 2>/dev/null)" -- "$cur")) ;;
esac
+ elif [ "''${COMP_WORDS[1]}" = rename ]; then
+ COMPREPLY=($(compgen -W "--stop" -- "$cur"))
fi
}
complete -F _claude_remote claude-remote