# BEGIN: AI GUARDRAILS

# Worktree plugin bootstrap.
#
# A git worktree is a DISTINCT project path to Claude Code, so the plugins
# enabled in .claude/settings.json are "enabled in project settings but isn't
# installed here" for the worktree until `claude plugin install --scope project`
# runs against that path. The result: Lisa's guardrail hooks (block-no-verify,
# the verification gate, inject-rules) AND the other managed plugins
# (coderabbit / sentry / atlassian / safety-net / …) load ZERO hooks in a
# worktree session started as `cd <worktree> && claude`. (A `claude -w` session
# inherits the marketplace plugins, but the project-scoped ones still report
# "not installed here".)
#
# git fires post-checkout INSIDE the new worktree at `git worktree add` time
# (which `claude -w` and Fleet both use), so this is a deadlock-free place to
# seed those installs once, before any session loads plugins. Both `claude -w`
# and standalone `cd && claude` sessions then resolve every enabled plugin.
#
# Guards keep it cheap and safe:
#   - only in a LINKED git worktree (its private git dir differs from the shared
#     common dir); the primary checkout is handled by `lisa apply`. This catches
#     worktrees created anywhere (`git worktree add ../feature`), not just under
#     .claude/worktrees;
#   - only on a branch checkout ($3 = 1), never a file checkout;
#   - only once per worktree (a sentinel in the worktree's private git dir), so
#     ordinary branch switches do not re-run 10+ installs;
#   - only when `claude` and `jq` are on PATH and settings exist (skips CI/remote);
#   - each Claude call is time-bounded (when a `timeout` binary exists) so a
#     stalled network can't hang `git worktree add` past the WorktreeCreate budget;
#   - best-effort — never blocks or fails the checkout.

# Run the Claude CLI with a wall-clock bound when `timeout`/`gtimeout` is
# available, so a hung network call can't stall worktree creation indefinitely.
_lisa_claude() {
  if command -v timeout >/dev/null 2>&1; then
    timeout 45 claude "$@"
  elif command -v gtimeout >/dev/null 2>&1; then
    gtimeout 45 claude "$@"
  else
    claude "$@"
  fi
}

_lisa_bootstrap_worktree_plugins() {
  # $3 == 1 -> branch checkout (worktree add / branch switch); 0 -> file checkout
  [ "${3:-1}" = "1" ] || return 0
  command -v claude >/dev/null 2>&1 || return 0
  command -v jq >/dev/null 2>&1 || return 0

  # Only LINKED worktrees need bootstrapping — detect via git metadata rather
  # than a path substring, so worktrees created outside .claude/worktrees still
  # get their project-scoped installs. Equal dirs ⇒ primary checkout ⇒ skip.
  _gitdir="$(git rev-parse --git-dir 2>/dev/null || echo .git)"
  _common_gitdir="$(git rev-parse --git-common-dir 2>/dev/null || echo "$_gitdir")"
  [ "$_gitdir" != "$_common_gitdir" ] || return 0

  _root="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
  _settings="$_root/.claude/settings.json"
  [ -f "$_settings" ] || return 0

  # Per-worktree sentinel lives in the worktree's private git dir
  # (<main>/.git/worktrees/<name>), so it neither pollutes the tree nor leaks to
  # other worktrees, and survives branch switches.
  _sentinel="$_gitdir/lisa-plugins-bootstrapped"
  [ -f "$_sentinel" ] && return 0

  # Only the truthy entries — an explicit `false` means "disabled", not "install".
  _plugins="$(jq -r '(.enabledPlugins // {}) | to_entries[] | select(.value == true) | .key' "$_settings" 2>/dev/null)"
  [ -n "$_plugins" ] || return 0

  echo "🔌 Bootstrapping Claude Code plugins for new worktree (scope: project)…"
  _lisa_claude plugin marketplace update lisa >/dev/null 2>&1 || true
  _had_failure=0
  for _p in $_plugins; do
    # Skip ids with shell-unsafe characters before interpolating into the CLI.
    case "$_p" in
      *[!A-Za-z0-9@._/-]*) continue ;;
    esac
    if _lisa_claude plugin install "$_p" --scope project >/dev/null 2>&1; then
      echo "  ✓ $_p"
    else
      echo "  ⚠ $_p (skipped)"
      _had_failure=1
    fi
  done

  # Mark bootstrapped only when every install succeeded, so a transient failure
  # retries on the next checkout instead of being skipped forever.
  if [ "$_had_failure" = "0" ]; then
    : >"$_sentinel" 2>/dev/null || true
  fi
}

# Never let a bootstrap hiccup block the checkout.
_lisa_bootstrap_worktree_plugins "$@" || true

exit 0

# END: AI GUARDRAILS
