#!/usr/bin/env bash
# gstack-team-init — generate repo-level bootstrap files for team mode
#
# Usage:
#   gstack-team-init optional   # gentle CLAUDE.md suggestion, one-time offer
#   gstack-team-init required   # CLAUDE.md enforcement + PreToolUse hook
#
# Run from the root of your team's repo (not from the gstack directory).

# Heredoc delivery guard. bash 5.2+ writes a heredoc body <=64KiB through a
# pipe in the forked child before exec, with no reader on the other end. On
# macOS under pipe-KVA pressure a fresh pipe gets a 512-byte buffer, so any
# body >=512B blocks write() forever and the script hangs at startup with no
# output. Compat level 50 restores the tempfile path. These scripts are
# bash-3.2-clean, so the compat level costs them nothing. Not exported: the
# guard is per-script, and it survives `bash script.sh` call sites that
# bypass the shebang.
BASH_COMPAT=50

set -euo pipefail
GSTACK_BUN_CONFIG=/dev/null; case "${OSTYPE:-}" in msys*|cygwin*) if command -v cygpath >/dev/null 2>&1; then GSTACK_BUN_CONFIG=NUL; fi ;; esac

MODE="${1:-}"

if [ "$MODE" != "optional" ] && [ "$MODE" != "required" ]; then
  echo "Usage: gstack-team-init {optional|required}" >&2
  echo "" >&2
  echo "  optional  — suggest gstack install once per developer (gentle)" >&2
  echo "  required  — enforce gstack install, block work without it" >&2
  exit 1
fi

# Must be in a git repo
if ! git rev-parse --show-toplevel >/dev/null 2>&1; then
  echo "Error: not in a git repository. Run from your project root." >&2
  exit 1
fi

REPO_ROOT=$(git rev-parse --show-toplevel)
CLAUDE_MD="$REPO_ROOT/CLAUDE.md"
GENERATED=()
HOOK_COMMAND="node -e \"require(require('path').resolve(process.env.CLAUDE_PROJECT_DIR || '.', '.claude', 'hooks', 'check-gstack.cjs'))\""

# ── Migrate vendored copy if present ──────────────────────────

if [ -d "$REPO_ROOT/.claude/skills/gstack" ] && [ ! -L "$REPO_ROOT/.claude/skills/gstack" ]; then
  if [ -f "$REPO_ROOT/.claude/skills/gstack/VERSION" ] || [ -d "$REPO_ROOT/.claude/skills/gstack/.git" ]; then
    echo "  Found vendored gstack copy at $REPO_ROOT/.claude/skills/gstack"
    echo "  Team mode uses the global install — removing vendored copy..."
    ( cd "$REPO_ROOT" && git rm -r --cached .claude/skills/gstack/ 2>/dev/null ) || true
    if [ -f "$REPO_ROOT/.gitignore" ]; then
      if ! grep -qF '.claude/skills/gstack/' "$REPO_ROOT/.gitignore" 2>/dev/null; then
        echo '.claude/skills/gstack/' >> "$REPO_ROOT/.gitignore"
      fi
    else
      echo '.claude/skills/gstack/' > "$REPO_ROOT/.gitignore"
    fi
    rm -rf "$REPO_ROOT/.claude/skills/gstack"
    GENERATED+=(".gitignore")
    echo "  Removed vendored copy and added .claude/skills/gstack/ to .gitignore"
  fi
fi

# ── CLAUDE.md snippet and preflight ────────────────────────────

if [ "$MODE" = "optional" ]; then
  SNIPPET='## gstack (recommended)

This project uses [gstack](https://github.com/garrytan/gstack) for AI-assisted workflows.
Install it for the best experience:

```bash
git clone --depth 1 https://github.com/garrytan/gstack.git ~/.claude/skills/gstack
cd ~/.claude/skills/gstack && ./setup --team
```

Default install includes the Core-10 skills (such as /review, /qa, and /gstack-ship); your AI coding tool lists installed skills automatically.
If the optional browser pack is installed (`./setup --pack browser`), use /browse for web browsing (Aside first, the bundled gstack browser as fallback). Use ~/.claude/skills/gstack/... for gstack file paths.'
else
  SNIPPET='## gstack (REQUIRED — global install)

**Before doing ANY work, verify gstack is installed:**

```bash
_GS=""
for _D in "${GSTACK_ROOT:-}" "$HOME/.claude/skills/gstack" "$HOME/.codex/skills/gstack" "$HOME/.factory/skills/gstack" "$HOME/.kiro/skills/gstack" "$HOME/.config/opencode/skills/gstack" "$HOME/.slate/skills/gstack" "$HOME/.cursor/skills/gstack" "$HOME/.openclaw/skills/gstack" "$HOME/.hermes/skills/gstack" "$HOME/.gbrain/skills/gstack" "$HOME/.copilot/skills/gstack" "$HOME/.gemini/antigravity-cli/skills/gstack" "$HOME/.gemini/skills/gstack" "$HOME/.gstack/repos/gstack"; do
  [ -z "$_GS" ] && [ -n "$_D" ] && [ -d "$_D/bin" ] && _GS="$_D"
done
[ -n "$_GS" ] && echo "GSTACK_OK: $_GS" || echo "GSTACK_MISSING"
```

If GSTACK_MISSING: STOP. Do not proceed. Tell the user:

> gstack is required for all AI-assisted work in this repo.
> Install it:
> ```bash
> git clone --depth 1 https://github.com/garrytan/gstack.git ~/.claude/skills/gstack
> cd ~/.claude/skills/gstack && ./setup --team
> ```
> Then restart your AI coding tool.

Do not skip skills, ignore gstack errors, or work around missing gstack.

Using gstack skills: Default install includes the Core-10 skills (such as
/review, /qa, and /gstack-ship); your AI coding tool lists installed skills
automatically. If the optional browser pack is installed
(`./setup --pack browser`), use /browse for web browsing (Aside first, the
bundled gstack browser as fallback).
Use the resolved install path above for gstack file paths
(default: ~/.claude/skills/gstack).

The Skill gate in .claude/settings.json runs .claude/hooks/check-gstack.cjs with
Node.js and blocks when it cannot run. If a skill is blocked with "node: not
found", tell the user to install Node.js (https://nodejs.org); if it is blocked
with "Cannot find module ... check-gstack.cjs", the hook file is missing from
this checkout. Do not work around either block.'
fi

# Wrap the managed section in begin/end markers carrying the body's git blob
# hash so later runs can refresh unmodified generated sections in place while
# leaving hand-edited or unmarked sections untouched (matching harness-register).
MARKER_BEGIN_PREFIX='<!-- gstack:begin team-init hash:'
MARKER_BEGIN_SUFFIX=' -->'
MARKER_END='<!-- gstack:end team-init -->'
SNIPPET_HASH=$(printf '%s\n' "$SNIPPET" | git -C "$REPO_ROOT" hash-object --stdin)
BLOCK_BEGIN="${MARKER_BEGIN_PREFIX}${SNIPPET_HASH}${MARKER_BEGIN_SUFFIX}"

LINES=()
LINE_COUNT=0
BEGIN_COUNT=0
END_COUNT=0
BEGIN_IDX=-1
END_IDX=-1
IN_HARNESS_BLOCK=0
HAS_UNMARKED_GSTACK=0
ENDED_WITH_NL=1
CR=$'\r'
CLAUDE_ACTION="append"
CLAUDE_SKIP_REASON=""
CLAUDE_EXISTED=0
CLAUDE_PRE_HASH=""

if [ -L "$CLAUDE_MD" ]; then
  CLAUDE_ACTION="symlink"
  CLAUDE_SKIP_REASON="CLAUDE.md is a symlink"
else
  if [ -f "$CLAUDE_MD" ]; then
    CLAUDE_EXISTED=1
    CLAUDE_PRE_HASH=$(git -C "$REPO_ROOT" hash-object "$CLAUDE_MD")
    IDX=0
    while true; do
      if IFS= read -r RAW_LINE; then
        :
      elif [ -n "$RAW_LINE" ]; then
        ENDED_WITH_NL=0
      else
        break
      fi
      LINES+=("$RAW_LINE")
      CLEAN_LINE="${RAW_LINE%"$CR"}"
      case "$CLEAN_LINE" in
        '<!-- gstack:begin harness-routing -->')
          IN_HARNESS_BLOCK=1
          ;;
        '<!-- gstack:end harness-routing -->')
          IN_HARNESS_BLOCK=0
          ;;
        '<!-- gstack:begin team-init'*'-->')
          BEGIN_COUNT=$(( BEGIN_COUNT + 1 ))
          BEGIN_IDX=$IDX
          ;;
        '<!-- gstack:end team-init -->')
          END_COUNT=$(( END_COUNT + 1 ))
          END_IDX=$IDX
          ;;
        *'## gstack'*)
          if [ "$IN_HARNESS_BLOCK" -eq 0 ]; then
            HAS_UNMARKED_GSTACK=1
          fi
          ;;
      esac
      IDX=$(( IDX + 1 ))
    done < "$CLAUDE_MD"
    LINE_COUNT=$IDX
  fi

  if [ "$BEGIN_COUNT" -gt 0 ] || [ "$END_COUNT" -gt 0 ]; then
    STORED_HASH=""
    if [ "$BEGIN_COUNT" -eq 1 ] && [ "$END_COUNT" -eq 1 ] && [ "$END_IDX" -gt $(( BEGIN_IDX + 1 )) ]; then
      BEGIN_CLEAN="${LINES[$BEGIN_IDX]%"$CR"}"
      case "$BEGIN_CLEAN" in
        "${MARKER_BEGIN_PREFIX}"*"${MARKER_BEGIN_SUFFIX}")
          STORED_HASH="${BEGIN_CLEAN#"$MARKER_BEGIN_PREFIX"}"
          STORED_HASH="${STORED_HASH%"$MARKER_BEGIN_SUFFIX"}"
          case "$STORED_HASH" in
            ''|*[!0-9a-f]*) STORED_HASH="" ;;
          esac
          if [ "${#STORED_HASH}" -ne 40 ] && [ "${#STORED_HASH}" -ne 64 ]; then
            STORED_HASH=""
          fi
          ;;
      esac
    fi

    if [ -z "$STORED_HASH" ]; then
      CLAUDE_ACTION="malformed"
      CLAUDE_SKIP_REASON="CLAUDE.md has incomplete or duplicate gstack team-init markers"
    else
      EXISTING_HASH=$(
        _i=$(( BEGIN_IDX + 1 ))
        while [ "$_i" -lt "$END_IDX" ]; do
          printf '%s\n' "${LINES[$_i]%"$CR"}"
          _i=$(( _i + 1 ))
        done | git -C "$REPO_ROOT" hash-object --stdin
      )
      if [ "$EXISTING_HASH" != "$STORED_HASH" ]; then
        CLAUDE_ACTION="modified"
        CLAUDE_SKIP_REASON="CLAUDE.md gstack section was modified after gstack-team-init wrote it"
      elif [ "$EXISTING_HASH" = "$SNIPPET_HASH" ]; then
        CLAUDE_ACTION="up_to_date"
      else
        CLAUDE_ACTION="update"
      fi
    fi
  elif [ "$HAS_UNMARKED_GSTACK" -eq 1 ]; then
    CLAUDE_ACTION="unmarked"
    CLAUDE_SKIP_REASON="CLAUDE.md already has an unmarked gstack section"
  fi
fi

CLAUDE_TMP=""
OPT_SETTINGS_BAK=""
cleanup_temps() {
  if [ -n "${CLAUDE_TMP:-}" ] && [ -f "$CLAUDE_TMP" ]; then
    rm -f "$CLAUDE_TMP" 2>/dev/null || true
  fi
  if [ -n "${OPT_SETTINGS_BAK:-}" ] && [ -f "$OPT_SETTINGS_BAK" ]; then
    rm -f "$OPT_SETTINGS_BAK" 2>/dev/null || true
  fi
}
trap cleanup_temps EXIT

restore_opt_settings() {
  if [ -n "${OPT_SETTINGS_BAK:-}" ] && [ -f "$OPT_SETTINGS_BAK" ] && [ -n "${OPT_SETTINGS:-}" ]; then
    if mv -f "$OPT_SETTINGS_BAK" "$OPT_SETTINGS" 2>/dev/null; then
      OPT_SETTINGS_BAK=""
      echo "  Restored .claude/settings.json to its previous contents." >&2
    else
      echo "Warning: could not restore .claude/settings.json from $OPT_SETTINGS_BAK." >&2
    fi
  fi
}

stage_claude_update() {
  if [ -n "$CLAUDE_TMP" ]; then
    return 0
  fi
  if ! command -v mktemp >/dev/null 2>&1 || ! command -v mv >/dev/null 2>&1; then
    echo "Error: cannot update CLAUDE.md safely without mktemp and mv; leaving CLAUDE.md untouched." >&2
    return 1
  fi
  CLAUDE_TMP=$(mktemp "${CLAUDE_MD}.XXXXXX" 2>/dev/null || echo "")
  if [ -z "$CLAUDE_TMP" ]; then
    echo "Error: could not create temporary file next to CLAUDE.md; leaving CLAUDE.md untouched." >&2
    return 1
  fi
  if ! (
    if [ "$CLAUDE_ACTION" = "append" ]; then
      _i=0
      while [ "$_i" -lt "$LINE_COUNT" ]; do
        if [ "$_i" -eq $(( LINE_COUNT - 1 )) ] && [ "$ENDED_WITH_NL" -eq 0 ]; then
          printf '%s' "${LINES[$_i]}" || exit 1
        else
          printf '%s\n' "${LINES[$_i]}" || exit 1
        fi
        _i=$(( _i + 1 ))
      done
      if [ "$CLAUDE_EXISTED" -eq 1 ] && [ -s "$CLAUDE_MD" ]; then
        if [ "$ENDED_WITH_NL" -eq 0 ]; then
          printf '\n\n' || exit 1
        else
          printf '\n' || exit 1
        fi
      fi
      printf '%s\n%s\n%s\n' "$BLOCK_BEGIN" "$SNIPPET" "$MARKER_END" || exit 1
    else
      _i=0
      while [ "$_i" -lt "$BEGIN_IDX" ]; do
        printf '%s\n' "${LINES[$_i]}" || exit 1
        _i=$(( _i + 1 ))
      done
      printf '%s\n%s\n%s\n' "$BLOCK_BEGIN" "$SNIPPET" "$MARKER_END" || exit 1
      _i=$(( END_IDX + 1 ))
      while [ "$_i" -lt "$LINE_COUNT" ]; do
        if [ "$_i" -eq $(( LINE_COUNT - 1 )) ] && [ "$ENDED_WITH_NL" -eq 0 ]; then
          printf '%s' "${LINES[$_i]}" || exit 1
        else
          printf '%s\n' "${LINES[$_i]}" || exit 1
        fi
        _i=$(( _i + 1 ))
      done
    fi
  ) > "$CLAUDE_TMP"; then
    echo "Error: could not write updated CLAUDE.md temporary file; leaving CLAUDE.md untouched." >&2
    if [ -f "$CLAUDE_TMP" ]; then
      rm -f "$CLAUDE_TMP" 2>/dev/null || true
    fi
    CLAUDE_TMP=""
    return 1
  fi
  if [ "$CLAUDE_EXISTED" -eq 1 ]; then
    _CLAUDE_MODE=$(stat -c '%a' "$CLAUDE_MD" 2>/dev/null || stat -f '%Lp' "$CLAUDE_MD" 2>/dev/null || echo "")
    [ -n "$_CLAUDE_MODE" ] && chmod "$_CLAUDE_MODE" "$CLAUDE_TMP" 2>/dev/null || true
  else
    _UMASK=$(umask)
    _NEW_MODE=$(printf '%o' $(( 0666 & ~8#${_UMASK} )) 2>/dev/null || echo "")
    [ -n "$_NEW_MODE" ] && chmod "$_NEW_MODE" "$CLAUDE_TMP" 2>/dev/null || true
  fi
  return 0
}

commit_claude_staged() {
  if [ -L "$CLAUDE_MD" ]; then
    echo "Error: CLAUDE.md became a symlink while gstack-team-init was running; aborting without replacing it." >&2
    restore_opt_settings
    return 1
  fi
  if [ "$CLAUDE_EXISTED" -eq 1 ]; then
    _CUR_HASH=$(git -C "$REPO_ROOT" hash-object "$CLAUDE_MD" 2>/dev/null || echo "")
    if [ "$_CUR_HASH" != "$CLAUDE_PRE_HASH" ]; then
      echo "Error: CLAUDE.md changed while gstack-team-init was running; aborting without overwriting concurrent edits." >&2
      restore_opt_settings
      return 1
    fi
  elif [ -e "$CLAUDE_MD" ]; then
    echo "Error: CLAUDE.md appeared while gstack-team-init was running; aborting without overwriting it." >&2
    restore_opt_settings
    return 1
  fi
  if ! mv -f "$CLAUDE_TMP" "$CLAUDE_MD"; then
    echo "Error: could not install staged CLAUDE.md; aborting." >&2
    restore_opt_settings
    return 1
  fi
  CLAUDE_TMP=""
  if [ -n "${OPT_SETTINGS_BAK:-}" ] && [ -f "$OPT_SETTINGS_BAK" ]; then
    rm -f "$OPT_SETTINGS_BAK" 2>/dev/null || true
  fi
  OPT_SETTINGS_BAK=""
  return 0
}

# ── Optional mode: clean up required-mode enforcement hook first ─
# Preflight CLAUDE.md above, stage its replacement temp file, AND update
# .claude/settings.json (saving a rollback copy) before committing CLAUDE.md so
# a downgrade never splits CLAUDE.md and .claude/settings.json into
# half-required / half-optional. Defer unlinking check-gstack.cjs until both
# mode-defining files are committed, and keep cleanup failure non-fatal.
OPT_HOOKS_DIR="$REPO_ROOT/.claude/hooks"
OPT_SETTINGS="$REPO_ROOT/.claude/settings.json"
REMOVED_CJS_REG=0
REMOVED_SH_REG=0
if [ "$MODE" = "optional" ]; then
  if [ -f "$OPT_SETTINGS" ] && grep -q 'check-gstack' "$OPT_SETTINGS" 2>/dev/null; then
    if ! command -v bun >/dev/null 2>&1; then
      echo "Error: cannot switch from required to optional mode without bun to remove the check-gstack hook from .claude/settings.json." >&2
      echo "  Install bun or remove the check-gstack PreToolUse entry from .claude/settings.json, then re-run." >&2
      exit 1
    fi
    if [ "$CLAUDE_ACTION" = "update" ] || [ "$CLAUDE_ACTION" = "append" ]; then
      stage_claude_update || exit 1
    fi
    OPT_SETTINGS_OUT=""
    OPT_SETTINGS_RC=0
    OPT_SETTINGS_OUT=$(GSTACK_SETTINGS_PATH="$OPT_SETTINGS" GSTACK_HOOK_COMMAND="$HOOK_COMMAND" GSTACK_REPO_ROOT="$REPO_ROOT" GSTACK_CLAUDE_ACTION="$CLAUDE_ACTION" GSTACK_CLAUDE_SKIP_REASON="$CLAUDE_SKIP_REASON" bun --no-env-file --config="${GSTACK_BUN_CONFIG:-/dev/null}" -e '
      const crypto = require("crypto");
      const fs = require("fs");
      const path = require("path");
      const settingsPath = process.env.GSTACK_SETTINGS_PATH;
      const expectedCjs = process.env.GSTACK_HOOK_COMMAND;
      const repoRoot = process.env.GSTACK_REPO_ROOT;
      const claudeAction = process.env.GSTACK_CLAUDE_ACTION || "";
      const claudeSkipReason = process.env.GSTACK_CLAUDE_SKIP_REASON || "";
      const legacySh = new Set([
        "\"$CLAUDE_PROJECT_DIR/.claude/hooks/check-gstack.sh\"",
        "bash \"$CLAUDE_PROJECT_DIR/.claude/hooks/check-gstack.sh\"",
        ".claude/hooks/check-gstack.sh",
      ]);
      const hasCheckGstackInHooks = hooks => {
        if (!hooks || typeof hooks !== "object" || Array.isArray(hooks)) return false;
        return Object.values(hooks).some(
          entries => Array.isArray(entries) && JSON.stringify(entries).includes("check-gstack")
        );
      };
      const rawSettings = fs.readFileSync(settingsPath);
      const origMode = fs.statSync(settingsPath).mode & 0o777;
      const settings = JSON.parse(rawSettings.toString("utf8"));
      if (!settings || typeof settings !== "object" || Array.isArray(settings)) {
        throw new Error("settings.json root is not an object");
      }
      if (!hasCheckGstackInHooks(settings.hooks)) {
        process.stdout.write("NONE\n");
        process.exit(0);
      }
      const realRepo = fs.realpathSync(repoRoot);
      const repoPrefix = realRepo.endsWith(path.sep) ? realRepo : realRepo + path.sep;
      const settingsLstat = fs.lstatSync(settingsPath);
      const realSettings = fs.realpathSync(settingsPath);
      const realSettingsParent = fs.realpathSync(path.dirname(settingsPath));
      const insideRepo = p => p === realRepo || p.startsWith(repoPrefix);
      if (settingsLstat.isSymbolicLink() || !realSettings.startsWith(repoPrefix) || !insideRepo(realSettingsParent)) {
        process.stderr.write("Error: .claude/settings.json is a symlink or resolves outside the repository; remove the check-gstack hook manually before switching to optional mode.\n");
        process.exit(4);
      }
      if (["symlink", "malformed", "modified", "unmarked"].includes(claudeAction)) {
        process.stderr.write("Error: cannot switch from required to optional mode because " + claudeSkipReason + ".\n");
        process.stderr.write("  Remove or update the required gstack section in CLAUDE.md (or remove the check-gstack hook manually), then re-run.\n");
        process.exit(3);
      }
      const isCjs = h => h && h.type === "command" && h.command === expectedCjs;
      const isSh = h => h && h.type === "command" && legacySh.has(h.command);
      let removedCjs = 0;
      let removedSh = 0;
      if (settings.hooks && Array.isArray(settings.hooks.PreToolUse)) {
        settings.hooks.PreToolUse = settings.hooks.PreToolUse.filter(entry => {
          if (!entry || (entry.matcher !== "Skill" && entry.matcher !== "Skill|skill")) return true;
          if (!Array.isArray(entry.hooks)) return true;
          entry.hooks = entry.hooks.filter(h => {
            if (isCjs(h)) { removedCjs++; return false; }
            if (isSh(h)) { removedSh++; return false; }
            return true;
          });
          return entry.hooks.length > 0;
        });
        if (settings.hooks.PreToolUse.length === 0) delete settings.hooks.PreToolUse;
        if (Object.keys(settings.hooks).length === 0) delete settings.hooks;
      }
      if (hasCheckGstackInHooks(settings.hooks)) {
        process.stderr.write("Error: custom check-gstack hook registration remains in .claude/settings.json; remove it manually before switching to optional mode.\n");
        process.exit(2);
      }
      if (removedCjs > 0 || removedSh > 0) {
        const dir = path.dirname(settingsPath);
        const bak = path.join(dir, ".settings." + process.pid + "." + crypto.randomBytes(6).toString("hex") + ".bak");
        const tmp = path.join(dir, ".settings." + process.pid + "." + crypto.randomBytes(6).toString("hex") + ".tmp");
        let bakCreated = false;
        let tmpCreated = false;
        try {
          const bakFd = fs.openSync(bak, "wx", origMode);
          bakCreated = true;
          try {
            fs.writeFileSync(bakFd, rawSettings);
            fs.fchmodSync(bakFd, origMode);
          } finally {
            fs.closeSync(bakFd);
          }
          const fd = fs.openSync(tmp, "wx", origMode);
          tmpCreated = true;
          try {
            fs.writeFileSync(fd, JSON.stringify(settings, null, 2) + "\n", "utf8");
            fs.fchmodSync(fd, origMode);
          } finally {
            fs.closeSync(fd);
          }
          fs.renameSync(tmp, settingsPath);
          tmpCreated = false;
          bakCreated = false;
        } finally {
          if (tmpCreated) { try { fs.unlinkSync(tmp); } catch {} }
          if (bakCreated) { try { fs.unlinkSync(bak); } catch {} }
        }
        process.stdout.write("REMOVED:" + (removedCjs > 0 ? "1" : "0") + ":" + (removedSh > 0 ? "1" : "0") + "\n");
        process.stdout.write("BAK:" + bak + "\n");
      } else {
        process.stdout.write("NONE\n");
      }
    ') || OPT_SETTINGS_RC=$?
    if [ "$OPT_SETTINGS_RC" -eq 0 ]; then
      OPT_SETTINGS_STATUS=""
      while IFS= read -r _line; do
        case "$_line" in
          REMOVED:*|NONE) OPT_SETTINGS_STATUS="$_line" ;;
          BAK:*) OPT_SETTINGS_BAK="${_line#BAK:}" ;;
        esac
      done <<< "$OPT_SETTINGS_OUT"
      case "$OPT_SETTINGS_STATUS" in
        REMOVED:1:1) REMOVED_CJS_REG=1; REMOVED_SH_REG=1 ;;
        REMOVED:1:0) REMOVED_CJS_REG=1 ;;
        REMOVED:0:1) REMOVED_SH_REG=1 ;;
      esac
      if [ "$REMOVED_CJS_REG" = 1 ] || [ "$REMOVED_SH_REG" = 1 ]; then
        GENERATED+=(".claude/settings.json")
        echo "  - .claude/settings.json — removed check-gstack PreToolUse hook"
      fi
    elif [ "$OPT_SETTINGS_RC" -eq 3 ] || [ "$OPT_SETTINGS_RC" -eq 4 ]; then
      exit 1
    else
      echo "Error: could not update .claude/settings.json to remove the check-gstack hook; aborting before updating CLAUDE.md." >&2
      exit 1
    fi
  fi
fi

# ── Apply preflighted CLAUDE.md action ─────────────────────────

case "$CLAUDE_ACTION" in
  symlink)
    echo "CLAUDE.md is a symlink. Skipping CLAUDE.md update to preserve the link."
    echo "  Update its target file manually if you want a gstack section there."
    ;;
  malformed)
    echo "CLAUDE.md has incomplete or duplicate gstack team-init markers. Skipping CLAUDE.md update."
    echo "  Fix or remove the <!-- gstack:begin team-init ... --> / <!-- gstack:end team-init --> lines and re-run."
    ;;
  modified)
    echo "CLAUDE.md gstack section was modified after gstack-team-init wrote it. Skipping CLAUDE.md update."
    echo "  To replace it, remove the lines from <!-- gstack:begin team-init ... --> through <!-- gstack:end team-init --> and re-run."
    ;;
  up_to_date)
    echo "CLAUDE.md gstack section is already up to date."
    ;;
  unmarked)
    echo "CLAUDE.md already has an unmarked gstack section. Skipping CLAUDE.md update."
    echo "  To replace it with a managed section, remove the existing ## gstack section and re-run."
    ;;
  update)
    stage_claude_update || exit 1
    commit_claude_staged || exit 1
    GENERATED+=("CLAUDE.md")
    echo "  ~ CLAUDE.md — updated gstack $MODE section"
    ;;
  append)
    if [ -n "$CLAUDE_TMP" ]; then
      commit_claude_staged || exit 1
    else
      {
        if [ -f "$CLAUDE_MD" ] && [ -s "$CLAUDE_MD" ]; then
          if [ "$ENDED_WITH_NL" -eq 0 ]; then
            printf '\n\n'
          else
            printf '\n'
          fi
        fi
        printf '%s\n%s\n%s\n' "$BLOCK_BEGIN" "$SNIPPET" "$MARKER_END"
      } >> "$CLAUDE_MD"
    fi
    GENERATED+=("CLAUDE.md")
    echo "  + CLAUDE.md — added gstack $MODE section"
    ;;
esac

# Clean up .claude/settings.json rollback backup if CLAUDE.md was already up_to_date.
if [ -n "${OPT_SETTINGS_BAK:-}" ] && [ -f "$OPT_SETTINGS_BAK" ]; then
  rm -f "$OPT_SETTINGS_BAK" 2>/dev/null || true
  OPT_SETTINGS_BAK=""
fi

# ── Optional mode: remove unmodified in-repo hook script after commit ─
if [ "$MODE" = "optional" ]; then
  if [ "$REMOVED_CJS_REG" = 1 ] && [ -f "$OPT_HOOKS_DIR/check-gstack.cjs" ] && [ ! -L "$OPT_HOOKS_DIR/check-gstack.cjs" ]; then
    HOOK_CHECK_RC=0
    GSTACK_TEAM_INIT_SRC="${BASH_SOURCE[0]}" GSTACK_HOOK_FILE="$OPT_HOOKS_DIR/check-gstack.cjs" GSTACK_REPO_ROOT="$REPO_ROOT" bun --no-env-file --config="${GSTACK_BUN_CONFIG:-/dev/null}" -e '
      const fs = require("fs");
      const path = require("path");
      let realRepo;
      let realHook;
      try {
        realRepo = fs.realpathSync(process.env.GSTACK_REPO_ROOT);
        realHook = fs.realpathSync(process.env.GSTACK_HOOK_FILE);
      } catch {
        process.exit(1);
      }
      const repoPrefix = realRepo.endsWith(path.sep) ? realRepo : realRepo + path.sep;
      if (!realHook.startsWith(repoPrefix)) {
        process.exit(2);
      }
      const src = fs.readFileSync(process.env.GSTACK_TEAM_INIT_SRC, "utf8");
      const endTok = "HOOK" + "_EOF";
      const startMark = "cat > " + String.fromCharCode(34) + "$HOOKS_DIR/check-gstack.cjs" + String.fromCharCode(34) + " << " + String.fromCharCode(39) + endTok + String.fromCharCode(39) + "\n";
      const i = src.indexOf(startMark);
      const j = i >= 0 ? src.indexOf("\n" + endTok + "\n", i) : -1;
      const expected = (i >= 0 && j > i) ? src.slice(i + startMark.length, j + 1) : "";
      const actual = fs.readFileSync(realHook, "utf8");
      process.exit(expected !== "" && actual === expected ? 0 : 1);
    ' || HOOK_CHECK_RC=$?
    if [ "$HOOK_CHECK_RC" -eq 0 ]; then
      if rm -f "$OPT_HOOKS_DIR/check-gstack.cjs" 2>/dev/null; then
        git -C "$REPO_ROOT" ls-files --error-unmatch -- ".claude/hooks/check-gstack.cjs" >/dev/null 2>&1 \
          && GENERATED+=(".claude/hooks/check-gstack.cjs") || true
        echo "  - .claude/hooks/check-gstack.cjs — removed required-mode enforcement hook"
      else
        echo "  ! .claude/hooks/check-gstack.cjs could not be removed — delete manually (registration already removed from .claude/settings.json)"
      fi
    elif [ "$HOOK_CHECK_RC" -eq 2 ]; then
      echo "  ! .claude/hooks/check-gstack.cjs resolves outside the repository — kept on disk (registration removed from .claude/settings.json)"
    else
      echo "  ! .claude/hooks/check-gstack.cjs was customized — kept on disk (registration removed from .claude/settings.json)"
    fi
  fi
  if [ "$REMOVED_SH_REG" = 1 ] && [ -e "$OPT_HOOKS_DIR/check-gstack.sh" ]; then
    echo "  ! .claude/hooks/check-gstack.sh — left on disk (registration removed from .claude/settings.json; delete manually if unused)"
  fi
fi
# ── Required mode: enforcement hook ────────────────────────────

if [ "$MODE" = "required" ]; then
  HOOKS_DIR="$REPO_ROOT/.claude/hooks"
  SETTINGS="$REPO_ROOT/.claude/settings.json"

  # Create the enforcement hook. Claude Code and Copilot CLI may run hook
  # commands through sh, cmd.exe or PowerShell, so the hook is CommonJS run by
  # node, and the registered command holds no shell variable syntax: it reads
  # CLAUDE_PROJECT_DIR through process.env. `.cjs` keeps a project's
  # package.json "type" from changing how node loads it.
  mkdir -p "$HOOKS_DIR"
  cat > "$HOOKS_DIR/check-gstack.cjs" << 'HOOK_EOF'
'use strict';
// Block skill usage when gstack is not installed globally.
//
// Resolve the install root the way gstack skill preambles do: the GSTACK_ROOT
// env var first, then every host's global install location, then the migrated
// repo location. Block only when NONE exist (#2500 — hardcoding
// ~/.claude/skills/gstack false-blocked Codex-host and migrated-repo installs).
const fs = require('fs');
const os = require('os');
const path = require('path');

const home = process.env.HOME || process.env.USERPROFILE || os.homedir();
const roots = [process.env.GSTACK_ROOT || ''].concat([
  '.claude/skills/gstack', '.codex/skills/gstack', '.factory/skills/gstack', '.kiro/skills/gstack',
  '.config/opencode/skills/gstack', '.slate/skills/gstack', '.cursor/skills/gstack', '.openclaw/skills/gstack',
  '.hermes/skills/gstack', '.gbrain/skills/gstack', '.copilot/skills/gstack', '.gemini/antigravity-cli/skills/gstack', '.gemini/skills/gstack', '.gstack/repos/gstack',
].map((rel) => path.join(home, rel)));
const gstackRoot = roots.find((root) => {
  try { return root !== '' && fs.statSync(path.join(root, 'bin')).isDirectory(); } catch { return false; }
});

if (gstackRoot) {
  process.stdout.write('{}\n');
} else {
  process.stderr.write(`BLOCKED: gstack is not installed globally.

gstack is required for AI-assisted work in this repo.

Install it:
  git clone --depth 1 https://github.com/garrytan/gstack.git ~/.claude/skills/gstack
  cd ~/.claude/skills/gstack && ./setup --team

Then restart your AI coding tool.
`);
  // Exit 2 denies on Claude Code (#2413) and on Copilot CLI, which treats a
  // preToolUse exit 2 as deny (#2229).
  process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny',
    permissionDecisionReason: 'gstack is required but not installed. See stderr for install instructions.' } }) + '\n');
  process.exitCode = 2;
}
HOOK_EOF
  chmod +x "$HOOKS_DIR/check-gstack.cjs"
  GENERATED+=(".claude/hooks/check-gstack.cjs")
  echo "  + .claude/hooks/check-gstack.cjs — enforcement hook"

  # Add hook to project-level settings.json. The command exits 0 (allow) or
  # 2 (deny) only when node runs check-gstack.cjs. Without node the shell exits
  # 127, and a require error exits 1; Claude Code treats any other exit as a
  # non-blocking error and lets the Skill call through, so the handler is
  # registered with onFailure: block (Claude Code 2.1.295+) to fail closed
  # (#3319). Older Claude Code ignores the field and keeps the old behavior.
  if ! command -v bun >/dev/null 2>&1; then
    echo "  ! bun not found — manually add this PreToolUse hook (matcher Skill|skill, \"onFailure\": \"block\") to .claude/settings.json:"
    echo "    $HOOK_COMMAND"
  elif GSTACK_SETTINGS_PATH="$SETTINGS" GSTACK_HOOK_COMMAND="$HOOK_COMMAND" bun --no-env-file --config="${GSTACK_BUN_CONFIG:-/dev/null}" -e "
      const crypto = require('crypto');
      const fs = require('fs');
      const path = require('path');
      const settingsPath = process.env.GSTACK_SETTINGS_PATH;
      const handler = { type: 'command', command: process.env.GSTACK_HOOK_COMMAND, onFailure: 'block' };

      let settings = {};
      let origMode = null;
      try {
        origMode = fs.statSync(settingsPath).mode & 0o777;
        settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
      } catch (e) {
        if (!e || e.code !== 'ENOENT') throw e;
      }
      if (!settings || typeof settings !== 'object' || Array.isArray(settings)) {
        throw new Error('settings.json root is not an object');
      }

      if (!settings.hooks) settings.hooks = {};
      if (!settings.hooks.PreToolUse) settings.hooks.PreToolUse = [];

      // Claude Code's skill tool is Skill; Copilot CLI's is skill, which no
      // Claude tool name maps to, so a bare 'Skill' never fired there (#2229).
      // A registration an older team-init wrote (the .sh hook, matcher Skill)
      // is replaced in place: exactly one check-gstack handler remains, and
      // unrelated hooks in the same entry are kept. Re-running upgrades a
      // handler registered without onFailure.
      const MATCHER = 'Skill|skill';
      const isOurs = h => h && typeof h.command === 'string' && h.command.includes('check-gstack');
      let placed = false;
      settings.hooks.PreToolUse = settings.hooks.PreToolUse.filter(entry => {
        if (entry.matcher !== 'Skill' && entry.matcher !== MATCHER) return true;
        if (!Array.isArray(entry.hooks) || !entry.hooks.some(isOurs)) return true;
        entry.matcher = MATCHER;
        const kept = [];
        for (const h of entry.hooks) {
          if (!isOurs(h)) kept.push(h);
          else if (!placed) { kept.push({ ...handler }); placed = true; }
        }
        entry.hooks = kept;
        return kept.length > 0;
      });
      if (!placed) settings.hooks.PreToolUse.push({ matcher: MATCHER, hooks: [{ ...handler }] });

      const tmp = path.join(path.dirname(settingsPath), '.settings.' + process.pid + '.' + crypto.randomBytes(6).toString('hex') + '.tmp');
      let created = false;
      try {
        const fd = fs.openSync(tmp, 'wx', origMode !== null ? origMode : 0o666);
        created = true;
        try {
          fs.writeFileSync(fd, JSON.stringify(settings, null, 2) + '\n', 'utf8');
          if (origMode !== null) fs.fchmodSync(fd, origMode);
        } finally {
          fs.closeSync(fd);
        }
        fs.renameSync(tmp, settingsPath);
        created = false;
      } finally {
        if (created) { try { fs.unlinkSync(tmp); } catch {} }
      }
    "; then
    GENERATED+=(".claude/settings.json")
    echo "  + .claude/settings.json — PreToolUse hook registered"
    # The bash hook an older team-init wrote goes only once its replacement is
    # registered; a tracked one is staged as a deletion by the git add below.
    if [ -e "$HOOKS_DIR/check-gstack.sh" ]; then
      rm -f "$HOOKS_DIR/check-gstack.sh"
      git -C "$REPO_ROOT" ls-files --error-unmatch -- .claude/hooks/check-gstack.sh >/dev/null 2>&1 \
        && GENERATED+=(".claude/hooks/check-gstack.sh")
      echo "  - .claude/hooks/check-gstack.sh — replaced by check-gstack.cjs"
    fi
  else
    echo "  ! could not update .claude/settings.json — add this PreToolUse hook (matcher Skill|skill, \"onFailure\": \"block\") manually:"
    echo "    $HOOK_COMMAND"
  fi
fi

# ── Summary ────────────────────────────────────────────────────

echo ""
echo "Team mode ($MODE) initialized."
echo ""
if [ ${#GENERATED[@]} -gt 0 ]; then
  echo "Commit the generated files:"
  echo "  git add ${GENERATED[*]}"
  echo "  git commit -m \"chore: require gstack for AI-assisted work\""
fi
echo ""
echo "Each developer then runs:"
echo "  git clone --depth 1 https://github.com/garrytan/gstack.git ~/.claude/skills/gstack"
echo "  cd ~/.claude/skills/gstack && ./setup --team"
if [ "$MODE" = "required" ]; then
  echo ""
  echo "The Skill gate runs on Node.js and blocks when it cannot run, so every"
  echo "developer also needs node on PATH and Claude Code 2.1.295 or later."
  echo "Older Claude Code ignores onFailure: without node there, skills are not blocked."
fi
