#!/usr/bin/env bash
# init — set up a fresh copy of this control plane on a machine.
#
# Two ways in, same result:
#   a person:  lane init                      (asks what it needs)
#   Claude:    lane init --owner "Sam" --yes  (asks nothing)
#
# Safe to run again. It never overwrites something you already have; it fills in what is missing
# and tells you which is which.
set -u

# Resolve through symlinks: `lane` is normally invoked via a link on your PATH, and the scripts it
# runs live next to the real file, not next to the link.
_self="${BASH_SOURCE[0]:-$0}"
while [ -L "$_self" ]; do
  _l=$(readlink "$_self")
  case "$_l" in /*) _self="$_l" ;; *) _self="$(dirname "$_self")/$_l" ;; esac
done
# PRODUCT ships the templates and scripts; AD is the workspace being set up (the same split as scripts/lib.sh,
# which init cannot source: it runs before a plane has a registry).
PRODUCT="${LANE_PRODUCT:-$(cd "$(dirname "$_self")/.." && pwd)}"
AD="${LANE_WORKSPACE:-$PRODUCT}"
CLAUDE_HOME="${CLAUDE_HOME:-$HOME/.claude}"
OWNER=""; TRACKER=""; ASSUME_YES=0; CHECK_ONLY=0; DELETE_SESSIONS_ON_DONE=""; SYNC_DAYS=""; PRIVATE=""; PRIVATE_EXPLICIT=0

while [ $# -gt 0 ]; do
  case "$1" in
    --owner) OWNER="${2:-}"; shift 2 ;;
    --tracker) TRACKER="${2:-}"; shift 2 ;;   # full URL with {key}, or: jira:<site> linear:<lane> github:<owner/repo>
    --jira)    TRACKER="https://${2:-}.atlassian.net/browse/{key}"; shift 2 ;;
    --linear)  TRACKER="https://linear.app/${2:-}/issue/{key}"; shift 2 ;;
    --github)  TRACKER="https://github.com/${2:-}/issues/{key}"; shift 2 ;;
    --claude-home) CLAUDE_HOME="${2:-}"; shift 2 ;;
    --delete-sessions-on-done) DELETE_SESSIONS_ON_DONE="${2:-}"; shift 2 ;;
    --sync-days) SYNC_DAYS="${2:-}"; shift 2 ;;
    --private) PRIVATE=true; PRIVATE_EXPLICIT=1; shift ;;
    --public) PRIVATE=false; PRIVATE_EXPLICIT=1; shift ;;
    --yes|-y) ASSUME_YES=1; shift ;;
    --check) CHECK_ONLY=1; shift ;;
    -h|--help) sed -n '2,12p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
    *) echo "init: unknown option $1" >&2; exit 2 ;;
  esac
done

# pick <prompt> <option>…  — arrow keys and Enter, with a typed fallback when there is no terminal
# (piped input, CI, or Claude running this). Everything it draws goes to stderr; only the chosen
# number comes back on stdout.
pick(){
  local prompt="$1"; shift
  local n=$#; local i cur=0 key rest
  local opts=("$@")
  # stdout is a pipe here (pick is always called inside $(...)), so the terminal test is on
  # stdin, where keys come from, and stderr, where the list is drawn.
  if [ ! -t 0 ] || [ ! -t 2 ]; then          # no terminal: ask for a number instead
    printf '%s\n' "$prompt" >&2
    i=0; while [ $i -lt $n ]; do printf '  %d  %s\n' $((i+1)) "${opts[$i]}" >&2; i=$((i+1)); done
    printf '  choose [1-%d]: ' "$n" >&2
    read -r key || true
    case "$key" in ''|*[!0-9]*) key=$n ;; esac
    [ "$key" -ge 1 ] 2>/dev/null && [ "$key" -le $n ] || key=$n
    printf '%s' "$key"; return
  fi
  printf '%s\n' "$prompt" >&2
  printf '\033[?25l' >&2                      # hide the cursor while we redraw
  trap 'printf "\033[?25h" >&2' EXIT INT TERM
  local drawn=0
  while :; do
    [ $drawn = 1 ] && printf '\033[%dA' "$n" >&2
    i=0
    while [ $i -lt $n ]; do
      if [ $i = $cur ]; then printf '\033[2K  \033[36m❯\033[0m \033[1m%s\033[0m\n' "${opts[$i]}" >&2
      else                   printf '\033[2K    \033[2m%s\033[0m\n' "${opts[$i]}" >&2; fi
      i=$((i+1))
    done
    drawn=1
    IFS= read -rsn1 key || break
    if [ "$key" = $'\033' ]; then read -rsn2 -t 1 rest 2>/dev/null; key="$key$rest"; fi
    case "$key" in
      $'\033[A'|k) cur=$(( (cur - 1 + n) % n )) ;;
      $'\033[B'|j) cur=$(( (cur + 1) % n )) ;;
      '') break ;;                            # Enter
      q) cur=$((n-1)); break ;;
    esac
  done
  printf '\033[?25h' >&2
  trap - EXIT INT TERM
  printf '%s' "$((cur+1))"
}

G=$'\e[32m'; Y=$'\e[33m'; R=$'\e[31m'; D=$'\e[2m'; N=$'\e[0m'
ok(){   printf "  ${G}ok${N}    %s\n" "$1"; }
made(){ printf "  ${G}made${N}  %s\n" "$1"; }
kept(){ printf "  ${D}kept${N}  %s ${D}(already there)${N}\n" "$1"; }
warn(){ printf "  ${Y}warn${N}  %s\n" "$1"; }
bad(){  printf "  ${R}miss${N}  %s\n" "$1"; }

# ---------------------------------------------------------------- 1. prerequisites
missing=0
echo "Checking what this needs:"
for c in git python3; do
  if command -v "$c" >/dev/null 2>&1; then ok "$c"; else bad "$c — required"; missing=1; fi
done
if command -v gh >/dev/null 2>&1; then
  if gh auth status >/dev/null 2>&1; then ok "gh (signed in)"
  else warn "gh is installed but not signed in — run: gh auth login"; fi
else
  warn "gh not found — pull request status and lane-gh will not work"
fi
command -v claude >/dev/null 2>&1 && ok "claude" || warn "claude not found — the hooks only matter inside Claude Code"
[ "$missing" = 0 ] || { echo; echo "Install the missing tools above, then run this again."; exit 1; }
[ "$CHECK_ONLY" = 1 ] && exit 0
echo

# ---------------------------------------------------------------- 2. who owns this
if [ -z "$OWNER" ] && [ -f "$AD/registry/config.yml" ]; then
  OWNER=$(sed -n 's/^[[:space:]]*name:[[:space:]]*//p' "$AD/registry/config.yml" | head -1 | tr -d '"'"'")
  [ "$OWNER" = "YOUR NAME" ] && OWNER=""
fi
if [ -z "$TRACKER" ] && [ -f "$AD/registry/config.yml" ]; then
  TRACKER=$(sed -n 's/^[[:space:]]*url:[[:space:]]*//p' "$AD/registry/config.yml" | head -1 | tr -d '"'"'")
fi
if [ -z "$PRIVATE" ] && [ -f "$AD/registry/config.yml" ]; then
  PRIVATE=$(sed -n 's/^private:[[:space:]]*//p' "$AD/registry/config.yml" | head -1 | tr -d '"'"'"' ')
fi
if [ -z "$OWNER" ]; then
  if [ "$ASSUME_YES" = 1 ]; then
    OWNER=$(git config user.name 2>/dev/null) || true
    [ -n "$OWNER" ] || OWNER="the user"
  else
    d=$(git config user.name 2>/dev/null || echo "")
    printf "Your name, used when the hooks address you%s: " "${d:+ [$d]}"
    read -r ans || true
    OWNER="${ans:-$d}"
    [ -n "$OWNER" ] || OWNER="the user"
  fi
fi

# Pick a tracker from a list rather than asking someone to remember a URL shape. We know what
# each one looks like; all we need from them is their org or workspace name.
if [ -z "$TRACKER" ] && [ "$ASSUME_YES" != 1 ]; then
  echo
  pick=$(pick "Where do ticket keys like ABC-123 link to?" \
    "Jira" "Linear" "GitHub Issues" "Azure DevOps" "something else — you paste the link" \
    "nothing — show keys as plain text")
  # the prompt goes to stderr so that $(ask ...) captures only what was typed
  ask(){ printf "  %s: " "$1" >&2; read -r REPLY_ || true; printf '%s' "$REPLY_"; }
  case "${pick:-6}" in
    1) s=$(ask "your Jira site (the bit before .atlassian.net)")
       s=${s#https://}; s=${s%%.atlassian.net*}; s=${s%%/*}
       [ -n "$s" ] && TRACKER="https://$s.atlassian.net/browse/{key}" ;;
    2) s=$(ask "your Linear workspace")
       s=${s#https://linear.app/}; s=${s%%/*}
       [ -n "$s" ] && TRACKER="https://linear.app/$s/issue/{key}" ;;
    3) s=$(ask "owner/repo, for example acme/web")
       s=${s#https://github.com/}; s=${s%/}
       [ -n "$s" ] && TRACKER="https://github.com/$s/issues/{key}" ;;
    4) s=$(ask "org/project, for example acme/platform")
       s=${s#https://dev.azure.com/}; s=${s%/}
       [ -n "$s" ] && TRACKER="https://dev.azure.com/$s/_workitems/edit/{key}" ;;
    5) TRACKER=$(ask "the link, with {key} where the key goes") ;;
    *) TRACKER="" ;;
  esac
  if [ -n "$TRACKER" ]; then
    case "$TRACKER" in *"{key}"*) : ;; *) TRACKER="${TRACKER%/}/{key}" ;; esac
    echo "  ABC-123 will link to ${TRACKER/\{key\}/ABC-123}"
  else
    echo "  ticket keys will show as plain text"
  fi
  echo
fi

# Same style as the tracker question above: a default for a later prompt, not a switch that
# skips it. `lane done` still asks every time it finds sessions to clean up — this only decides
# which answer that prompt defaults to.
if [ -z "$DELETE_SESSIONS_ON_DONE" ] && [ "$ASSUME_YES" != 1 ]; then
  pick2=$(pick "When a lane finishes, delete its Claude sessions by default, or keep them?" \
    "Keep them (default)" "Delete them")
  case "${pick2:-1}" in
    2) DELETE_SESSIONS_ON_DONE=true ;;
    *) DELETE_SESSIONS_ON_DONE=false ;;
  esac
  echo
fi
[ -n "$DELETE_SESSIONS_ON_DONE" ] || DELETE_SESSIONS_ON_DONE=false

# Same style again: a default for `lane doctor`'s advisory, not a switch that turns branch
# protection checking on or off — `lane sync` itself is always available regardless of this.
if [ -z "$SYNC_DAYS" ] && [ "$ASSUME_YES" != 1 ]; then
  pick3=$(pick "How often should lane doctor remind you to re-check GitHub branch protection?" \
    "Every 7 days (default)" "Every 30 days" "Manual only (never flag it)")
  case "${pick3:-1}" in
    2) SYNC_DAYS=30 ;;
    3) SYNC_DAYS=0 ;;
    *) SYNC_DAYS=7 ;;
  esac
  echo
fi
[ -n "$SYNC_DAYS" ] || SYNC_DAYS=7

# Same style again: this decides whether registry/repos.yaml, registry/rules.yaml and
# scripts/local/ get tracked by git (below) instead of gitignored. The gitignored default is
# right for this public template — a fork inherits whatever is committed — so it stays off
# unless someone says otherwise, here or with a fresh --private later.
if [ -z "$PRIVATE" ] && [ "$ASSUME_YES" != 1 ]; then
  pick4=$(pick "Is this control plane's own repo private (not the public Repolane template)?" \
    "No — public, or forked from the public template (default)" \
    "Yes — a private fork; track repos.yaml, rules.yaml and scripts/local/ in git")
  case "${pick4:-1}" in
    2) PRIVATE=true ;;
    *) PRIVATE=false ;;
  esac
  echo
fi
[ -n "$PRIVATE" ] || PRIVATE=false

echo "Setting up $(printf %s "$AD" | sed "s#^$HOME#~#") for $OWNER:"

# ---------------------------------------------------------------- 3. folders and files
mk_dir(){ if [ -d "$1" ]; then kept "${1#$AD/}/"; else mkdir -p "$1"; made "${1#$AD/}/"; fi; }
for d in registry/lanes memory knowledge/conventions knowledge/domains repos lanes .cache; do
  mk_dir "$AD/$d"
done

if [ -f "$AD/registry/config.yml" ] && ! grep -q "YOUR NAME" "$AD/registry/config.yml"; then
  # --private/--public on an already-initialized plane used to be silently ignored: PRIVATE was
  # computed but the config.yml-writing heredoc below only ever runs for a brand-new file. Rewrite
  # just the `private:` line in place when the flag actually asked for a change from what's there.
  if [ "$PRIVATE_EXPLICIT" = 1 ] && [ -n "$PRIVATE" ]; then
    CUR_PRIVATE=$(sed -n 's/^private:[[:space:]]*//p' "$AD/registry/config.yml" | head -1 | tr -d '"'"'"' ')
    if [ "$CUR_PRIVATE" != "$PRIVATE" ]; then
      python3 - "$AD/registry/config.yml" "$PRIVATE" <<'PY'
import re, sys
path, private = sys.argv[1:3]
text = open(path).read()
new, n = re.subn(r"(?m)^private:.*$", f"private: {private}", text, count=1)
if n == 0:
    if new and not new.endswith("\n"): new += "\n"
    new += f"\nprivate: {private}\n"
open(path, "w").write(new)
PY
      made "registry/config.yml (private: $CUR_PRIVATE -> $PRIVATE)"
    else
      kept "registry/config.yml"
    fi
  else
    kept "registry/config.yml"
  fi
else
  cat > "$AD/registry/config.yml" <<EOT
# Who this control plane belongs to, and how it should talk to them.
# This is the only file that needs editing when someone else adopts the system.
owner:
  # Named in hook messages and agent prompts: "ask <name> first", "work <name> asked for".
  name: $OWNER

tracker:
  # Where a ticket key links to. {key} is replaced with the key found in a lane's
  # \`ticket:\` field, or at the front of its id (ABC-123-short-name -> ABC-123).
  # Blank means keys show as plain text instead of links.
  url: $TRACKER

lanes:
  # A lane nobody has touched in this many days is reported as stale by \`lane doctor\`,
  # with the one command that clears it out. Nothing is ever done automatically.
  # 0 turns the check off.
  stale_days: 21
  # Default answer for the "delete this lane's Claude sessions?" prompt \`lane done\` shows when
  # it finds any. This only changes which answer the prompt defaults to — it is always asked
  # interactively, never skipped, because it is deciding whether to delete conversation history.
  delete_sessions_on_done: $DELETE_SESSIONS_ON_DONE

protection:
  # \`lane doctor\` reminds you to run \`lane sync\` for a repo whose GitHub branch protection
  # has not been checked in this many days (or never). Sync itself is always manual —
  # this only decides when the reminder shows up. 0 turns the reminder off.
  sync_days: $SYNC_DAYS

# Is THIS control plane's own repo a private fork (not the public Repolane template)? Default
# false, matching .gitignore's template-safe default. true makes \`lane init\` track
# registry/repos.yaml, registry/rules.yaml and scripts/local/ in git instead of ignoring them —
# see "Tracking your control plane's own files in a private fork" in docs/extending.md. Flip
# this and re-run \`lane init\` to apply it retroactively.
private: $PRIVATE
EOT
  made "registry/config.yml"
fi

if [ -f "$AD/registry/repos.yaml" ]; then
  kept "registry/repos.yaml"
else
  cat > "$AD/registry/repos.yaml" <<'EOT'
# Source of truth for what this control plane manages. Paths are relative to this folder.
# Add repos with:  lane add <git-url> [name]
# status: active | archived
repos:
EOT
  made "registry/repos.yaml"
fi

if [ -f "$AD/memory/MEMORY.md" ]; then
  kept "memory/MEMORY.md"
else
  printf '# Memory Index — applies everywhere (per-repo memory lives in the subfolders)\n' > "$AD/memory/MEMORY.md"
  made "memory/MEMORY.md"
fi

if [ -f "$AD/knowledge/preferences.md" ]; then
  kept "knowledge/preferences.md"
elif [ -f "$PRODUCT/knowledge/preferences.md.example" ]; then
  cp "$PRODUCT/knowledge/preferences.md.example" "$AD/knowledge/preferences.md"; made "knowledge/preferences.md"
fi

if [ -f "$AD/CLAUDE.md" ]; then
  kept "CLAUDE.md"
elif [ -f "$PRODUCT/CLAUDE.md.template" ]; then
  # the template's placeholder is {{owner}}; escape the name so a "/" or "&" in it cannot break the substitution
  OWNER_SED=$(printf '%s' "$OWNER" | sed 's/[\/&]/\\&/g')
  sed "s/{{owner}}/$OWNER_SED/g" "$PRODUCT/CLAUDE.md.template" > "$AD/CLAUDE.md"; made "CLAUDE.md"
fi

# ---------------------------------------------------------------- 3b. private: true tracks the files that are gitignored by default
# Read fresh off disk, not the $PRIVATE we may have just asked about — this also applies
# retroactively when someone hand-edits registry/config.yml's `private:` and re-runs lane init.
PRIVATE_CFG=$(sed -n 's/^private:[[:space:]]*//p' "$AD/registry/config.yml" 2>/dev/null | head -1 | tr -d '"'"'"' ')
case "$PRIVATE_CFG" in true) : ;; *) PRIVATE_CFG=false ;; esac
if [ -f "$AD/.gitignore" ]; then
  GI_RESULT=$(python3 - "$AD/.gitignore" "$PRIVATE_CFG" <<'PY'
import sys
path, private = sys.argv[1], sys.argv[2] == "true"

ORIG_SCRIPTS_LOCAL = "/scripts/local/\n"
PRIVATE_SCRIPTS_LOCAL = (
    "# private: true (registry/config.yml) — scripts/local/ is tracked in this fork, not ignored.\n"
)
ORIG_YAML_BLOCK = "/registry/*.yaml\n/registry/rules.yaml\n"
PRIVATE_YAML_BLOCK = (
    "# private: true (registry/config.yml) — registry/repos.yaml and registry/rules.yaml are\n"
    "# tracked in this fork, not ignored. These two stay ignored regardless of private: (lane rules\n"
    "# pull's own SHA-pinned copy, and secrets-scan dismissal bookkeeping):\n"
    "/registry/rules.shared.yaml\n"
    "/registry/secrets-ignored.yaml\n"
)

text = open(path).read()
changed = False
# Tracked separately, not just "did anything change": a hand-edited .gitignore (reworded or
# reordered from the shipped text) can make one block match and the other silently not, and a
# blanket "now tracked" message would then be a false claim for the half that didn't move.
scripts_local_ok = yaml_block_ok = False
if private:
    if ORIG_SCRIPTS_LOCAL in text:
        text = text.replace(ORIG_SCRIPTS_LOCAL, PRIVATE_SCRIPTS_LOCAL, 1); changed = True; scripts_local_ok = True
    elif PRIVATE_SCRIPTS_LOCAL in text:
        scripts_local_ok = True  # already flipped
    if ORIG_YAML_BLOCK in text:
        text = text.replace(ORIG_YAML_BLOCK, PRIVATE_YAML_BLOCK, 1); changed = True; yaml_block_ok = True
    elif PRIVATE_YAML_BLOCK in text:
        yaml_block_ok = True  # already flipped
else:
    if PRIVATE_SCRIPTS_LOCAL in text:
        text = text.replace(PRIVATE_SCRIPTS_LOCAL, ORIG_SCRIPTS_LOCAL, 1); changed = True; scripts_local_ok = True
    elif ORIG_SCRIPTS_LOCAL in text:
        scripts_local_ok = True  # already back to ignored
    if PRIVATE_YAML_BLOCK in text:
        text = text.replace(PRIVATE_YAML_BLOCK, ORIG_YAML_BLOCK, 1); changed = True; yaml_block_ok = True
    elif ORIG_YAML_BLOCK in text:
        yaml_block_ok = True  # already back to ignored
if changed:
    open(path, "w").write(text)
print(("CHANGED" if changed else "UNCHANGED") + " " +
      ("scripts_local:ok" if scripts_local_ok else "scripts_local:MISMATCH") + " " +
      ("yaml_block:ok" if yaml_block_ok else "yaml_block:MISMATCH"))
PY
)
  GI_STATE="${GI_RESULT%% *}"; GI_REST="${GI_RESULT#* }"
  case "$GI_REST" in *MISMATCH*)
    warn ".gitignore doesn't match the shipped private: block for one or both of repos.yaml/rules.yaml/scripts/local/ ($GI_REST) — it looks hand-edited; lane init left it alone rather than guess. Edit it by hand to match private: $PRIVATE_CFG."
    ;;
  esac
  if [ "$GI_STATE" = CHANGED ]; then
    if [ "$PRIVATE_CFG" = true ]; then made ".gitignore (private: true — repos.yaml, rules.yaml, scripts/local/ now tracked)"
    else made ".gitignore (private: false — repos.yaml, rules.yaml, scripts/local/ ignored again)"; fi
  else
    kept ".gitignore (already matches private: $PRIVATE_CFG)"
  fi
fi

# ---------------------------------------------------------------- 4. memory where Claude looks for it
# Claude Code keeps per-project data under ~/.claude/projects/<path with every character outside A-Za-z0-9- turned into ->.
# Pointing that folder's `memory` at ours keeps memory versioned here instead of in a cache.
# The same rule as claude_project_dir in scripts/lib.sh (init runs before a plane has a lib to source).
claude_project_dir(){ printf '%s' "$1" | LC_ALL=C sed 's#[^A-Za-z0-9-]#-#g'; }
slug=$(claude_project_dir "$AD")
proj="$CLAUDE_HOME/projects/$slug"
mkdir -p "$proj"
if [ -L "$proj/memory" ]; then
  kept "memory linked into Claude's project folder"
elif [ -d "$proj/memory" ]; then
  cp -an "$proj/memory/." "$AD/memory/" 2>/dev/null
  rm -rf "$proj/memory" && ln -s "$AD/memory" "$proj/memory"
  made "memory linked (existing notes moved in, nothing lost)"
else
  ln -s "$AD/memory" "$proj/memory"; made "memory linked into Claude's project folder"
fi

# ---------------------------------------------------------------- 4b. the status line
# The script ships, but nothing points Claude Code at it. Add it only if neither settings file
# already does, so an existing setup is never disturbed.
if ! grep -qs statusLine "$AD/.claude/settings.json" "$AD/.claude/settings.local.json" 2>/dev/null; then
  # Relative to the project folder while the product sits in it (a clone); an absolute path, naming the workspace,
  # once it lives somewhere else.
  if [ "$PRODUCT" = "$AD" ]; then sl='"$CLAUDE_PROJECT_DIR"/scripts/statusline.sh'
  else sl="LANE_PRODUCT=$(printf %q "$PRODUCT") LANE_WORKSPACE=$(printf %q "$AD") $(printf %q "$PRODUCT/scripts/statusline.sh")"; fi
  if python3 "$PRODUCT/scripts/wire-statusline.py" "$AD/.claude/settings.json" "$sl" 2>/dev/null; then
    made "status line wired into .claude/settings.json"
  else
    warn "could not wire the status line — add it by hand if you want it"
  fi
else
  kept "status line"
fi

# ---------------------------------------------------------------- 4c. don't leave the template's push remote live
# This checkout IS a git repo (docs/concepts.md — "the clone is the control plane"), and after
# `lane init` it holds real state: registry/config.yml can name a private tracker, and
# registry/old-checkouts.json can hold local filesystem paths. If `origin` still points at this
# public template, a naive `git push` from inside the control plane would publish both to it.
# Fixed the same way a reporter worked around it by hand: disable the push side of `origin`, but
# only when it still demonstrably points at the known public template — never touch a remote
# someone has already pointed somewhere of their own.
DISABLED_PUSH_SENTINEL="DISABLED-set-a-private-remote-first"
# Normalized, not a raw string enum: a trailing slash or a different case in the org name (GitHub
# itself treats both as the same repo) was confirmed to slip past an exact-match comparison,
# silently leaving push live on a remote that still is the public template.
normalize_repo_url(){
  printf '%s' "$1" | tr '[:upper:]' '[:lower:]' | sed -e 's#/*$##' -e 's#\.git$##'
}
is_known_template_url(){
  case "$(normalize_repo_url "$1")" in
    https://github.com/aj-oss-tools/repolane|git@github.com:aj-oss-tools/repolane) return 0 ;;
    *) return 1 ;;
  esac
}
if git -C "$AD" remote get-url origin >/dev/null 2>&1; then
  FETCH_URL=$(git -C "$AD" remote get-url origin 2>/dev/null || echo "")
  PUSH_URL=$(git -C "$AD" remote get-url --push origin 2>/dev/null || echo "")
  if [ "$PUSH_URL" = "$DISABLED_PUSH_SENTINEL" ]; then
    kept "origin push (already disabled — still the public template's remote)"
  elif [ "$FETCH_URL" = "$PUSH_URL" ] && is_known_template_url "$FETCH_URL"; then
    git -C "$AD" remote set-url --push origin "$DISABLED_PUSH_SENTINEL"
    warn "disabled pushing to origin (still the public template's remote) — point it at your own private repo first: git remote set-url origin <your-repo>, then git remote set-url --push origin <your-repo>"
  else
    kept "origin (already points somewhere of your own — left alone)"
  fi
fi

# the root's local settings: the lanes' folders, and lane-memory goal / draft for a session that enters a lane (lib.sh)
( source "$PRODUCT/scripts/lib.sh" && write_additional_dirs ) >/dev/null 2>&1 || true

# ---------------------------------------------------------------- 5. is the wiring intact
echo
echo "Checking the wiring:"
[ -f "$AD/.claude/settings.json" ] && ok "hooks configured (.claude/settings.json)" \
                                   || bad ".claude/settings.json is missing — hooks will not run"
if [ -x "$PRODUCT/scripts/hooks/guard-check" ] && "$PRODUCT/scripts/hooks/guard-check" >/dev/null 2>&1; then
  ok "the guard compiles and still refuses what it should"
else
  bad "the guard is not working — run: bash scripts/hooks/test-guard.sh"
fi

# ---------------------------------------------------------------- 6. what to do next
echo
n=$(sed -n 's/^  \([a-zA-Z0-9._-]*\):$/\1/p' "$AD/registry/repos.yaml" 2>/dev/null | wc -l | tr -d ' ')
if [ "$n" = 0 ]; then
  cat <<EOT
Nothing is managed yet. Bring your first repo in:

  lane add https://github.com/<org>/<repo>.git

Then start a piece of work:

  lane start <id> <repo>
  claude
EOT
else
  echo "$n repo(s) managed.  lane status  to see where things stand,  lane board  for the browser view."
fi
