#!/usr/bin/env bash
# air-worktree — Air's worktree tool for coding agents.
#
# Every coding task runs in its own git worktree, created and registered by
# this tool so the Air Sessions panel can show the worktree (files changed,
# commits, push/PR state) with the conversations working in it nested under.
#
#   air-worktree create --name <feature-slug> --goal "<sentence>" [--base <ref>] [--repo <path>] [--branch <existing>] [--json]
#       Create a new worktree on a fresh branch. NAME IT AFTER THE FEATURE /
#       TASK being worked on (e.g. `login-rate-limit`); free text is slugified
#       and de-duplicated. Without --name a random adjective-noun is used.
#       --goal states, in one sentence, what the worktree group is for; the
#       group's page shows it under the name until its review states one.
#       --branch checks out an EXISTING branch (local, else a fetched
#       <remote>/<branch>, tracked) instead of cutting air/<name> — how
#       `gnosis worktree-group open` recreates a teammate's worktree.
#   air-worktree join <name> --goal "<sentence>" [--repo <path>] [--json]
#       Attach this session to an existing worktree; prints its path + branch.
#       Without --repo the name is looked up in the cwd's repository, then in
#       every registry (join/path/status) — several matches need --repo.
#       --goal is recorded only when the worktree has none yet.
#   air-worktree goal <name> ["<sentence>"]
#       Print the worktree's goal, or set / replace it.
#   air-worktree adopt [<path>] [--name <name>] [--goal "<sentence>"] [--base <ref>] [--json]
#       Register a git worktree SOMETHING ELSE created (Cursor's /worktree or
#       `agent --worktree`, Claude Code's EnterWorktree, `git worktree add`) —
#       the one at <path>, else the cwd — so the Sessions panel shows it and
#       the group knowledge is keyed by its name. Creates nothing; the checkout
#       stays where its manager put it. Idempotent: an adopted path is re-emitted.
#   air-worktree rename <name> <new-name> [--keep-branch]
#       Rename a worktree (dir + registry + branch air/<new>, unless the branch
#       is already pushed or --keep-branch). Sessions stay linked.
#   air-worktree list [--json]
#   air-worktree status <name> [--json]
#   air-worktree path <name>
#   air-worktree remove <name>
#   air-worktree doctor [--repo <path>]
#       Check this machine's wiring (jq, HOME, hook scripts + registrations,
#       registry) and SELF-TEST the PostToolUse linker — start here when a
#       conversation does not show up under its worktree.
#
# Layout (shared with the Air VS Code plugin, which reads it read-only):
#   ${AIR_HOME:-~/.air}/worktrees/<repoKey>/
#     repo.json            { repoRoot }
#     trees/<name>/        the git worktree checkout (outside the repo, so
#                          indexers never see a second copy of the code)
#     meta/<name>.json     the worktree record (`groupModel: 2` = created under
#                          logical groups: its group is its creator session's,
#                          not its name's — see the Air plugin's groupModel.ts)
#     links/<name>/*.json  conversation ↔ worktree links (written by this tool
#                          from the PreToolUse handoff, and by the
#                          Air PostToolUse hook, keyed by session id)
# <repoKey> = <repo basename>-<first 12 hex of sha1(repo root path)>.
#
# Every `create` / `join` ends stdout with one machine-readable line:
#   AIR_WORKTREE_JSON {"name":…,"path":…,"branch":…,"repoKey":…,…}
# The Air hooks parse that line to link the session to the worktree.
# bash 3.2 compatible (macOS default shell); runs under Git Bash on Windows.
set -euo pipefail

# Windows: a bash spawned without HOME (a non-login Git Bash inherits only the
# Windows environment) would put the registry under /.air; USERPROFILE is the
# home Windows itself knows.
HOME="${HOME:-${USERPROFILE:-}}"
AIR_HOME="${AIR_HOME:-$HOME/.air}"
WT_HOME="$AIR_HOME/worktrees"

# Windows (Git for Windows / MSYS2 / Cygwin). Claude Code's Bash tool is Git
# Bash there, so this script runs — but paths come in two spellings: POSIX
# (/c/Users/…, what $HOME, $PWD and `pwd -P` give) and native (C:/Users/…, what
# git prints and what the plugin's Node side can open). Every path that LEAVES
# this script (registry records, the AIR_WORKTREE_JSON line) is written in the
# native form via cygpath -m, so one repo hashes to one repoKey however it was
# reached and the Sessions panel can read the checkout; bash accepts both forms,
# so nothing here converts back.
case "$(uname -s 2>/dev/null)" in MINGW*|MSYS*|CYGWIN*) IS_WIN=1 ;; *) IS_WIN=0 ;; esac
# A jq Air provisioned into $AIR_HOME/bin (machines without one — typically
# Windows) is found after whatever PATH already carries.
PATH="$PATH:$AIR_HOME/bin"

native_path() {
  if [[ "$IS_WIN" == "1" ]] && command -v cygpath >/dev/null 2>&1; then
    cygpath -m "$1" 2>/dev/null || printf '%s' "$1"
  else
    printf '%s' "$1"
  fi
}
# Absolute in either spelling: /posix, C:/native, C:\native, \\unc.
is_abs() { case "$1" in /*|[A-Za-z]:/*|[A-Za-z]:\\*|\\\\*) return 0 ;; *) return 1 ;; esac; }

die() { printf 'air-worktree: %s\n' "$*" >&2; exit 1; }

usage() {
  sed -n '2,40p' "$0" | sed 's/^# \{0,1\}//'
  exit "${1:-0}"
}

need_jq() {
  command -v jq >/dev/null 2>&1 && return 0
  die "jq is required (macOS: brew install jq · Debian/Ubuntu: apt install jq · Windows: winget install jqlang.jq — or reload the Air VS Code extension, which downloads a jq into $AIR_HOME/bin when PATH has none)"
}

sha1_12() {
  if command -v shasum >/dev/null 2>&1; then
    printf '%s' "$1" | shasum -a 1 | cut -c1-12
  elif command -v sha1sum >/dev/null 2>&1; then
    printf '%s' "$1" | sha1sum | cut -c1-12
  else
    die "need shasum or sha1sum on PATH"
  fi
}

# The MAIN repository root, even when invoked from inside a linked worktree
# (git-common-dir points back at the primary checkout's .git).
repo_root() {
  local start="${1:-$PWD}" common top
  common="$(git -C "$start" rev-parse --git-common-dir 2>/dev/null)" \
    || die "not inside a git repository (cd into the project or pass --repo <path>)"
  is_abs "$common" || common="$start/$common"
  common="$(cd "$common" && pwd -P)"
  top="$(git -C "$(dirname "$common")" rev-parse --show-toplevel 2>/dev/null)" \
    || die "could not resolve the main repository root from $common"
  native_path "$top"
}

repo_key() { printf '%s-%s' "$(basename "$1")" "$(sha1_12 "$1")"; }

now_iso() { date -u +%Y-%m-%dT%H:%M:%SZ; }

# Turn free text into a worktree name: lower-case, non-alphanumerics → "-",
# collapsed, trimmed, capped at 48 chars. Empty when nothing survives.
slugify() {
  printf '%s' "$1" | tr '[:upper:]' '[:lower:]' | sed -E 's/[^a-z0-9]+/-/g; s/^-+//; s/-+$//' | cut -c1-48 | sed -E 's/-+$//'
}

# Append -2, -3, … until the name is free (registry, checkout dir, branch).
unique_name() {
  local base="$1" meta_dir="$2" trees_dir="$3" n="$1" i=2
  while [[ -e "$meta_dir/$n.json" || -e "$trees_dir/$n" ]] || git -C "$ROOT" show-ref --verify --quiet "refs/heads/air/$n"; do
    n="$base-$i"; i=$((i + 1))
  done
  printf '%s' "$n"
}

ADJECTIVES=(amber brisk calm cedar coral dusky eager fabled gentle hazel ivory jade keen lunar mellow noble opal pale quartz rustic sage swift tidy umber vivid witty zesty bold quiet young)
NOUNS=(otter heron falcon lynx maple birch fjord delta ember harbor island juniper kestrel lagoon meadow nova orchid pebble quill ridge summit thistle valley willow yarrow zephyr cove grove pine reef)

# Autogenerated adjective-noun name, unique within the repo's registry.
gen_name() {
  local meta_dir="$1" trees_dir="$2" n i
  for i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20; do
    n="${ADJECTIVES[$((RANDOM % ${#ADJECTIVES[@]}))]}-${NOUNS[$((RANDOM % ${#NOUNS[@]}))]}"
    if [[ ! -e "$meta_dir/$n.json" && ! -e "$trees_dir/$n" ]] \
      && ! git -C "$ROOT" show-ref --verify --quiet "refs/heads/air/$n"; then
      printf '%s' "$n"
      return 0
    fi
  done
  # Pathological collision run — fall back to a numeric suffix.
  i=2
  while [[ -e "$meta_dir/$n-$i.json" || -e "$trees_dir/$n-$i" ]]; do i=$((i + 1)); done
  printf '%s-%s' "$n" "$i"
}

# Print a record: human summary (unless --json) + the AIR_WORKTREE_JSON line.
emit_record() {
  local meta="$1" verb="$2" json_only="$3" name path branch base goal
  name="$(jq -r .name "$meta")"
  path="$(jq -r .path "$meta")"
  branch="$(jq -r .branch "$meta")"
  base="$(jq -r '.baseRef + " @ " + (.baseSha | .[0:10])' "$meta")"
  goal="$(jq -r '.goal // empty' "$meta")"
  if [[ "$json_only" != "1" ]]; then
    printf 'Worktree %s: %s\n' "$verb" "$name"
    printf '  path:   %s\n' "$path"
    printf '  branch: %s\n' "$branch"
    printf '  base:   %s\n' "$base"
    if [[ -n "$goal" ]]; then
      printf '  goal:   %s\n' "$goal"
    else
      printf 'This worktree group has no goal yet. State what it is for in one sentence: %s goal %s "<goal>"\n' "$0" "$name"
    fi
    printf 'Do ALL work for this task inside that path: cd there for shell commands and use absolute paths under it for every file edit. The main checkout stays untouched.\n'
    printf 'Shared knowledge of this worktree group: every conversation working in %s (any repository) records its tasks and decisions into one knowledge base. Before settling something a peer may already have decided, read what the group already did with `gnosis knowledge worktree-tasks --name %s` (each task it ran with its decision headlines), open the full knowledge of every task that touches your change with the `cmd` on its row, and ask specific questions with `gnosis knowledge search "<question>" --worktree %s --mode hybrid`.\n' "$name" "$name" "$name"
  fi
  printf 'AIR_WORKTREE_JSON %s\n' "$(jq -c . "$meta")"
}

# Record the group's goal on a worktree record: whitespace collapsed to one
# line, capped at 300 chars. With keep=1 an existing goal wins (a joiner does not
# restate the goal of the group it joins).
set_goal() {
  local meta="$1" text="$2" keep="${3:-0}"
  text="$(printf '%s' "$text" | tr '\r\n\t' '   ' | sed -E 's/  +/ /g; s/^ //; s/ $//' | cut -c1-300)"
  [[ -n "$text" ]] || return 0
  if [[ "$keep" == "1" && -n "$(jq -r '.goal // empty' "$meta")" ]]; then return 0; fi
  jq --arg goal "$text" --arg at "$(now_iso)" '.goal = $goal | .goalAt = $at' "$meta" >"$meta.tmp" && mv "$meta.tmp" "$meta"
}

# ── session link handoff ─────────────────────────────────────────────────────
# This tool never learns the agent session id — only the hooks do. The
# PreToolUse hook (Bash matcher) therefore leaves a PENDING record for every
# `air-worktree create|join` command it sees, under
#   $AIR_HOME/pending-links/<key>/<session_id>.json   key = sha1_12(<raw name>)
# (the raw `--name` text / the join positional; "anonymous" for a nameless
# create), and the tool CLAIMS the freshest one (≤ PENDING_LINK_TTL_S old) and
# writes the conversation↔worktree link ITSELF. The AIR_WORKTREE_JSON line is
# then a confirmation, not the mechanism: 2026-10-10 two worktrees created
# through `… 2>&1 | head -5` lost that line to the pipe and showed "No
# conversation linked yet" — one of them ran a whole feature's change model
# conversation-less. Stale records are swept here; a wrong claim needs two
# sessions to create/join the SAME raw name within the TTL.
PENDING_LINK_TTL_S=300
# GNU stat first: on Linux `stat -f` means FILESYSTEM status and treats `%m` as a
# file name, printing a multi-line "File: …" block before it fails, which the
# arithmetic below then read as a variable name under `set -u`. BSD `stat -c` is
# an illegal option and prints nothing to stdout. Anything non-numeric reads as 0.
file_mtime() {
  local m
  m="$(stat -c %Y "$1" 2>/dev/null)" || m="$(stat -f %m "$1" 2>/dev/null)" || m=0
  [[ "$m" =~ ^[0-9]+$ ]] || m=0
  printf '%s' "$m"
}
pending_key() { if [[ -n "$1" ]]; then sha1_12 "$1"; else printf 'anonymous'; fi; }
claim_pending_link() {
  local raw="$1" name="$2" role="$3" dir f newest="" newest_m=0 m now sid t cwd link existing
  dir="$AIR_HOME/pending-links/$(pending_key "$raw")"
  [[ -d "$dir" ]] || return 0
  now="$(date -u +%s)"
  for f in "$dir"/*.json; do
    [[ -f "$f" ]] || continue
    m="$(file_mtime "$f")"
    if (( now - m > PENDING_LINK_TTL_S )); then rm -f "$f"; continue; fi
    if (( m >= newest_m )); then newest="$f"; newest_m="$m"; fi
  done
  if [[ -z "$newest" ]]; then rmdir "$dir" 2>/dev/null || true; return 0; fi
  sid="$(jq -r '.sessionId // empty' "$newest" 2>/dev/null || true)"
  t="$(jq -r '.transcriptPath // empty' "$newest" 2>/dev/null || true)"
  cwd="$(jq -r '.cwd // empty' "$newest" 2>/dev/null || true)"
  rm -f "$newest"; rmdir "$dir" 2>/dev/null || true
  [[ -n "$sid" ]] || return 0
  mkdir -p "$LINKS_DIR/$name"
  link="$LINKS_DIR/$name/$sid.json"
  # A session that joins its own creation stays "creator".
  existing="$(jq -r '.role // empty' "$link" 2>/dev/null || true)"
  [[ "$existing" == "creator" ]] && role=creator
  jq -n --arg sid "$sid" --arg t "$t" --arg role "$role" --arg cwd "$cwd" --arg at "$(now_iso)" \
    '{sessionId:$sid, transcriptPath:(if $t=="" then null else $t end), role:$role, cwd:(if $cwd=="" then null else $cwd end), at:$at, version:1, linkedBy:"air-worktree"}' \
    >"$link.tmp" 2>/dev/null && mv "$link.tmp" "$link"
}

# ── argument parsing ─────────────────────────────────────────────────────────
[[ $# -ge 1 ]] || usage 1
VERB="$1"; shift
JSON_ONLY=0
BASE_REF=""
REPO_ARG=""
NAME_ARG=""
BRANCH_ARG=""
GOAL_ARG=""
KEEP_BRANCH=0
POSITIONAL=()
while [[ $# -gt 0 ]]; do
  case "$1" in
    --json) JSON_ONLY=1 ;;
    --base) shift; [[ $# -gt 0 ]] || die "--base needs a ref"; BASE_REF="$1" ;;
    --base=*) BASE_REF="${1#--base=}" ;;
    --repo) shift; [[ $# -gt 0 ]] || die "--repo needs a path"; REPO_ARG="$1" ;;
    --repo=*) REPO_ARG="${1#--repo=}" ;;
    --name) shift; [[ $# -gt 0 ]] || die "--name needs a value"; NAME_ARG="$1" ;;
    --name=*) NAME_ARG="${1#--name=}" ;;
    --branch) shift; [[ $# -gt 0 ]] || die "--branch needs a branch name"; BRANCH_ARG="$1" ;;
    --branch=*) BRANCH_ARG="${1#--branch=}" ;;
    --goal) shift; [[ $# -gt 0 ]] || die "--goal needs a sentence"; GOAL_ARG="$1" ;;
    --goal=*) GOAL_ARG="${1#--goal=}" ;;
    --keep-branch) KEEP_BRANCH=1 ;;
    -h|--help) usage 0 ;;
    -*) die "unknown option: $1" ;;
    *) POSITIONAL+=("$1") ;;
  esac
  shift
done

case "$VERB" in
  -h|--help|help) usage 0 ;;
esac

# ── doctor ───────────────────────────────────────────────────────────────────
# Runs BEFORE need_jq (a missing jq is its first finding) and tolerates a cwd
# outside any repo (registry checks are then skipped).
DOCTOR_FAIL=0
d_ok()   { printf '  ok    %s\n' "$*"; }
d_bad()  { printf '  FAIL  %s\n' "$*"; DOCTOR_FAIL=1; }
d_info() { printf '  info  %s\n' "$*"; }
doctor() {
  local jq_bin="" scope s n found_hook="" f name links meta sid payload
  printf 'air-worktree doctor\n'
  d_info "platform: $(uname -s 2>/dev/null || echo unknown) (windows=$IS_WIN) · bash $BASH_VERSION"
  if jq_bin="$(command -v jq 2>/dev/null)"; then
    d_ok "jq: $jq_bin ($(jq --version 2>/dev/null || echo '?'))"
  else
    d_bad "jq: not on PATH nor in $AIR_HOME/bin — the tool refuses and every hook exits silently without it (Windows: winget install jqlang.jq, or reload the Air extension)"
  fi
  if [[ -n "${HOME:-}" ]]; then d_ok "HOME: $HOME"; else d_bad "HOME is unset and USERPROFILE is ${USERPROFILE:-unset} — hooks would write under /.air"; fi
  if [[ -d "$AIR_HOME" ]]; then d_ok "AIR_HOME: $AIR_HOME"; else d_bad "AIR_HOME: $AIR_HOME does not exist"; fi
  if [[ -f "$AIR_HOME/bin/air-worktree" ]]; then d_ok "tool: $AIR_HOME/bin/air-worktree"; else d_bad "tool missing at $AIR_HOME/bin/air-worktree — the PreToolUse gate fails open without it (reload the Air extension)"; fi
  n="$(ls "${TMPDIR:-/tmp}"/air-worktree-hook-*.json 2>/dev/null | wc -l | tr -d ' ' || true)"
  d_info "TMPDIR: ${TMPDIR:-/tmp} — $n session state file(s)"
  n="$(ls "$AIR_HOME/isolation"/*.json 2>/dev/null | wc -l | tr -d ' ' || true)"
  d_info "isolation scopes: $AIR_HOME/isolation — ${n:-0} session record(s) (worktree / branch / agent, written by the Air chat when a task starts)"
  # Hook scripts + settings registrations: user scope, plus the workspace's.
  for scope in "$HOME/.claude" ${ROOT:+"$ROOT/.claude"}; do
    [[ -d "$scope" ]] || continue
    for s in user-prompt-submit pre-tool-use post-tool-use; do
      if [[ -f "$scope/hooks/air-worktree-$s.sh" ]]; then
        d_ok "hook script: $scope/hooks/air-worktree-$s.sh"
        [[ "$s" == "post-tool-use" && -z "$found_hook" ]] && found_hook="$scope/hooks/air-worktree-$s.sh"
      fi
    done
    if [[ -f "$scope/settings.json" ]]; then
      n="$(grep -c 'air-worktree-' "$scope/settings.json" 2>/dev/null || true)"
      if [[ "${n:-0}" -gt 0 ]]; then d_ok "settings: $scope/settings.json registers $n air-worktree hook command(s)"; else d_info "settings: $scope/settings.json registers no air-worktree hooks"; fi
    fi
  done
  [[ -n "$found_hook" ]] || d_bad "PostToolUse linker not installed (no air-worktree-post-tool-use.sh under ~/.claude/hooks${ROOT:+ or $ROOT/.claude/hooks}) — reload the Air extension with air.worktrees.enabled on"
  if [[ -z "$ROOT" ]]; then
    d_info "not inside a git repository — registry checks skipped (pass --repo <path>)"
  else
    d_ok "repo: $ROOT (repoKey $KEY)"
    if [[ -d "$META_DIR" ]] && ls "$META_DIR"/*.json >/dev/null 2>&1; then
      for f in "$META_DIR"/*.json; do
        name="$(basename "$f" .json)"
        links="$(ls "$LINKS_DIR/$name"/*.json 2>/dev/null | wc -l | tr -d ' ' || true)"
        d_info "worktree $name: $links linked conversation(s)"
      done
      # Self-test: feed the linker a synthetic `join` of the newest worktree and
      # look for the link file it must write. Exercises jq, HOME, the registry
      # path and the script itself exactly as Claude Code would run it.
      if [[ -n "$found_hook" && -n "$jq_bin" ]]; then
        meta="$(ls -t "$META_DIR"/*.json 2>/dev/null | head -n1)"
        name="$(jq -r .name "$meta")"; sid="doctor-$$-$RANDOM"
        payload="$(jq -n --arg sid "$sid" --arg cmd "air-worktree join $name" --arg out "AIR_WORKTREE_JSON $(jq -c . "$meta")" \
          '{session_id:$sid, tool_name:"Bash", tool_input:{command:$cmd}, tool_response:{stdout:$out}}')"
        if bash "$found_hook" <<<"$payload" && [[ -f "$LINKS_DIR/$name/$sid.json" ]]; then
          d_ok "self-test: the PostToolUse linker wrote $LINKS_DIR/$name/$sid.json (removed again)"
        else
          d_bad "self-test: the PostToolUse linker did NOT write $LINKS_DIR/$name/$sid.json — run it by hand to see why: printf '%s' '<payload>' | bash $found_hook"
        fi
        rm -f "$LINKS_DIR/$name/$sid.json" "${TMPDIR:-/tmp}/air-worktree-hook-$sid.json"
      fi
    else
      d_info "no Air worktrees registered for this repo yet"
    fi
  fi
  if [[ "$DOCTOR_FAIL" == "0" ]]; then printf 'All checks passed.\n'; else printf 'Some checks FAILED — see above.\n'; fi
  return "$DOCTOR_FAIL"
}
if [[ "$VERB" == "doctor" ]]; then
  # if-form, not `|| true`: under bash 3.2's errexit a `die` (exit) inside a
  # function inside $(…) takes the parent shell down even with `|| true`.
  if ! ROOT="$(repo_root "${REPO_ARG:-$PWD}" 2>/dev/null)"; then ROOT=""; fi
  KEY=""; META_DIR=""; LINKS_DIR=""
  if [[ -n "$ROOT" ]]; then
    KEY="$(repo_key "$ROOT")"; META_DIR="$WT_HOME/$KEY/meta"; LINKS_DIR="$WT_HOME/$KEY/links"
  fi
  doctor
  exit $?
fi

need_jq
# `adopt <path>` names the worktree, not the repo: resolve the registry from it.
if [[ "$VERB" == "adopt" && -z "$REPO_ARG" && ${#POSITIONAL[@]} -ge 1 ]]; then
  [[ -d "${POSITIONAL[0]}" ]] || die "no such directory: ${POSITIONAL[0]}"
  REPO_ARG="${POSITIONAL[0]}"
fi
# `join|path|status <name>` without --repo: the name is looked up in the cwd's
# repository first; when that repo has no worktree of that name (or the cwd is in
# no repo at all), every registry under $WT_HOME is searched. A session often
# starts in ANOTHER repository of the workspace than the worktree it is told to
# join, and a failed join leaves the conversation unlinked. One match = use its
# registry; several (one group spans repos) = refuse, naming the --repo forms.
find_registry_for_name() {
  local name="$1" f matches=() cwd_root=""
  [[ "$name" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]] || return 1
  if cwd_root="$(repo_root "$PWD" 2>/dev/null)" && [[ -f "$WT_HOME/$(repo_key "$cwd_root")/meta/$name.json" ]]; then
    printf '%s' "$cwd_root"; return 0
  fi
  for f in "$WT_HOME"/*/meta/"$name".json; do [[ -f "$f" ]] && matches+=("$f"); done
  if [[ ${#matches[@]} -eq 1 ]]; then
    jq -r '.repoRoot // empty' "${matches[0]}"; return 0
  fi
  if [[ ${#matches[@]} -gt 1 ]]; then
    {
      printf "air-worktree: worktree '%s' exists in %d repositories and %s is in none of them — pick one:\n" "$name" "${#matches[@]}" "$PWD"
      for f in "${matches[@]}"; do printf '  air-worktree %s %s --repo %s\n' "$VERB" "$name" "$(jq -r '.repoRoot // empty' "$f")"; done
    } >&2
    return 2
  fi
  printf '%s' "$cwd_root"
}
ROOT=""
if [[ -z "$REPO_ARG" && ${#POSITIONAL[@]} -ge 1 ]]; then
  case "$VERB" in
    join|path|status|goal)
      # if-form: a non-zero status inside $(…) must not trip errexit (bash 3.2).
      if ROOT="$(find_registry_for_name "${POSITIONAL[0]}")"; then :; else
        [[ $? -eq 2 ]] && exit 1
        ROOT=""
      fi ;;
  esac
fi
[[ -n "$ROOT" ]] || ROOT="$(repo_root "${REPO_ARG:-$PWD}")"
KEY="$(repo_key "$ROOT")"
REPO_DIR="$WT_HOME/$KEY"
META_DIR="$REPO_DIR/meta"
TREES_DIR="$REPO_DIR/trees"
LINKS_DIR="$REPO_DIR/links"

ensure_registry() {
  umask 077
  mkdir -p "$META_DIR" "$TREES_DIR" "$LINKS_DIR"
  if [[ ! -f "$REPO_DIR/repo.json" ]]; then
    jq -n --arg root "$ROOT" --arg key "$KEY" '{repoRoot:$root, repoKey:$key, version:1}' >"$REPO_DIR/repo.json"
  fi
}

# One mutating air-worktree run at a time per repository: a Cursor setup script and
# a sessionStart hook, or two Air windows, can both adopt/create within the same
# second and mint two names for one path. mkdir is the atomic primitive every
# platform has; a lock older than 60 s belongs to a dead run.
LOCK_DIR=""
release_lock() { [[ -n "$LOCK_DIR" ]] && rmdir "$LOCK_DIR" 2>/dev/null; return 0; }
take_lock() {
  local i=0 age
  mkdir -p "$REPO_DIR"
  LOCK_DIR="$REPO_DIR/.lock"
  until mkdir "$LOCK_DIR" 2>/dev/null; do
    age=$(( $(date -u +%s) - $(file_mtime "$LOCK_DIR") ))
    if (( age > 60 )); then rmdir "$LOCK_DIR" 2>/dev/null || rm -rf "$LOCK_DIR"; continue; fi
    i=$((i + 1))
    (( i > 150 )) && die "the registry is locked by another air-worktree run ($LOCK_DIR); try again"
    sleep 0.1
  done
  trap release_lock EXIT
}
case "$VERB" in create|adopt|rename|remove|goal) take_lock ;; esac

# Registry hygiene for adopted worktrees: their manager owns the checkout (Cursor
# sweeps ~/.cursor/worktrees past its limit), so a record whose directory is gone is
# unregistered here rather than lingering as a worktree that does not exist.
sweep_adopted() {
  local f p n
  ls "$META_DIR"/*.json >/dev/null 2>&1 || return 0
  for f in "$META_DIR"/*.json; do
    [[ "$(jq -r '.adopted // false' "$f" 2>/dev/null)" == "true" ]] || continue
    p="$(jq -r '.path // empty' "$f")"; n="$(jq -r '.name // empty' "$f")"
    [[ -n "$p" && ! -d "$p" ]] || continue
    rm -f "$f"; rm -rf "$LINKS_DIR/$n"
    printf 'AIR_WORKTREE_REMOVED %s %s\n' "$n" "$KEY"
  done
}

require_name() {
  [[ ${#POSITIONAL[@]} -ge 1 ]] || die "$VERB needs a worktree name (see: air-worktree list)"
  NAME="${POSITIONAL[0]}"
  [[ "$NAME" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]] || die "invalid worktree name: $NAME"
  META="$META_DIR/$NAME.json"
  [[ -f "$META" ]] || die "no worktree named '$NAME' for $ROOT (see: air-worktree list)"
}

case "$VERB" in
  create)
    ensure_registry
    if [[ -n "$BASE_REF" ]]; then
      BASE_SHA="$(git -C "$ROOT" rev-parse --verify --quiet "${BASE_REF}^{commit}")" || die "unknown base ref: $BASE_REF"
    else
      BASE_SHA="$(git -C "$ROOT" rev-parse --verify --quiet HEAD)" || die "repository has no commits yet"
      BASE_REF="$(git -C "$ROOT" rev-parse --abbrev-ref HEAD)"
      [[ "$BASE_REF" != "HEAD" ]] || BASE_REF="$BASE_SHA"
    fi
    if [[ -n "$BRANCH_ARG" ]]; then
      # An existing branch: the name only has to be free in the registry and
      # the trees dir (the branch air/<name> legitimately exists already).
      SLUG="$(slugify "${NAME_ARG:-${BRANCH_ARG#air/}}")"
      [[ -n "$SLUG" ]] || die "no usable worktree name for branch $BRANCH_ARG — pass --name <name>"
      NAME="$SLUG"; i=2
      while [[ -e "$META_DIR/$NAME.json" || -e "$TREES_DIR/$NAME" ]]; do NAME="$SLUG-$i"; i=$((i + 1)); done
      BRANCH="$BRANCH_ARG"
      WPATH="$(native_path "$TREES_DIR/$NAME")"
      if git -C "$ROOT" show-ref --verify --quiet "refs/heads/$BRANCH"; then
        ERR="$(git -C "$ROOT" worktree add "$WPATH" "$BRANCH" 2>&1 >/dev/null)" \
          || die "git worktree add failed for $WPATH (branch $BRANCH): $ERR"
      else
        REMOTE_REF=""
        for r in origin $(git -C "$ROOT" remote 2>/dev/null); do
          if git -C "$ROOT" show-ref --verify --quiet "refs/remotes/$r/$BRANCH"; then REMOTE_REF="$r/$BRANCH"; break; fi
        done
        [[ -n "$REMOTE_REF" ]] || die "branch $BRANCH exists neither locally nor on a fetched remote (git fetch <remote> $BRANCH first)"
        ERR="$(git -C "$ROOT" worktree add --track -b "$BRANCH" "$WPATH" "$REMOTE_REF" 2>&1 >/dev/null)" \
          || die "git worktree add failed for $WPATH (branch $BRANCH from $REMOTE_REF): $ERR"
      fi
      # The base is where the branch left the base ref, so the panel's
      # "commits ahead" counts this branch's own work.
      HEAD_SHA="$(git -C "$WPATH" rev-parse --verify --quiet HEAD)" || die "$WPATH has no commits"
      MB="$(git -C "$ROOT" merge-base "$BASE_SHA" "$HEAD_SHA" 2>/dev/null || true)"
      [[ -n "$MB" ]] && BASE_SHA="$MB"
    else
      if [[ -n "$NAME_ARG" ]]; then
        SLUG="$(slugify "$NAME_ARG")"
        [[ -n "$SLUG" ]] || die "--name '$NAME_ARG' has no usable characters"
        NAME="$(unique_name "$SLUG" "$META_DIR" "$TREES_DIR")"
      else
        NAME="$(gen_name "$META_DIR" "$TREES_DIR")"
      fi
      BRANCH="air/$NAME"
      WPATH="$(native_path "$TREES_DIR/$NAME")"
      git -C "$ROOT" worktree add -b "$BRANCH" "$WPATH" "$BASE_SHA" >/dev/null 2>&1 \
        || die "git worktree add failed for $WPATH (branch $BRANCH, base $BASE_SHA)"
    fi
    jq -n \
      --arg name "$NAME" --arg path "$WPATH" --arg branch "$BRANCH" \
      --arg baseRef "$BASE_REF" --arg baseSha "$BASE_SHA" \
      --arg repoRoot "$ROOT" --arg repoKey "$KEY" --arg createdAt "$(now_iso)" \
      '{name:$name, path:$path, branch:$branch, baseRef:$baseRef, baseSha:$baseSha, repoRoot:$repoRoot, repoKey:$repoKey, createdAt:$createdAt, groupModel:2, version:1}' \
      >"$META_DIR/$NAME.json"
    set_goal "$META_DIR/$NAME.json" "$GOAL_ARG"
    mkdir -p "$LINKS_DIR/$NAME"
    claim_pending_link "$NAME_ARG" "$NAME" creator
    if [[ -n "${SLUG:-}" && "$NAME" != "$SLUG" && "$JSON_ONLY" != "1" ]]; then
      # Groups follow the conversation, not the name: the suffixed worktree is in THIS
      # session's group, never in the group of the worktree that already had the name.
      printf "Note: a worktree named '%s' already exists in this repository, so this one is '%s'. It belongs to this conversation's worktree group (groups follow the conversation that creates a worktree, not its name) — if this task should continue in '%s', ask the user instead of working here.\n" "$SLUG" "$NAME" "$SLUG"
    fi
    emit_record "$META_DIR/$NAME.json" created "$JSON_ONLY"
    ;;

  join)
    require_name
    [[ -d "$(jq -r .path "$META")" ]] || die "worktree '$NAME' is registered but its directory is gone — remove it with: air-worktree remove $NAME"
    set_goal "$META" "$GOAL_ARG" 1
    mkdir -p "$LINKS_DIR/$NAME"
    claim_pending_link "$NAME" "$NAME" joined
    emit_record "$META" joined "$JSON_ONLY"
    ;;

  goal)
    require_name
    if [[ ${#POSITIONAL[@]} -ge 2 ]]; then
      set_goal "$META" "${POSITIONAL[1]}"
      printf 'Goal of %s: %s\n' "$NAME" "$(jq -r '.goal // empty' "$META")"
    else
      jq -r '.goal // empty' "$META"
    fi
    ;;

  adopt)
    ensure_registry
    sweep_adopted
    WT_IN="${POSITIONAL[0]:-$PWD}"
    WT_TOP="$(git -C "$WT_IN" rev-parse --show-toplevel 2>/dev/null)" || die "$WT_IN is not inside a git work tree"
    WT_GIT="$(cd "$WT_TOP" && cd "$(git rev-parse --git-dir)" && pwd -P)"
    WT_COMMON="$(cd "$WT_TOP" && cd "$(git rev-parse --git-common-dir)" && pwd -P)"
    [[ "$WT_GIT" != "$WT_COMMON" ]] || die "$WT_TOP is the main checkout, not a linked worktree — to start one, use: air-worktree create --name <feature-slug>"
    WPATH="$(native_path "$WT_TOP")"
    # Already registered (by path): behave like join.
    EXISTING=""
    if ls "$META_DIR"/*.json >/dev/null 2>&1; then
      EXISTING="$(jq -r --arg p "$WPATH" 'select(.path == $p) | .name' "$META_DIR"/*.json 2>/dev/null | head -n1)"
    fi
    if [[ -n "$EXISTING" ]]; then
      NAME="$EXISTING"
      set_goal "$META_DIR/$NAME.json" "$GOAL_ARG" 1
      mkdir -p "$LINKS_DIR/$NAME"
      claim_pending_link "$NAME_ARG" "$NAME" joined
      emit_record "$META_DIR/$NAME.json" joined "$JSON_ONLY"
      exit 0
    fi
    BRANCH="$(git -C "$WT_TOP" rev-parse --abbrev-ref HEAD 2>/dev/null || true)"
    HEAD_SHA="$(git -C "$WT_TOP" rev-parse --verify --quiet HEAD)" || die "$WT_TOP has no commits"
    [[ -n "$BRANCH" && "$BRANCH" != "HEAD" ]] || BRANCH="$HEAD_SHA"
    if [[ -n "$BASE_REF" ]]; then
      BASE_SHA="$(git -C "$ROOT" rev-parse --verify --quiet "${BASE_REF}^{commit}")" || die "unknown base ref: $BASE_REF"
    else
      # The main checkout's current branch is the base Cursor and Claude Code cut from
      # (both default to the current HEAD); the merge-base is where this branch left it.
      BASE_REF="$(git -C "$ROOT" rev-parse --abbrev-ref HEAD 2>/dev/null || true)"
      BASE_SHA="$(git -C "$ROOT" rev-parse --verify --quiet HEAD)"
      [[ -n "$BASE_REF" && "$BASE_REF" != "HEAD" ]] || BASE_REF="$BASE_SHA"
      MB="$(git -C "$ROOT" merge-base "$BASE_SHA" "$HEAD_SHA" 2>/dev/null || true)"
      [[ -n "$MB" ]] && BASE_SHA="$MB"
    fi
    if [[ -n "$NAME_ARG" ]]; then SLUG="$(slugify "$NAME_ARG")"; else SLUG="$(slugify "$(basename "$WT_TOP")")"; fi
    [[ -n "$SLUG" ]] || die "no usable name for $WT_TOP — pass --name <name>"
    NAME="$(unique_name "$SLUG" "$META_DIR" "$TREES_DIR")"
    case "$WPATH" in
      */.cursor/worktrees/*) MANAGER=cursor ;;
      */.claude/worktrees/*) MANAGER=claude ;;
      *) MANAGER=external ;;
    esac
    jq -n \
      --arg name "$NAME" --arg path "$WPATH" --arg branch "$BRANCH" \
      --arg baseRef "$BASE_REF" --arg baseSha "$BASE_SHA" --arg manager "$MANAGER" \
      --arg repoRoot "$ROOT" --arg repoKey "$KEY" --arg createdAt "$(now_iso)" \
      '{name:$name, path:$path, branch:$branch, baseRef:$baseRef, baseSha:$baseSha, repoRoot:$repoRoot, repoKey:$repoKey, createdAt:$createdAt, adopted:true, manager:$manager, groupModel:2, version:1}' \
      >"$META_DIR/$NAME.json"
    set_goal "$META_DIR/$NAME.json" "$GOAL_ARG"
    mkdir -p "$LINKS_DIR/$NAME"
    claim_pending_link "$NAME_ARG" "$NAME" creator
    emit_record "$META_DIR/$NAME.json" adopted "$JSON_ONLY"
    ;;

  path)
    require_name
    jq -r .path "$META"
    ;;

  list)
    if [[ ! -d "$META_DIR" ]] || ! ls "$META_DIR"/*.json >/dev/null 2>&1; then
      if [[ "$JSON_ONLY" == "1" ]]; then printf '[]\n'; else printf 'No Air worktrees for %s\n' "$ROOT"; fi
      exit 0
    fi
    if [[ "$JSON_ONLY" == "1" ]]; then
      jq -s . "$META_DIR"/*.json
    else
      printf '%-24s %-32s %s\n' NAME BRANCH PATH
      for f in "$META_DIR"/*.json; do
        jq -r '[.name, .branch, .path] | @tsv' "$f" | awk -F'\t' '{ printf "%-24s %-32s %s\n", $1, $2, $3 }'
      done
    fi
    ;;

  status)
    require_name
    WPATH="$(jq -r .path "$META")"
    [[ -d "$WPATH" ]] || die "worktree directory missing: $WPATH"
    BASE_SHA="$(jq -r .baseSha "$META")"
    PORCELAIN="$(git -C "$WPATH" status --porcelain=v1 2>/dev/null || true)"
    MOD=0; ADD=0; DEL=0; UNT=0
    while IFS= read -r line; do
      [[ -n "$line" ]] || continue
      code="${line:0:2}"
      case "$code" in
        '??') UNT=$((UNT + 1)) ;;
        *D*) DEL=$((DEL + 1)) ;;
        *A*) ADD=$((ADD + 1)) ;;
        *) MOD=$((MOD + 1)) ;;
      esac
    done <<<"$PORCELAIN"
    COMMITS="$(git -C "$WPATH" rev-list --count "$BASE_SHA..HEAD" 2>/dev/null || echo 0)"
    # Conversations the PostToolUse linker tied to this worktree (0 after a
    # create/join means the hook never ran — see `air-worktree doctor`).
    SESSIONS="$(ls "$LINKS_DIR/$NAME"/*.json 2>/dev/null | wc -l | tr -d ' ' || true)"
    SESSIONS="${SESSIONS:-0}"
    UPSTREAM="$(git -C "$WPATH" rev-parse --abbrev-ref --symbolic-full-name '@{u}' 2>/dev/null || true)"
    UNPUSHED=0
    if [[ -n "$UPSTREAM" ]]; then
      UNPUSHED="$(git -C "$WPATH" rev-list --count '@{u}..HEAD' 2>/dev/null || echo 0)"
    fi
    if [[ "$JSON_ONLY" == "1" ]]; then
      jq -n --arg name "$NAME" --arg path "$WPATH" --argjson m "$MOD" --argjson a "$ADD" --argjson d "$DEL" --argjson u "$UNT" \
        --argjson commits "$COMMITS" --arg upstream "$UPSTREAM" --argjson unpushed "$UNPUSHED" --argjson sessions "$SESSIONS" \
        '{name:$name, path:$path, files:{modified:$m, added:$a, deleted:$d, untracked:$u}, commits:$commits, upstream:(if $upstream=="" then null else $upstream end), unpushed:$unpushed, sessions:$sessions}'
    else
      printf '%s (%s)\n' "$NAME" "$WPATH"
      printf '  files:    %d modified, %d added, %d deleted, %d untracked\n' "$MOD" "$ADD" "$DEL" "$UNT"
      printf '  commits:  %s ahead of base\n' "$COMMITS"
      if [[ -n "$UPSTREAM" ]]; then
        printf '  upstream: %s (%s unpushed)\n' "$UPSTREAM" "$UNPUSHED"
      else
        printf '  upstream: none (not pushed)\n'
      fi
      printf '  sessions: %s linked conversation(s)\n' "$SESSIONS"
    fi
    ;;

  rename)
    require_name
    [[ ${#POSITIONAL[@]} -ge 2 ]] || die "rename needs the new name: air-worktree rename <name> <new-name>"
    NEW="$(slugify "${POSITIONAL[1]}")"
    [[ -n "$NEW" ]] || die "new name '${POSITIONAL[1]}' has no usable characters"
    [[ "$NEW" != "$NAME" ]] || die "'$NAME' is already the worktree's name"
    NEW="$(unique_name "$NEW" "$META_DIR" "$TREES_DIR")"
    OLD_PATH="$(jq -r .path "$META")"
    OLD_BRANCH="$(jq -r .branch "$META")"
    ADOPTED="$(jq -r '.adopted // false' "$META")"
    NEW_BRANCH="$OLD_BRANCH"
    if [[ "$ADOPTED" == "true" ]]; then
      # Another tool owns the checkout's location (Cursor sweeps ~/.cursor/worktrees by
      # path): rename the registry entry only.
      NEW_PATH="$OLD_PATH"
    else
      NEW_PATH="$(native_path "$TREES_DIR/$NEW")"
      if [[ -d "$OLD_PATH" ]]; then
        git -C "$ROOT" worktree move "$OLD_PATH" "$NEW_PATH" >/dev/null 2>&1 || die "git worktree move failed ($OLD_PATH → $NEW_PATH); is the checkout locked or dirty-submoduled?"
      fi
    fi
    # Rename the branch unless it is already published (or --keep-branch): a
    # pushed branch is referenced by remotes / PRs, so we leave it alone.
    if [[ "$KEEP_BRANCH" != "1" && "$OLD_BRANCH" == "air/$NAME" ]]; then
      if ! git -C "$ROOT" rev-parse --verify --quiet "$OLD_BRANCH@{u}" >/dev/null 2>&1; then
        if git -C "$ROOT" branch -m "$OLD_BRANCH" "air/$NEW" 2>/dev/null; then
          NEW_BRANCH="air/$NEW"
        fi
      fi
    fi
    jq --arg name "$NEW" --arg path "$NEW_PATH" --arg branch "$NEW_BRANCH" --arg renamedFrom "$NAME" --arg at "$(now_iso)" \
      '.name = $name | .path = $path | .branch = $branch | .renamedFromAll = ((.renamedFromAll // []) + [$renamedFrom]) | .renamedFrom = $renamedFrom | .renamedAt = $at' "$META" >"$META_DIR/$NEW.json"
    rm -f "$META"
    if [[ -d "$LINKS_DIR/$NAME" ]]; then
      mkdir -p "$LINKS_DIR/$NEW"
      cp -R "$LINKS_DIR/$NAME"/. "$LINKS_DIR/$NEW"/ 2>/dev/null || true
      rm -rf "$LINKS_DIR/$NAME"
    fi
    # Best effort: sessions on this machine that recorded the old name keep
    # pointing at the right worktree (the UserPromptSubmit reminder reads it).
    for st in "${TMPDIR:-/tmp}"/air-worktree-hook-*.json; do
      [[ -f "$st" ]] || continue
      if grep -q "\"$NAME\"" "$st" 2>/dev/null; then
        # Match on name AND repo — a same-named worktree in another repo of the
        # workspace must not be touched.
        jq --arg old "$NAME" --arg key "$KEY" --arg name "$NEW" --arg path "$NEW_PATH" --arg branch "$NEW_BRANCH" '
          (if (.worktrees | type) == "array" then .worktrees |= map(if .name == $old and ((.repoKey // "") == $key or (.repoKey // "") == "") then .name = $name | .path = $path | .branch = $branch else . end) else . end)
          | if (.name // "") == $old and ((.repoKey // "") == $key or (.repoKey // "") == "") then .name = $name | .path = $path | .branch = $branch else . end' "$st" >"$st.tmp" 2>/dev/null && mv "$st.tmp" "$st"
      fi
    done
    printf 'Renamed worktree %s → %s\n' "$NAME" "$NEW"
    if [[ "$NEW_BRANCH" == "$OLD_BRANCH" ]]; then
      printf '  branch kept: %s (already published or --keep-branch)\n' "$OLD_BRANCH"
    else
      printf '  branch:      %s → %s\n' "$OLD_BRANCH" "$NEW_BRANCH"
    fi
    printf '  path:        %s\n' "$NEW_PATH"
    emit_record "$META_DIR/$NEW.json" renamed "$JSON_ONLY"
    ;;

  remove)
    require_name
    WPATH="$(jq -r .path "$META")"
    if [[ "$(jq -r '.adopted // false' "$META")" == "true" ]]; then
      # Adopted = created and owned by another tool: unregister, never delete its checkout.
      rm -f "$META"
      rm -rf "$LINKS_DIR/$NAME"
      printf 'Unregistered adopted worktree %s (checkout %s left in place — its manager owns it)\n' "$NAME" "$WPATH"
      printf 'AIR_WORKTREE_REMOVED %s %s\n' "$NAME" "$KEY"
      exit 0
    fi
    if [[ -d "$WPATH" ]]; then
      git -C "$ROOT" worktree remove --force "$WPATH" >/dev/null 2>&1 || rm -rf "$WPATH"
    fi
    git -C "$ROOT" worktree prune >/dev/null 2>&1 || true
    rm -f "$META"
    rm -rf "$LINKS_DIR/$NAME"
    printf 'Removed worktree %s (branch air/%s kept)\n' "$NAME" "$NAME"
    printf 'AIR_WORKTREE_REMOVED %s %s\n' "$NAME" "$KEY"
    ;;

  *)
    die "unknown command: $VERB (try: air-worktree --help)"
    ;;
esac
