#!/usr/bin/env bash
# lane — the single entry point.
#
#   lane                 what is going on right now
#   lane <command> …     everything else
#   lane help            the full list
#
# There is nothing else to learn. Every command below is one word.
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 is where Repolane's own files are (this file, scripts/, VERSION); AD is the workspace with the user's
# data. One folder in a clone; LANE_PRODUCT / LANE_WORKSPACE split them, and an installed product finds its workspace
# from the current folder (scripts/roots.sh decides all of it, for every script).
PRODUCT="${LANE_PRODUCT:-$(cd "$(dirname "$_self")" && pwd)}"
S="$PRODUCT/scripts"
# what the caller named, before the resolver below exports the workspace it found (`lane init` needs to tell them apart)
_ws_named="${LANE_WORKSPACE:-}"
source "$S/roots.sh"
# A hook runs in the session's current folder, which a cd can move; the folder the session was started in is the one
# that says which workspace it belongs to.
if { [ "${1:-}" = hook ] || [ "${1:-}" = statusline ]; } && [ -n "${CLAUDE_PROJECT_DIR:-}" ] && [ -d "$CLAUDE_PROJECT_DIR" ]; then lane_resolve_roots "$CLAUDE_PROJECT_DIR"
else lane_resolve_roots; fi
# a workspace takes the installed version's rule files (and data migrations) on the first run after an upgrade; not
# for `lane doctor`, which reports a stale workspace (and repairs it with --fix) rather than hide it, nor for the
# doctor's own probe of the hook path
# nor for `lane upgrade`, which refreshes every registered workspace itself and reports what it did
case "${1:-} ${2:-}" in "doctor "*|"upgrade "*|"hook ping") : ;; *) lane_refresh_workspace ;; esac

# the installed package (LANE_PRODUCT set by its launcher, and no git checkout of its own) as opposed to a clone: a few
# commands only make sense for one of the two
PKG=""; [ -n "${LANE_PRODUCT:-}" ] && [ ! -e "$PRODUCT/.git" ] && PKG=1

# command → implementation, and the one line shown in `lane help`
map(){ case "$1" in
  init)        echo "$S/init|set this machine up (safe to re-run)" ;;
  add)         echo "$S/lane-add|bring a repo under management: lane add <git-url> [name]" ;;
  start)       echo "$S/lane-start|start a piece of work: lane start <id> <repo> [<repo>…]" ;;
  resume)      echo "$S/lane-resume|pick work back up: lane resume <id>" ;;
  park)        echo "$S/lane-park|leave work for later: lane park <id> \"<note>\"" ;;
  done)        echo "$S/lane-done|finish and clean up: lane done <id>" ;;
  status)      echo "$S/status-all|where everything stands (fetches origin in each repo first)" ;;
  brief)       echo "$S/lane-brief|catch up on one piece of work: lane brief <id>" ;;
  board)       echo "$S/lane-board|open the board in a browser" ;;
  with)        echo "$S/lane-with|add a repo to work already started: lane with <id> <repo>" ;;
  run)         echo "$S/lane-run|run a command inside a repo: lane run <repo> <cmd…>" ;;
  gh)          echo "$S/lane-gh|GitHub inside a repo: lane gh <repo> pr create" ;;
  ref)         echo "$S/lane-ref|attach outside code or docs: lane ref <id> add <path>" ;;
  note)        echo "$S/lane-memory|write something worth remembering" ;;
  merge)       echo "$S/lane-merge|two pieces of work turned out to be one" ;;
  plan)        echo "$S/lane-merge-plan|preview a merge without doing it" ;;
  find)        echo "$S/lane-find|which lane touched this file, branch or commit: lane find <text>" ;;
  sessions)    echo "$S/sessions|past Claude conversations for a repo" ;;
  audit)       echo "$S/branch-audit|branches that look finished or stale" ;;
  workspace)   echo "$S/lane-workspace|editor workspace file for a piece of work" ;;
  env)         echo "$S/lane-env-check|check a lane's .env files are linked in: lane env [id]" ;;
  keys)        echo "$S/lane-env-keys|list the key names in an env file, never the values" ;;
  secrets)     echo "$S/repo-secrets|deny a repo's secret/credential files: lane secrets <repo> scan|add|ignore|list|ignored" ;;
  sync)        echo "$S/lane-sync|check a repo's real GitHub branch protection: lane sync [repo]" ;;
  doctor)      echo "$S/hooks/guard-check|check the safety rules are working" ;;
  rules)       echo "$S/lane-rules|shared, git-backed rules: lane rules pull|status" ;;
  upgrade)     echo "$S/lane-upgrade|upgrade Repolane: lane upgrade" ;;
  import)      echo "$S/lane-import|bring past Claude conversations in (optional)" ;;
  nested)      echo "$S/lane-nested|find and repair nested worktrees" ;;
  menu)        echo "$S/menu|the long-form menu (needs bin/ on your PATH)" ;;
  "")          echo "$S/status-all|what is going on right now" ;;
  *)           return 1 ;;
esac; }

ORDER="init add import start resume park done status brief board find with run gh ref note merge plan sessions audit workspace env keys secrets sync doctor rules upgrade nested"

usage(){
  printf '\n  \e[1mlane\e[0m — one piece of work at a time, across all your repos\n\n'
  for c in $ORDER; do
    line=$(map "$c"); printf "    \e[1m%-10s\e[0m %s\n" "$c" "${line#*|}"
  done
  if [ -n "$PKG" ]; then
    # the package is on PATH already and finds the workspace from the folder: install and use are a clone's
    printf '\n    %-10s %s\n\n' "migrate" "turn a git-clone install into a workspace: lane migrate [folder]"
  else
    printf '\n    %-10s %s\n' "install" "put lane on your PATH so it works from anywhere"
    printf '    %-10s %s\n' "migrate" "turn a git-clone install into a workspace (from the installed package): lane migrate [folder]"
    printf '    %-10s %s\n\n' "use" "switch which registered plane is active; lane use --remove <name> forgets one (stable ~/.local/bin/lane dispatcher)"
  fi
  # scripts/local/<name> (docs/extending.md): any executable there is a `lane <name>` too. Listed
  # separately, after the built-ins, so a shadowed name is never confused for one of them.
  if [ -d "$DATA/scripts/local" ]; then
    locals=""
    for f in "$DATA/scripts/local"/*; do
      [ -x "$f" ] && [ ! -d "$f" ] || continue
      locals="$locals $f"
    done
    if [ -n "$locals" ]; then
      printf '  \e[1myour commands:\e[0m\n\n'
      for f in $locals; do
        b=$(basename "$f")
        # `# lane: <one-liner>` on the script's own second line, the same convention `lane <cmd>
        # --help` already reads a usage block from — sed -n '2,/^$/p' etc.
        desc=$(sed -n '2p' "$f" 2>/dev/null)
        case "$desc" in '# lane: '*) desc="${desc#\# lane: }" ;; *) desc="" ;; esac
        # A local script can come from `lane rules pull`'s scripts.d/ (docs/extending.md) --
        # a remote source, however trusted -- so this one-liner is untrusted display text: strip
        # control/escape characters (no terminal tricks) and cap the length (no runaway lines).
        desc=$(printf '%s' "$desc" | tr -d '\000-\010\013\014\016-\037\177')
        desc=$(printf '%s' "$desc" | cut -c1-72)
        printf "    \e[1m%-10s\e[0m %s\n" "$b" "$desc"
      done
      echo
    fi
  fi
}

cmd="${1:-}"

# An installed product (LANE_PRODUCT, set by the package's launcher) makes a workspace: in the folder given, or the
# current one (scripts/workspace.py). LANE_WORKSPACE naming a folder without .repolane/ keeps the clone layout there,
# and a clone running its own files keeps its own init: both are scripts/init, unchanged.
if [ "$cmd" = init ] && [ -n "${LANE_PRODUCT:-}" ] && { [ -z "$_ws_named" ] || [ -d "$_ws_named/.repolane" ]; }; then
  shift
  exec python3 -B "$S/workspace.py" init "$@"
fi

# `lane upgrade` from an installed package upgrades the package (pipx / uv tool) and refreshes every registered workspace
# (scripts/upgrade.py); a clone's is scripts/lane-upgrade, a fast-forward of the clone.
if [ "$cmd" = upgrade ] && [ -n "${LANE_PRODUCT:-}" ] && [ ! -e "$PRODUCT/.git" ]; then
  shift
  exec python3 -B "$S/upgrade.py" "$@"
fi

# `lane migrate` turns a git-clone install into a workspace (scripts/migrate.py). It runs from the installed package, never
# from the clone it is about to take apart.
if [ "$cmd" = migrate ]; then
  shift
  [ -n "${LANE_PRODUCT:-}" ] && exec python3 -B "$S/migrate.py" "$@"
  cat >&2 <<EOT
lane migrate turns this clone into a workspace, and runs from the installed package, not from the clone itself:

  pipx install repolane        (or: uv tool install repolane)
  lane migrate $(printf %q "$AD")

If \`lane\` on your PATH is still the old router \`lane install\` wrote (~/.local/bin/lane), run the installed one by its
full path. lane migrate shows everything it would change and asks before changing anything.
EOT
  exit 2
fi

# `lane <command> --help` used to reach the script, which read it as a lane id and answered
# with something misleading ("no lane '--help'"). Answer it here instead, from the same one
# line `lane help` shows, plus the script's own usage comment.
if [ $# -ge 2 ] && { [ "$2" = "--help" ] || [ "$2" = "-h" ]; } && entry=$(map "$cmd"); then
  printf '\n  \e[1mlane %s\e[0m — %s\n\n' "$cmd" "${entry#*|}"
  # The usage block is the comment lines directly under the shebang, up to the first line that is
  # not a comment. Comments further down are for whoever maintains the script, not for the user.
  awk 'NR==1{next} /^#/{print; next} {exit}' "${entry%%|*}" | sed 's/^# \{0,1\}//' | sed 's/^/  /'
  echo
  exit 0
fi

# `lane install` and `lane use` belong to a git clone: install writes the router into ~/.local/bin that picks a clone,
# use switches between clones. The installed package is on PATH already and finds the workspace from the current folder.
if [ -n "$PKG" ] && { [ "$cmd" = install ] || [ "$cmd" = use ]; }; then
  if [ "$cmd" = install ]; then
    echo "lane install is for a git clone of Repolane (it writes a router into ~/.local/bin). The installed package already" >&2
    echo "put lane on your PATH, so there is nothing to install." >&2
  else
    echo "lane use switched between git-clone installs. The installed package acts on the workspace you are in: it looks up" >&2
    echo "from the current folder for one with a .repolane/ folder (or LANE_WORKSPACE names it)." >&2
  fi
  echo "  make a workspace:            lane init [folder]" >&2
  echo "  move a clone install over:   lane migrate <clone-folder>" >&2
  exit 2
fi

case "$cmd" in
  -h|--help|help) usage; exit 0 ;;
  hook)
    # `lane hook <event>`: what a workspace's .claude/settings.json runs, so no hook names a file in the product. The
    # hook's JSON passes through on stdin to the same implementations a clone's settings name by path.
    ev="${2:-}"
    case "$ev" in
      session-start) exec "$S/session-start" ;;
      # `lane doctor` runs this exactly the way a hook runs, to see which product and workspace a hook would reach
      ping) v=$( (tr -d '[:space:]' < "$PRODUCT/VERSION") 2>/dev/null ); printf 'lane-hook %s %s %s\n' "${v:-unknown}" "$LANE_MODE" "$AD"; exit 0 ;;
      pre-tool-use|post-tool-use|user-prompt-submit|pre-compact|session-end|worktree-create|worktree-remove)
        # -B: the product is never written to, not even a __pycache__ for the modules the guard imports
        exec python3 -B "$S/hooks/guard.py" ;;
      *) echo "lane hook: unknown event '$ev' (session-start, pre-tool-use, post-tool-use, user-prompt-submit, pre-compact, session-end, worktree-create, worktree-remove)" >&2
         exit 1 ;;
    esac ;;
  statusline)
    # what a workspace's statusLine runs (the status line's JSON on stdin), so it names no file in the product either
    exec "$S/statusline.sh" ;;
  --version|version)
    # VERSION is the one place the number is written down, so a tarball with no .git still knows
    # what it is. The release tag is always v<VERSION>; git is asked only for the detail a file
    # cannot carry — how far past that tag this checkout has drifted.
    # the redirection itself is what fails when VERSION is absent, so the subshell, not tr, is
    # what has to be silenced
    v=$( (tr -d '[:space:]' < "$PRODUCT/VERSION") 2>/dev/null ); [ -n "$v" ] || v=unknown
    extra=""
    # Only a checkout of its own has a git answer: an installed package (or a tarball) unpacked somewhere inside an
    # unrelated repo would otherwise report that repo's commits as its own.
    if [ ! -e "$PRODUCT/.git" ]; then :
    elif g=$(cd "$PRODUCT" && git describe --tags --long --dirty --match 'v[0-9]*' 2>/dev/null); then
      # v0.1.0-3-gabc1234[-dirty]: the middle field is the commit count since the tag
      n=${g#v*-}; n=${n%%-*}
      case "$g" in *-dirty) d=", uncommitted changes" ;; *) d="" ;; esac
      if [ "$n" = 0 ]; then extra="$d"; else extra=" (+$n commits$d)"; fi
    elif h=$(cd "$PRODUCT" && git rev-parse --short HEAD 2>/dev/null); then
      # a checkout with no release tag in its history: before the first tag, or a shallow clone
      extra=" (untagged, $h)"
    fi
    printf 'lane %s%s\n' "$v" "$extra"; exit 0 ;;
  install)
    dest="$HOME/.local/bin"; force=0; as_name=""; make_active=0
    rest=("${@:2}"); i=0
    while [ $i -lt ${#rest[@]} ]; do
      a="${rest[$i]}"
      case "$a" in
        --force) force=1 ;;
        -y|--yes) force=1 ;;
        --make-active) make_active=1 ;;
        --as) i=$((i+1)); as_name="${rest[$i]:-}" ;;
        *) dest="$a" ;;
      esac
      i=$((i+1))
    done
    # The `lane` already there may be the installed package's (pipx, uv tool and pip all write a small Python launcher,
    # pipx and uv as a link into their venv). It is not a clone and not the router: writing the router over it would take
    # the package's `lane` away, and registering it would make its venv's bin/ a "plane". Refuse, and say what to do.
    if [ -e "$dest/lane" ]; then
      _l=$(python3 -c 'import os,sys;print(os.path.realpath(sys.argv[1]))' "$dest/lane" 2>/dev/null)
      if [ -f "$_l" ] && head -c 4096 "$_l" 2>/dev/null | grep -qE 'repolane\.cli|from repolane'; then
        echo "lane install: $dest/lane is the installed Repolane package's lane (pipx, uv tool or pip), not a clone's router." >&2
        echo "  Writing the router there would replace it, so nothing was changed. The package works on workspaces:" >&2
        echo "    move this clone over:            lane migrate $(printf %q "$AD")" >&2
        echo "    or keep the clone's own router:  ./lane install <another-folder-on-PATH>" >&2
        exit 2
      fi
    fi
    mkdir -p "$dest" || exit 1
    SHARE="$HOME/.local/share/lane"; mkdir -p "$SHARE" || exit 1
    PY="$SHARE/planes.py"

    # Multi-plane registry (piece 1/2, CONTRIBUTING.md): `~/.local/bin/lane` is no longer a
    # symlink at THIS checkout — it becomes a small, stable, generic dispatcher that routes to
    # whichever registered plane applies (directory-aware first, `active` as the fallback), and
    # is never repointed again. Writing it is always safe to re-run: the content is identical no
    # matter which checkout runs `lane install`, so this step alone can never take another
    # project's usable install away — that silent theft was the entire bug being fixed here.
    #
    # Migration: an existing `dest/lane` that is a plain symlink (the old one-checkout-at-a-time
    # model) is detected here, before it gets replaced, so whatever checkout it pointed at can be
    # auto-registered rather than silently orphaned.
    migrated_from=""
    if [ -L "$dest/lane" ]; then
      old_real="$(python3 -c 'import os,sys;print(os.path.realpath(sys.argv[1]))' "$dest/lane" 2>/dev/null)"
      if [ -n "$old_real" ] && [ -x "$old_real" ]; then
        migrated_from="$(cd "$(dirname "$old_real")" && pwd)"
        # only a git clone of Repolane is a plane: a link to anything else is not registered
        if [ ! -f "$migrated_from/lane" ] || [ ! -f "$migrated_from/scripts/lib.sh" ]; then
          echo "not registering $migrated_from (the old $dest/lane pointed there): it is not a git clone of Repolane" >&2
          migrated_from=""
        fi
      fi
    fi

    # `rm -f` before every write below: `dest/lane` (and each long-form name) may currently be a
    # symlink at some checkout's real file — an old install, or even THIS checkout's own bin/.
    # Writing through a symlink with `cp`/a redirect overwrites the checkout's source file, not
    # just the link; removing the link first guarantees each write below lands on a fresh regular
    # file at `dest/…`, never back into any checkout.
    rm -f "$dest/lane"
    cp "$S/lane-stable-dispatcher" "$dest/lane" && chmod +x "$dest/lane"
    rm -f "$PY"
    cp "$S/lane-planes.py" "$PY"
    echo "installed the stable dispatcher: $dest/lane (routes by plane — see: lane use)"

    if [ -n "$migrated_from" ] && [ "$migrated_from" != "$AD" ]; then
      mig_name="$(basename "$migrated_from")"
      out="$(python3 "$PY" register "$mig_name" "$migrated_from" 2>&1)" \
        && echo "migrated old install: $out" \
        || echo "migration: could not register '$mig_name' automatically ($out) — register it by hand later: lane install --as <name> (from $migrated_from)" >&2
    fi

    # The 27 long-form names (lane-start, lane-brief, guard-check, …) had the exact same
    # ambiguity bare `lane` did. Each is now a tiny stub that routes THROUGH the stable
    # dispatcher's own resolution rather than reimplementing it 27 times. The short-name mapping
    # is 1:1 and mechanical for most of them (strip `lane-`); the exceptions (see `map()` above)
    # are spelled out in longform_short() rather than guessed at.
    LONGFORM_NAMES="lane-add lane-audit lane-board lane-brief lane-done lane-env-check lane-env-keys \
      lane-find lane-gh lane-help lane-import lane-init lane-memory lane-menu lane-merge \
      lane-merge-plan lane-nested lane-park lane-ref lane-resume lane-run lane-sessions \
      lane-start lane-status lane-with lane-workspace guard-check"
    longform_short(){ case "$1" in
      lane-memory) echo note ;;
      lane-env-check) echo env ;;
      lane-env-keys) echo keys ;;
      lane-merge-plan) echo plan ;;
      guard-check) echo doctor ;;
      lane-*) echo "${1#lane-}" ;;
      *) return 1 ;;
    esac; }
    is_cmd(){ [ -x "$1" ] && [ ! -d "$1" ]; }
    # An earlier version symlinked bin/ entries directly, including bin/README.md. Clean up any
    # stray link left from that — but only one that clearly came from a Repolane bin/ (has
    # lane-start next to it), never an unrelated file the user keeps on their own PATH.
    for l in "$dest"/*; do
      [ -L "$l" ] || continue
      b=$(basename "$l"); [ "$b" = lane ] && continue
      case " $LONGFORM_NAMES " in *" $b "*) continue ;; esac
      d=$(dirname "$(readlink "$l")" 2>/dev/null) || continue
      [ -e "$d/lane-start" ] || continue
      is_cmd "$d/$b" && continue
      rm -f "$l" && echo "unlinked $dest/$b — it is not a command; an older install put it on your PATH"
    done
    n=0
    for name in $LONGFORM_NAMES; do
      short="$(longform_short "$name")" || continue
      rm -f "$dest/$name"
      printf '#!/usr/bin/env bash\nexec "$(command -v lane)" %s "$@"\n' "$short" > "$dest/$name" \
        && chmod +x "$dest/$name" && n=$((n+1))
    done
    echo "wrote $n long-form command stubs (lane-start, lane-run, …) into $dest"

    # Register THIS checkout. Default name is the directory's basename; --as overrides. Re-running
    # install from a checkout already registered updates that same entry rather than duplicating
    # it. `active` is set only when this is the very first plane ever registered, or --make-active
    # was passed explicitly — installing from a second project must never silently steal `active`
    # away from whatever you were already using; that is the exact bug this whole piece fixes.
    name="$as_name"
    if [ -z "$name" ]; then
      existing="$(python3 "$PY" find-by-path "$AD" 2>/dev/null)" && name="$existing"
    fi
    [ -n "$name" ] || name="$(basename "$AD")"
    if [ "$make_active" = 1 ]; then
      cur_active="$(python3 -c "
import json,os
try:
    d=json.load(open(os.path.expanduser('~/.local/share/lane/planes.json')))
    print(d.get('active') or '')
except Exception:
    print('')
" 2>/dev/null)"
      if [ -n "$cur_active" ] && [ "$cur_active" != "$name" ] && [ "$force" != 1 ] && [ -t 0 ] && [ -t 2 ]; then
        echo "active plane is currently '$cur_active' — installing with --make-active would switch it to '$name'"
        printf "switch active plane? [y/N]: " >&2
        read -r yn || true
        case "${yn:-n}" in [yY]*) : ;; *) echo "lane install: kept '$cur_active' active — plane still registered" >&2; make_active=0 ;; esac
      fi
    fi
    reg_flags=""; [ "$make_active" = 1 ] && reg_flags="--make-active"
    reg_out="$(python3 "$PY" register "$name" "$AD" $reg_flags 2>&1)"; reg_rc=$?
    if [ "$reg_rc" = 2 ]; then
      # A DIFFERENT checkout is already registered under this name (usually an auto-derived
      # basename collision) -- refuse to silently repoint it. Confirm explicitly, or refuse
      # outright with no terminal to ask, same "never silently reassign" rule as --make-active.
      echo "$reg_out" >&2
      if [ -t 0 ] && [ -t 2 ]; then
        printf "repoint '%s' to this checkout instead? [y/N]: " "$name" >&2
        read -r yn || true
        case "${yn:-n}" in
          [yY]*) python3 "$PY" register "$name" "$AD" $reg_flags --force ;;
          *) echo "lane install: not registered — re-run with --as <a-different-name>" >&2; exit 1 ;;
        esac
      else
        echo "lane install: not registered (no terminal to confirm) — re-run with --as <a-different-name>" >&2
        exit 1
      fi
    else
      echo "$reg_out"
    fi

    case ":$PATH:" in
      *":$dest:"*) echo "ready — run: lane" ;;
      *) echo; echo "add this to your shell profile, then open a new terminal:"; echo "  export PATH=\"$dest:\$PATH\"" ;;
    esac
    echo
    echo "note: Claude can make mistakes. The hooks are a guardrail, not a sandbox: review what Claude changes."
    echo "      Provided as is, without warranty, under Apache-2.0 (see LICENSE)."
    exit 0 ;;
esac

if entry=$(map "$cmd"); then
  # Before `lane init` there is no registry, and these commands used to fail with raw git
  # or Python errors. Say the one thing that helps.
  case "$cmd" in
    init|help) : ;;
    *) [ -f "$REGISTRY/repos.yaml" ] || {
         if [ "$LANE_MODE" = clone ] && [ -n "${LANE_PRODUCT:-}" ]; then
           printf '\e[31mlane: this folder is not a workspace yet\e[0m\n' >&2
         else
           printf '\e[31mlane: this %s is not set up yet\e[0m\n' "$PLANE_WORD" >&2
         fi
         echo "  run:  lane init" >&2
         exit 2
       } ;;
  esac
  shift 2>/dev/null || true
  exec "${entry%%|*}" "$@"
fi

# Not a built-in — but scripts/local/<name> (gitignored, docs/extending.md) turns any executable
# file into a `lane <name>` subcommand without ever touching this dispatcher again. Checked only
# here, after `map()` has already missed, so a built-in of the same name always wins.
# $cmd is only ever a bare filename in that directory, never a path into or out of it: a name
# with a `/` (traversal, or reaching some other executable entirely) is never looked up here.
# A separate variable, not $cmd itself, so a rejected name still shows correctly in the "no
# command named" error below rather than printing blank.
local_cmd="$cmd"; case "$local_cmd" in */*) local_cmd="" ;; esac
if [ -n "$local_cmd" ] && [ -x "$DATA/scripts/local/$local_cmd" ] && [ ! -d "$DATA/scripts/local/$local_cmd" ]; then
  shift 2>/dev/null || true
  exec "$DATA/scripts/local/$local_cmd" "$@"
fi

# not a command — say so, and guess what was meant
printf '\e[31mlane: no command named "%s"\e[0m\n' "$cmd" >&2
near=$(for c in $ORDER; do [[ $c == *"$cmd"* ]] && echo "  lane $c"; done)
[ -n "$near" ] && { echo "did you mean:" >&2; echo "$near" >&2; }
echo >&2; echo "  lane help   for the full list" >&2
exit 2
