#!/usr/bin/env sh
# devloop — unified control-plane CLI entry
set -eu

HERE=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)

usage() {
  cat <<'EOF'
devloop — control-plane kernel CLI

Usage: devloop <command> [args]

Commands:
  setup [--project DIR] [--check]
                      初始化项目知识入口；--check 只读检查
  init --id ID [--title T] [--root DIR] [--stage S]
                      创建任务模板，并只读检查项目知识入口
  gate intent|spec|plan|goal --file PATH [--intent|--spec|--plan PATH] [--draft]
                      Stage exit gate (lint) — 0 pass / 1 fail
  stage <validate|can|transitions> --from S [--to S]
                      Pipeline stage machine: intent|spec|plan|loop|done
  doctor              Health check skill tree and tools
  detect-host [...]   Run detect-runtime-host.sh
  detect-scheduler [...]
  cleanup-sessions --orca-cli PATH --worktree ID [opts]
  attempt <new|archive> ...
  lock <acquire|release|check> ...
  state <validate|can|transitions> ...
  status --plan PATH [--json]
  next --dir .devloop/ID | --plan PATH [--run-dir DIR]
  review-packet --devloop-dir PATH
  run-tests            Run all tests/*.test.sh
  help

Version: 0.9.1
EOF
}

[ $# -ge 1 ] || { usage; exit 2; }
cmd=$1
shift

case "$cmd" in
  setup) exec sh "$HERE/setup.sh" "$@" ;;
  init) exec sh "$HERE/init.sh" "$@" ;;
  archive) printf '整包归档命令已移除；用 devloop skill 将定稿需求归入 docs/knowledge/specs，领域/经验/ADR 分别归入 domain/playbooks/decisions。\n' >&2; exit 2 ;;
  gate) exec sh "$HERE/gate.sh" "$@" ;;
  stage)
    [ $# -ge 1 ] || { printf 'error: stage needs a subcommand\n' >&2; exit 2; }
    sub=$1
    shift
    case "$sub" in
      validate|can|transitions)
        exec sh "$HERE/state-machine.sh" "stage-$sub" "$@"
        ;;
      *)
        printf 'error: unknown stage subcommand: %s\n' "$sub" >&2
        exit 2
        ;;
    esac
    ;;
  doctor) exec sh "$HERE/doctor.sh" "$@" ;;
  detect-host|detect-runtime-host)
    exec sh "$HERE/detect-runtime-host.sh" "$@"
    ;;
  detect-scheduler|detect-loop-scheduler)
    exec sh "$HERE/detect-loop-scheduler.sh" "$@"
    ;;
  cleanup-sessions|cleanup-orca-sessions)
    exec sh "$HERE/cleanup-orca-sessions.sh" "$@"
    ;;
  attempt) exec sh "$HERE/attempt.sh" "$@" ;;
  lock) exec sh "$HERE/lock.sh" "$@" ;;
  state|state-machine) exec sh "$HERE/state-machine.sh" "$@" ;;
  status) exec sh "$HERE/status.sh" "$@" ;;
  next|next-action) exec sh "$HERE/next-action.sh" "$@" ;;
  review-packet|review) exec sh "$HERE/review-packet.sh" "$@" ;;
  run-tests|test) exec sh "$HERE/run-tests.sh" "$@" ;;
  help|-h|--help) usage; exit 0 ;;
  version|--version) printf '0.9.1\n'; exit 0 ;;
  *)
    printf 'error: unknown command: %s\n' "$cmd" >&2
    usage >&2
    exit 2
    ;;
esac
