#!/usr/bin/env bash
#clear
#export PS4='\e[90m+${LINENO} in ${#BASH_SOURCE[@]}>${FUNCNAME[0]}:${BASH_SOURCE[@]##*/} \e[0m'
#set -x

#echo "starting: $0 <LOG_LEVEL=$1>"

### new.method

# ============================================================================
# claudeFlow - Claude Flow wrapper for oosh
# Makes Claude Flow CLI commands easy to use with intuitive method names
# ============================================================================

# ─────────────────────────────────────────────────────────────────────────────
# SYSTEM COMMANDS
# ─────────────────────────────────────────────────────────────────────────────

claudeFlow.init() # <?path> # initialize claude flow in a directory
{
  if [ -n "$1" ]; then
    claude-flow init "$1"
  else
    claude-flow init
  fi
}

claudeFlow.start() # <?options> # start the orchestration system
{
  claude-flow start "$@"
}

claudeFlow.stop() # # stop the orchestration system
{
  claude-flow start stop
}

claudeFlow.restart() # # restart the orchestration system
{
  claude-flow start restart
}

claudeFlow.quick() # # quick start with default settings
{
  claude-flow start quick
}

claudeFlow.daemon() # <?options> # start as background daemon
{
  claude-flow start --daemon "$@"
}

claudeFlow.status() # # show system status
{
  claude-flow status
  echo ""
  echo "Claude Flow wrapper for oosh"
  echo "Type 'claudeFlow' for interactive mode"
  echo "Type 'claudeFlow help' for all options"
}

claudeFlow.doctor() # # run diagnostics and health checks
{
  claude-flow doctor
}

claudeFlow.version() # # show claude-flow version
{
  claude-flow --version
}

claudeFlow.v() # # shorthand for version
{
  claudeFlow.version
}

claudeFlow.help() # # show claude-flow help
{
  claude-flow --help
}

claudeFlow.install() # # install claude-flow via npm
{
  # Check if npm is available
  if ! command -v npm &> /dev/null; then
    error.log "npm is required but not installed."
    error.log "Please install Node.js and npm first:"
    if command -v apt-get >/dev/null 2>&1; then
      echo "  curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -"
      echo "  sudo apt-get install -y nodejs"
    elif command -v dnf >/dev/null 2>&1 || command -v yum >/dev/null 2>&1; then
      echo "  curl -fsSL https://rpm.nodesource.com/setup_lts.x | sudo bash -"
      echo "  sudo dnf install -y nodejs"
    else
      echo "  Visit https://nodejs.org/ for installation instructions"
    fi
    return 1
  fi

  # Check if already installed
  if command -v claude-flow &> /dev/null; then
    info.log "Claude Flow is already installed: $(which claude-flow)"
    claude-flow --version
    echo ""
    read -p "Reinstall/update anyway? [y/N] " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
      info.log "Installation cancelled"
      return 0
    fi
  fi

  info.log "Installing Claude Flow via npm..."

  # Install globally via npm
  npm install -g claude-flow

  if [ $? -ne 0 ]; then
    error.log "Installation failed"
    error.log "Try running with sudo: sudo npm install -g claude-flow"
    return 1
  fi

  # Verify installation
  if command -v claude-flow &> /dev/null; then
    success.log "Claude Flow installed successfully!"
    claude-flow --version
    echo ""
    info.log "Run 'claudeFlow init' to initialize in a directory"
    info.log "Run 'claudeFlow doctor' to verify setup"
  else
    error.log "Installation completed but 'claude-flow' command not found"
    error.log "Check that npm global bin is in your PATH"
    return 1
  fi
}

claudeFlow.uninstall() # # uninstall claude-flow
{
  if ! command -v claude-flow &> /dev/null; then
    warn.log "Claude Flow does not appear to be installed"
    return 0
  fi

  local installPath=$(which claude-flow)
  info.log "Claude Flow is installed at: $installPath"
  claude-flow --version
  echo ""
  read -p "Are you sure you want to uninstall Claude Flow? [y/N] " -n 1 -r
  echo

  if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    info.log "Uninstall cancelled"
    return 0
  fi

  info.log "Uninstalling Claude Flow via npm..."

  npm uninstall -g claude-flow

  if [ $? -ne 0 ]; then
    error.log "Uninstall failed"
    error.log "Try running with sudo: sudo npm uninstall -g claude-flow"
    return 1
  fi

  if ! command -v claude-flow &> /dev/null; then
    success.log "Claude Flow uninstalled successfully"
  else
    warn.log "claude-flow command still found - may need manual removal"
  fi
}

claudeFlow.update() # # update claude-flow to latest version
{
  if ! command -v claude-flow &> /dev/null; then
    warn.log "Claude Flow is not installed. Run 'claudeFlow install' first."
    return 1
  fi

  info.log "Current version:"
  claude-flow --version
  echo ""
  info.log "Updating Claude Flow via npm..."

  npm update -g claude-flow

  if [ $? -ne 0 ]; then
    error.log "Update failed"
    error.log "Try running with sudo: sudo npm update -g claude-flow"
    return 1
  fi

  success.log "Claude Flow updated!"
  claude-flow --version
}

# ─────────────────────────────────────────────────────────────────────────────
# AGENT COMMANDS
# ─────────────────────────────────────────────────────────────────────────────

claudeFlow.agent() # <subcommand> # agent management commands
{
  claude-flow agent "$@"
}

claudeFlow.agent.spawn() # <options> # spawn a new agent
{
  claude-flow agent spawn "$@"
}
claudeFlow.agent.spawn.completion.type() {
  echo "coder"
  echo "researcher"
  echo "reviewer"
  echo "planner"
}

claudeFlow.agent.list() # # list all active agents
{
  claude-flow agent list "$@"
}

claudeFlow.agent.ls() # # shorthand for agent list
{
  claudeFlow.agent.list "$@"
}

claudeFlow.agent.status() # <agentId> # show agent status
{
  claude-flow agent status "$@"
}

claudeFlow.agent.stop() # <agentId> # stop a running agent
{
  claude-flow agent stop "$@"
}

claudeFlow.agent.kill() # <agentId> # alias for agent stop
{
  claudeFlow.agent.stop "$@"
}

claudeFlow.agent.metrics() # <?agent-id> # show agent performance metrics
{
  claude-flow agent metrics "$@"
}

claudeFlow.agent.pool() # <options> # manage agent pool for scaling
{
  claude-flow agent pool "$@"
}

claudeFlow.agent.health() # <?agent-id> # show agent health
{
  claude-flow agent health "$@"
}

claudeFlow.agent.logs() # <?agent-id> # show agent activity logs
{
  claude-flow agent logs "$@"
}

# ─────────────────────────────────────────────────────────────────────────────
# TASK COMMANDS
# ─────────────────────────────────────────────────────────────────────────────

claudeFlow.task() # <subcommand> # task management commands
{
  claude-flow task "$@"
}

claudeFlow.task.create() # <options> # create a new task
{
  claude-flow task create "$@"
}

claudeFlow.task.new() # <options> # alias for task create
{
  claudeFlow.task.create "$@"
}

claudeFlow.task.list() # <?options> # list tasks
{
  claude-flow task list "$@"
}

claudeFlow.task.ls() # <?options> # shorthand for task list
{
  claudeFlow.task.list "$@"
}

claudeFlow.task.all() # # list all tasks including completed
{
  claude-flow task list --all
}

claudeFlow.task.status() # <taskId> # get task status and details
{
  claude-flow task status "$@"
}

claudeFlow.task.info() # <taskId> # alias for task status
{
  claudeFlow.task.status "$@"
}

claudeFlow.task.cancel() # <taskId> # cancel a running task
{
  claude-flow task cancel "$@"
}

claudeFlow.task.assign() # <taskId> <options> # assign task to agent(s)
{
  claude-flow task assign "$@"
}

claudeFlow.task.retry() # <taskId> # retry a failed task
{
  claude-flow task retry "$@"
}

# ─────────────────────────────────────────────────────────────────────────────
# SESSION COMMANDS
# ─────────────────────────────────────────────────────────────────────────────

claudeFlow.session() # <subcommand> # session management commands
{
  claude-flow session "$@"
}

claudeFlow.session.list() # # list all sessions
{
  claude-flow session list "$@"
}

claudeFlow.list() # <?--json> # list all Claude Code sessions on this host in tree format
{
  local CLAUDE_PROJECTS_DIR="$HOME/.claude/projects"
  local format="tree"

  [ "$1" = "--json" ] && format="json"

  if [ ! -d "$CLAUDE_PROJECTS_DIR" ]; then
    warn.log "No Claude projects directory found: $CLAUDE_PROJECTS_DIR"
    return 1
  fi

  if [ "$format" = "json" ]; then
    claudeFlow.list.json
    return $?
  fi

  echo ""
  echo "┌─────────────────────────────────────────────────────────────────────────────┐"
  echo "│                        CLAUDE CODE SESSIONS                                 │"
  echo "└─────────────────────────────────────────────────────────────────────────────┘"
  echo ""

  local totalSessions=0
  local totalProjects=0

  # Iterate through all project directories
  for project_dir in "$CLAUDE_PROJECTS_DIR"/*; do
    [ ! -d "$project_dir" ] && continue

    local projectName=$(basename "$project_dir")
    local indexFile="$project_dir/sessions-index.json"

    # Decode path: -var-dev-Workspaces -> /var/dev/Workspaces
    local decodedPath=$(echo "$projectName" | sed 's/^-/\//' | sed 's/-/\//g')

    ((totalProjects++))

    echo "📁 $decodedPath"
    echo "│"

    if [ -f "$indexFile" ]; then
      # Parse sessions-index.json
      local sessionCount=0

      if command -v jq &>/dev/null; then
        # Use jq if available
        local entries=$(jq -r '.entries | length' "$indexFile" 2>/dev/null)

        if [ "$entries" -gt 0 ]; then
          jq -r '.entries[] | "\(.sessionId)|\(.firstPrompt // "untitled")|\(.messageCount // 0)|\(.modified // "unknown")|\(.gitBranch // "-")"' "$indexFile" 2>/dev/null | \
          while IFS='|' read -r sid prompt msgs modified branch; do
            ((sessionCount++))
            ((totalSessions++))

            # Truncate prompt to 50 chars
            local shortPrompt=$(echo "$prompt" | cut -c1-50)
            [ ${#prompt} -gt 50 ] && shortPrompt="${shortPrompt}..."

            # Format modified date
            local modDate=$(echo "$modified" | cut -c1-10)

            # Determine if last entry
            local prefix="├──"
            [ "$sessionCount" -eq "$entries" ] && prefix="└──"

            echo "$prefix 💬 $shortPrompt"
            echo "│   │  ID: ${sid:0:8}...  msgs: $msgs  branch: $branch  modified: $modDate"
          done
        else
          echo "└── (no sessions)"
        fi
      else
        # Fallback without jq - basic grep parsing
        local sids=$(grep -o '"sessionId":"[^"]*"' "$indexFile" 2>/dev/null | cut -d'"' -f4)
        local prompts=$(grep -o '"firstPrompt":"[^"]*"' "$indexFile" 2>/dev/null | cut -d'"' -f4)

        if [ -n "$sids" ]; then
          echo "$sids" | while read sid; do
            ((totalSessions++))
            echo "├── 💬 Session ${sid:0:8}..."
          done
        else
          echo "└── (no sessions or unable to parse)"
        fi
      fi
    else
      # No index file - check for .jsonl files directly
      local jsonlFiles=$(ls "$project_dir"/*.jsonl 2>/dev/null | grep -v sessions-index)
      if [ -n "$jsonlFiles" ]; then
        echo "$jsonlFiles" | while read f; do
          local sid=$(basename "$f" .jsonl)
          local size=$(du -h "$f" 2>/dev/null | cut -f1)
          echo "├── 📄 ${sid:0:8}... ($size)"
          ((totalSessions++))
        done
      else
        echo "└── (no sessions)"
      fi
    fi
    echo ""
  done

  echo "─────────────────────────────────────────────────────────────────────────────"
  echo "Total: $totalProjects projects"
  echo ""
}

claudeFlow.list.json() # # output all sessions as JSON
{
  local CLAUDE_PROJECTS_DIR="$HOME/.claude/projects"

  echo "{"
  echo '  "projects": ['

  local firstProject=1
  for project_dir in "$CLAUDE_PROJECTS_DIR"/*; do
    [ ! -d "$project_dir" ] && continue

    local projectName=$(basename "$project_dir")
    local decodedPath=$(echo "$projectName" | sed 's/^-/\//' | sed 's/-/\//g')
    local indexFile="$project_dir/sessions-index.json"

    [ "$firstProject" -eq 0 ] && echo ","
    firstProject=0

    echo "    {"
    echo "      \"path\": \"$decodedPath\","
    echo "      \"encoded\": \"$projectName\","

    if [ -f "$indexFile" ] && command -v jq &>/dev/null; then
      echo -n "      \"sessions\": "
      jq '.entries' "$indexFile" 2>/dev/null
    else
      echo "      \"sessions\": []"
    fi
    echo -n "    }"
  done

  echo ""
  echo "  ]"
  echo "}"
}

claudeFlow.list.completion() {
  echo "--json"
}

claudeFlow.session.ls() # # shorthand for session list
{
  claudeFlow.session.list "$@"
}

claudeFlow.session.save() # <?name> # save current session state
{
  claude-flow session save "$@"
}

claudeFlow.session.restore() # <sessionId> # restore a saved session
{
  claude-flow session restore "$@"
}

claudeFlow.session.load() # <sessionId> # alias for session restore
{
  claudeFlow.session.restore "$@"
}

claudeFlow.session.delete() # <sessionId> # delete a saved session
{
  claude-flow session delete "$@"
}

claudeFlow.session.rm() # <sessionId> # shorthand for session delete
{
  claudeFlow.session.delete "$@"
}

claudeFlow.session.export() # <options> # export session to file
{
  claude-flow session export "$@"
}

claudeFlow.session.import() # <file> # import session from file
{
  claude-flow session import "$@"
}

claudeFlow.session.current() # # show current active session
{
  claude-flow session current
}

# ─────────────────────────────────────────────────────────────────────────────
# SWARM COMMANDS
# ─────────────────────────────────────────────────────────────────────────────

claudeFlow.swarm() # <subcommand> # swarm coordination commands
{
  claude-flow swarm "$@"
}

claudeFlow.swarm.init() # <?options> # initialize a new swarm
{
  claude-flow swarm init "$@"
}

claudeFlow.swarm.v3() # <?options> # initialize V3 swarm with hierarchical mesh
{
  claude-flow swarm init --v3-mode "$@"
}

claudeFlow.swarm.start() # <options> # start swarm execution
{
  claude-flow swarm start "$@"
}

claudeFlow.swarm.status() # # show swarm status
{
  claude-flow swarm status "$@"
}

claudeFlow.swarm.stop() # # stop swarm execution
{
  claude-flow swarm stop "$@"
}

claudeFlow.swarm.scale() # <count> # scale swarm agent count
{
  claude-flow swarm scale "$@"
}

claudeFlow.swarm.coordinate() # <?options> # execute V3 15-agent hierarchical mesh coordination
{
  claude-flow swarm coordinate "$@"
}

# ─────────────────────────────────────────────────────────────────────────────
# MEMORY COMMANDS
# ─────────────────────────────────────────────────────────────────────────────

claudeFlow.memory() # <subcommand> # memory management commands
{
  claude-flow memory "$@"
}

claudeFlow.memory.init() # # initialize memory database
{
  claude-flow memory init "$@"
}

claudeFlow.memory.store() # <options> # store data in memory
{
  claude-flow memory store "$@"
}

claudeFlow.memory.get() # <key> # retrieve data from memory
{
  claude-flow memory retrieve "$@"
}

claudeFlow.memory.search() # <query> # search memory with semantic search
{
  claude-flow memory search "$@"
}

claudeFlow.memory.list() # # list memory entries
{
  claude-flow memory list "$@"
}

claudeFlow.memory.ls() # # shorthand for memory list
{
  claudeFlow.memory.list "$@"
}

claudeFlow.memory.delete() # <key> # delete memory entry
{
  claude-flow memory delete "$@"
}

claudeFlow.memory.rm() # <key> # shorthand for memory delete
{
  claudeFlow.memory.delete "$@"
}

claudeFlow.memory.stats() # # show memory statistics
{
  claude-flow memory stats
}

claudeFlow.memory.cleanup() # # clean up stale and expired entries
{
  claude-flow memory cleanup
}

claudeFlow.memory.compress() # # compress and optimize storage
{
  claude-flow memory compress
}

claudeFlow.memory.export() # <file> # export memory to file
{
  claude-flow memory export "$@"
}

claudeFlow.memory.import() # <file> # import memory from file
{
  claude-flow memory import "$@"
}

# ─────────────────────────────────────────────────────────────────────────────
# MCP COMMANDS
# ─────────────────────────────────────────────────────────────────────────────

claudeFlow.mcp() # <subcommand> # MCP server management
{
  claude-flow mcp "$@"
}

claudeFlow.mcp.start() # <?options> # start MCP server
{
  claude-flow mcp start "$@"
}

claudeFlow.mcp.stop() # # stop MCP server
{
  claude-flow mcp stop
}

claudeFlow.mcp.status() # # show MCP server status
{
  claude-flow mcp status
}

claudeFlow.mcp.health() # # check MCP server health
{
  claude-flow mcp health
}

claudeFlow.mcp.restart() # # restart MCP server
{
  claude-flow mcp restart
}

claudeFlow.mcp.tools() # # list available MCP tools
{
  claude-flow mcp tools "$@"
}

claudeFlow.mcp.toggle() # <tool> # enable or disable MCP tools
{
  claude-flow mcp toggle "$@"
}

claudeFlow.mcp.exec() # <tool> <options> # execute an MCP tool
{
  claude-flow mcp exec "$@"
}

claudeFlow.mcp.logs() # # show MCP server logs
{
  claude-flow mcp logs "$@"
}

# ─────────────────────────────────────────────────────────────────────────────
# HIVE-MIND COMMANDS
# ─────────────────────────────────────────────────────────────────────────────

claudeFlow.hive() # <subcommand> # hive-mind coordination commands
{
  claude-flow hive-mind "$@"
}

claudeFlow.hive.init() # <?options> # initialize a hive mind
{
  claude-flow hive-mind init "$@"
}

claudeFlow.hive.spawn() # <options> # spawn worker agents into the hive
{
  claude-flow hive-mind spawn "$@"
}

claudeFlow.hive.status() # <?pane:1> # show hive mind status (pane: 0=here, 1=lower, or pane id)
{
  local pane=${1:-1}
  if [ -n "$1" ]; then shift; fi

  # If pane=0 or "here" or not in tmux, run in current pane
  if [ "$pane" = "0" ] || [ "$pane" = "here" ] || [ -z "$TMUX" ]; then
    claude-flow hive-mind status "$@"
    return $?
  fi

  # Get target pane ID
  local targetPane=$(tmux list-panes -F "#{pane_index}:#{pane_id}" | grep "^${pane}:" | cut -d: -f2)

  if [ -z "$targetPane" ]; then
    # Fallback: run in current pane if target pane doesn't exist
    claude-flow hive-mind status "$@"
    return $?
  fi

  # Send command to target pane using otmux
  otmux send -t "$targetPane" "claude-flow hive-mind status $*" Enter

  info.log "Hive status displayed in pane $pane"
  echo "Switch to view: Ctrl+b ↓  or  claudeFlow tmux.lower"
}
claudeFlow.hive.status.completion.pane() {
  echo "0"
  echo "1"
  echo "here"
  tmux list-panes -F "#{pane_index}" 2>/dev/null
}

claudeFlow.hive.task() # <options> # submit tasks to the hive
{
  claude-flow hive-mind task "$@"
}

claudeFlow.hive.list() # # list all agent IDs in the hive
{
  # Get queen and worker IDs from hive-mind status JSON
  if command -v jq &>/dev/null; then
    claude-flow hive-mind status --format json 2>/dev/null | jq -r '.queen.id // empty, .workers[].id // empty' 2>/dev/null
  else
    # Fallback: parse JSON with grep
    claude-flow hive-mind status --format json 2>/dev/null | grep -o '"id":"[^"]*"' | cut -d'"' -f4
  fi
}

# Parameter completion shared across all methods using <agentId>
claudeFlow.parameter.completion.agentId() {
  claudeFlow.hive.list
}

claudeFlow.parameter.completion.agent() {
  claudeFlow.parameter.completion.agentId "$@"
}

claudeFlow.parameter.completion.sessionId() {
  claude-flow session list --format json 2>/dev/null | grep -o '"id":"[^"]*"' | cut -d'"' -f4
}

claudeFlow.parameter.completion.taskId() {
  claude-flow task list --format json 2>/dev/null | grep -o '"id":"[^"]*"' | cut -d'"' -f4
}

claudeFlow.parameter.completion.tool() {
  claude-flow mcp tools 2>/dev/null | grep -oE '^[a-zA-Z][a-zA-Z0-9_.-]*'
}

claudeFlow.parameter.completion.file() {
  compgen -f "$1"
}

claudeFlow.parameter.completion.path() {
  compgen -d "$1"
}

claudeFlow.hive.join() # <agentId> # join an agent to the hive mind
{
  claude-flow hive-mind join "$@"
}

claudeFlow.hive.leave() # <agentId> # remove an agent from the hive mind
{
  claude-flow hive-mind leave "$@"
}

claudeFlow.hive.consensus() # <options> # manage consensus proposals and voting
{
  claude-flow hive-mind consensus "$@"
}

claudeFlow.hive.broadcast() # <message> # broadcast message to all workers
{
  claude-flow hive-mind broadcast "$@"
}

claudeFlow.hive.memory() # # access hive shared memory
{
  claude-flow hive-mind memory "$@"
}

claudeFlow.hive.optimize() # # optimize hive memory and patterns
{
  claude-flow hive-mind optimize-memory "$@"
}

claudeFlow.hive.shutdown() # # shutdown the hive mind
{
  claude-flow hive-mind shutdown "$@"
}

# ─────────────────────────────────────────────────────────────────────────────
# TMUX AGENT COMMANDS
# ─────────────────────────────────────────────────────────────────────────────

# Environment defaults
: ${CLAUDE_AGENTS_SESSION:=claude-agents}
: ${CLAUDE_MAIN_PANE_SIZE:=80}
: ${CLAUDE_AGENT_LAYOUT:=mainH}

claudeFlow.tmux() # <subcommand> # tmux agent management commands
{
  local cmd="$1"
  shift
  case "$cmd" in
    init|spawn|agents|focus|kill|kill.all|main|status|layout|bind|pane|run|list|task|lower)
      claudeFlow.tmux.$cmd "$@"
      ;;
    *)
      error.log "Unknown tmux command: $cmd"
      echo "Available: init, task, lower, spawn, agents, focus, kill, kill.all, main, status, layout, bind, pane, run, list"
      return 1
      ;;
  esac
}

claudeFlow.tmux.init() # # initialize two-pane layout: main (top) + task-agent (bottom)
{
  # Check if already initialized (look for task-agent pane)
  if tmux list-panes -F "#{pane_title}" 2>/dev/null | grep -q "task-agent"; then
    info.log "Task agent workspace already initialized"
    echo "Layout: Main Claude (top) + Task Agent (bottom)"
    echo ""
    echo "Run task: claudeFlow tmux.task 'your prompt here'"
    echo "Switch:   Ctrl+b ↑/↓  or  claudeFlow tmux.main/lower"
    return 0
  fi

  # Check if already in tmux
  if [ -z "$TMUX" ]; then
    info.log "Creating new tmux session: $CLAUDE_AGENTS_SESSION"
    tmux new-session -d -s "$CLAUDE_AGENTS_SESSION" -n main
    tmux split-window -v -p 30 -t "$CLAUDE_AGENTS_SESSION:main"

    # Mark panes: top = main Claude, bottom = task agent
    tmux select-pane -t "$CLAUDE_AGENTS_SESSION:main.0" -T "claude-main"
    tmux select-pane -t "$CLAUDE_AGENTS_SESSION:main.1" -T "task-agent"

    # Focus main pane (top)
    tmux select-pane -t "$CLAUDE_AGENTS_SESSION:main.0"

    # Add key bindings
    tmux bind-key -T prefix m select-pane -t "$CLAUDE_AGENTS_SESSION:main.0"
    tmux bind-key -T prefix t select-pane -t "$CLAUDE_AGENTS_SESSION:main.1"

    info.log "Attach with: tmux attach -t $CLAUDE_AGENTS_SESSION"
    echo ""
    echo "Layout:"
    echo "  ┌─────────────────────────┐"
    echo "  │  Main Claude (70%)      │  ← You are here"
    echo "  │  claude-main            │"
    echo "  ├─────────────────────────┤"
    echo "  │  Task Agent (30%)       │  ← Tasks run here"
    echo "  │  task-agent             │"
    echo "  └─────────────────────────┘"
    echo ""
    echo "Commands:"
    echo "  claudeFlow tmux.task 'prompt'  - Run task in lower pane"
    echo "  claudeFlow tmux.main           - Switch to main (top)"
    echo "  claudeFlow tmux.lower          - Switch to task (bottom)"
    echo ""
    echo "Keys: Ctrl+b m (main) | Ctrl+b t (task) | Ctrl+b ↑/↓ (navigate)"
  else
    info.log "Already in tmux, creating task-agent layout"

    # Split: 70% top (main), 30% bottom (task agent)
    tmux split-window -v -p 30

    # Mark panes
    tmux select-pane -t .0 -T "claude-main"
    tmux select-pane -t .1 -T "task-agent"

    # Add bindings
    tmux bind-key -T prefix m select-pane -t .0
    tmux bind-key -T prefix t select-pane -t .1

    # Focus main (top)
    tmux select-pane -t .0

    success.log "Task agent layout initialized"
    echo ""
    echo "Layout:"
    echo "  Top:    claude-main (this session)"
    echo "  Bottom: task-agent (run: claudeFlow tmux.task 'prompt')"
    echo ""
    echo "Keys: Ctrl+b m (main) | Ctrl+b t (task) | Ctrl+b ↑/↓ (navigate)"
  fi
}

claudeFlow.tmux.spawn() # <type> <task> # spawn agent in new tmux pane
{
  local agentType="$1"
  local task="$2"

  if [ -z "$agentType" ] || [ -z "$task" ]; then
    error.log "Usage: claudeFlow tmux.spawn <type> <task>"
    echo "Types: coder, researcher, reviewer, planner, tester"
    return 1
  fi

  # Generate agent ID
  local agentId="agent-$(date +%s | tail -c 5)"

  # Check if in tmux
  if [ -z "$TMUX" ]; then
    error.log "Not in tmux. Run 'claudeFlow tmux.init' first or attach to session"
    return 1
  fi

  # Create new pane for agent
  local paneId=$(tmux split-window -h -P -F "#{pane_id}" \
    "claude-flow agent spawn -t $agentType --id $agentId -d '$task'; echo 'Agent $agentId finished. Press Enter to close.'; read")

  # Mark the pane
  tmux select-pane -t "$paneId" -T "$agentId"

  # Apply layout
  tmux select-layout "$CLAUDE_AGENT_LAYOUT" 2>/dev/null || tmux select-layout tiled

  success.log "Spawned $agentType agent: $agentId"
  echo "Pane: $paneId"
  echo "Focus with: claudeFlow tmux.focus $agentId"
}
claudeFlow.tmux.spawn.completion.type() {
  echo "coder"
  echo "researcher"
  echo "reviewer"
  echo "planner"
  echo "tester"
}

claudeFlow.tmux.agents() # # list all agent panes
{
  echo "Agent Panes:"
  echo "─────────────────────────────────────────"

  # List panes with their titles
  tmux list-panes -a -F "#{pane_id} #{pane_title} #{pane_current_command}" 2>/dev/null | \
    grep -E "agent-|claude-main|agent-status" | \
    while read paneId title cmd; do
      local status="running"
      [ "$cmd" = "bash" ] && status="idle"
      printf "%-12s %-20s %s\n" "$paneId" "$title" "$status"
    done

  echo "─────────────────────────────────────────"
  echo ""
  echo "Navigate: Ctrl+b then arrow keys"
  echo "Zoom pane: Ctrl+b z"
}

claudeFlow.tmux.focus() # <agentId> # focus on specific agent pane
{
  local agentId="$1"

  if [ -z "$agentId" ]; then
    error.log "Usage: claudeFlow tmux.focus <agent-id>"
    return 1
  fi

  # Find pane by title
  local pane=$(tmux list-panes -a -F "#{pane_id} #{pane_title}" | grep "$agentId" | awk '{print $1}' | head -1)

  if [ -n "$pane" ]; then
    tmux select-pane -t "$pane"
    success.log "Focused on $agentId"
  else
    error.log "Agent pane not found: $agentId"
    echo "Available panes:"
    claudeFlow.tmux.agents
    return 1
  fi
}

claudeFlow.tmux.kill() # <agentId> # kill agent and close its pane
{
  local agentId="$1"

  if [ -z "$agentId" ]; then
    error.log "Usage: claudeFlow tmux.kill <agent-id>"
    return 1
  fi

  # Find pane by title
  local pane=$(tmux list-panes -a -F "#{pane_id} #{pane_title}" | grep "$agentId" | awk '{print $1}' | head -1)

  if [ -n "$pane" ]; then
    # Kill the agent via claude-flow
    claude-flow agent stop "$agentId" 2>/dev/null

    # Kill the pane
    tmux kill-pane -t "$pane"
    success.log "Killed agent and pane: $agentId"
  else
    error.log "Agent pane not found: $agentId"
    return 1
  fi
}

claudeFlow.tmux.kill.all() # # kill all agent panes, keep main
{
  # Get all agent panes (not main or status)
  local panes=$(tmux list-panes -a -F "#{pane_id} #{pane_title}" | grep "^%.*agent-[0-9]" | awk '{print $1}')

  local count=0
  for pane in $panes; do
    tmux kill-pane -t "$pane" 2>/dev/null && ((count++))
  done

  # Kill all agents via claude-flow
  claude-flow agent list --format json 2>/dev/null | \
    grep -o '"id":"[^"]*"' | \
    cut -d'"' -f4 | \
    while read aid; do
      claude-flow agent stop "$aid" 2>/dev/null
    done

  success.log "Killed $count agent panes"
}

claudeFlow.tmux.main() # # return focus to main Claude pane
{
  # Find main pane
  local pane=$(tmux list-panes -a -F "#{pane_id} #{pane_title}" | grep "claude-main" | awk '{print $1}' | head -1)

  if [ -n "$pane" ]; then
    tmux select-pane -t "$pane"
  else
    # Fallback to pane 0
    tmux select-pane -t .0
  fi
}

claudeFlow.tmux.status() # # refresh agent status display
{
  claude-flow agent list
  echo ""
  echo "─────────────────────────────────────────"
  claudeFlow.tmux.agents
}

claudeFlow.tmux.bind() # <?mode> # setup quick-switch key bindings (alt or ctrl)
{
  local mode="${1:-alt}"

  case "$mode" in
    alt)
      # Bind Alt+1-9 to switch to agent panes directly (no prefix needed)
      for i in 1 2 3 4 5 6 7 8 9; do
        tmux bind-key -n M-$i select-pane -t $i 2>/dev/null
      done
      tmux bind-key -n M-0 select-pane -t 0
      tmux bind-key -n M-n select-pane -t :.+
      tmux bind-key -n M-p select-pane -t :.-
      tmux bind-key -n M-z resize-pane -Z

      success.log "Alt-key bindings set:"
      echo "  Alt+0     → Main pane"
      echo "  Alt+1-9   → Agent panes by index"
      echo "  Alt+n/p   → Next/Previous pane"
      echo "  Alt+z     → Toggle zoom"
      ;;

    ctrl)
      # Ctrl-based bindings for environments without Alt key access
      # Ctrl+Space = show pane selector (display-panes with extended timeout)
      tmux bind-key -n C-Space display-panes -d 5000

      # Ctrl+] = next pane, Ctrl+[ = previous pane (vim-like)
      tmux bind-key -n C-] select-pane -t :.+
      tmux bind-key -n 'C-[' select-pane -t :.- 2>/dev/null || true

      # Ctrl+\ = toggle zoom
      tmux bind-key -n 'C-\' resize-pane -Z

      # Ctrl+_ = return to main pane (pane 0)
      tmux bind-key -n C-_ select-pane -t 0

      # Prefix-based alternatives (Ctrl+b then key)
      tmux bind-key Tab select-pane -t :.+
      tmux bind-key BTab select-pane -t :.-
      tmux bind-key Space display-panes -d 5000

      success.log "Ctrl-key bindings set:"
      echo "  Ctrl+Space    → Show pane selector (press number to switch)"
      echo "  Ctrl+]        → Next pane"
      echo "  Ctrl+\\        → Toggle zoom"
      echo "  Ctrl+_        → Main pane (pane 0)"
      echo ""
      echo "  Ctrl+b Tab    → Next pane"
      echo "  Ctrl+b Shift+Tab → Previous pane"
      echo "  Ctrl+b Space  → Show pane selector"
      ;;

    *)
      echo "Usage: claudeFlow tmux.bind [alt|ctrl]"
      echo "  alt  - Alt+0-9 bindings (default)"
      echo "  ctrl - Ctrl-based bindings for restricted environments"
      return 1
      ;;
  esac
}
claudeFlow.tmux.bind.completion.mode() {
  echo "alt"
  echo "ctrl"
}

claudeFlow.tmux.pane() # <name> <?command> # create named pane for agent/command
{
  local name="$1"
  local cmd="${2:-bash}"

  if [ -z "$name" ]; then
    error.log "Usage: claudeFlow tmux.pane <name> [command]"
    return 1
  fi

  if [ -z "$TMUX" ]; then
    error.log "Not in tmux"
    return 1
  fi

  # Create pane and capture its ID
  local paneId=$(tmux split-window -h -P -F "#{pane_id}" "$cmd")

  # Set pane title
  tmux select-pane -t "$paneId" -T "$name"

  # Apply layout
  tmux select-layout tiled 2>/dev/null

  # Get pane index for keybinding info
  local paneIdx=$(tmux display-message -p -t "$paneId" "#{pane_index}")

  success.log "Created pane '$name' (index: $paneIdx)"
  echo "Switch with: Alt+$paneIdx"
}

claudeFlow.tmux.run() # <name> <command...> # run command in new named pane
{
  local name="$1"
  shift
  local cmd="$*"

  if [ -z "$name" ] || [ -z "$cmd" ]; then
    error.log "Usage: claudeFlow tmux.run <name> <command...>"
    return 1
  fi

  # Create pane with command, keep open after completion
  claudeFlow.tmux.pane "$name" "$cmd; echo ''; echo '─── $name finished ───'; read -p 'Press Enter to close'"
}

claudeFlow.tmux.list() # # list panes with quick-switch indices
{
  echo "Pane Quick-Switch Reference:"
  echo "─────────────────────────────────────────"
  tmux list-panes -F "  Alt+#{pane_index}  →  #{pane_title} (#{pane_current_command})"
  echo "─────────────────────────────────────────"
  echo "  Alt+n/p  →  Next/Previous"
  echo "  Alt+z    →  Toggle zoom"
}

claudeFlow.tmux.layout() # <type> # change agent pane layout
{
  local layout="$1"

  if [ -z "$layout" ]; then
    echo "Layouts: mainH, mainV, evenH, evenV, tiled"
    return 0
  fi

  case "$layout" in
    mainH)  tmux select-layout main-horizontal ;;
    mainV)  tmux select-layout main-vertical ;;
    evenH)  tmux select-layout even-horizontal ;;
    evenV)  tmux select-layout even-vertical ;;
    tiled)  tmux select-layout tiled ;;
    *)
      error.log "Unknown layout: $layout"
      echo "Layouts: mainH, mainV, evenH, evenV, tiled"
      return 1
      ;;
  esac

  success.log "Applied layout: $layout"
}
claudeFlow.tmux.layout.completion.type() {
  echo "mainH"
  echo "mainV"
  echo "evenH"
  echo "evenV"
  echo "tiled"
}

claudeFlow.tmux.task() # <prompt> <?model> # run claude task in lower pane
{
  local prompt="$1"
  local model="${2:-haiku}"

  if [ -z "$prompt" ]; then
    error.log "Usage: claudeFlow tmux.task <prompt> [model]"
    echo "  model: haiku (default, fast), sonnet, opus"
    echo "Example: claudeFlow tmux.task 'explore the config module' sonnet"
    return 1
  fi

  if [ -z "$TMUX" ]; then
    error.log "Not in tmux. Start tmux or run: claudeFlow tmux.init"
    return 1
  fi

  # Find or create lower pane for task agents
  local lowerPane=$(tmux list-panes -F "#{pane_id} #{pane_title}" | grep "task-agent" | awk '{print $1}' | head -1)

  if [ -z "$lowerPane" ]; then
    # Create lower pane if it doesn't exist
    lowerPane=$(tmux split-window -v -p 30 -P -F "#{pane_id}" "bash")
    tmux select-pane -t "$lowerPane" -T "task-agent"
    # Return focus to upper pane
    tmux select-pane -t .0
  fi

  # Clear previous output and run new task
  "$OOSH_DIR/otmux" send "$lowerPane" C-c 2>/dev/null  # Kill any running process
  "$OOSH_DIR/otmux" send "$lowerPane" "clear" Enter

  # Build the claude command (use permission-mode for safer execution)
  local claudeCmd="claude --model $model --print"

  # Add permission mode if not root (dangerously-skip-permissions fails as root)
  if [ "$(id -u)" != "0" ]; then
    claudeCmd="$claudeCmd --dangerously-skip-permissions"
  fi

  claudeCmd="$claudeCmd '$prompt'"

  # Send to lower pane
  "$OOSH_DIR/otmux" send "$lowerPane" "$claudeCmd" Enter

  success.log "Task started in lower pane (model: $model)"
  echo "Lower pane: $lowerPane"
  echo "Switch to it: Ctrl+b ↓  or  claudeFlow tmux.lower"
  echo "Return here:  Ctrl+b ↑  or  claudeFlow tmux.main"
}
claudeFlow.tmux.task.completion.model() {
  echo "haiku"
  echo "sonnet"
  echo "opus"
}

claudeFlow.tmux.lower() # # switch focus to lower task pane
{
  if [ -z "$TMUX" ]; then
    error.log "Not in tmux"
    return 1
  fi

  # Find task-agent pane or last pane
  local lowerPane=$(tmux list-panes -F "#{pane_id} #{pane_title}" | grep "task-agent" | awk '{print $1}' | head -1)

  if [ -n "$lowerPane" ]; then
    tmux select-pane -t "$lowerPane"
  else
    # Fallback to last pane (usually lower)
    tmux select-pane -t :.+
  fi
}

# ─────────────────────────────────────────────────────────────────────────────
# CLAUDE CODE SETTINGS
# ─────────────────────────────────────────────────────────────────────────────

: ${CLAUDE_SETTINGS_GLOBAL:=$HOME/.claude/settings.json}
: ${CLAUDE_SETTINGS_PROJECT:=.claude/settings.json}
: ${CLAUDE_STATUSLINE_BACKUP:=$HOME/.claude/statusline-backup.json}

claudeFlow.statusline() # <subcommand> # manage Claude Code statusline display
{
  local cmd="$1"
  shift
  case "$cmd" in
    toggle|on|off|status|set|preview|config)
      claudeFlow.statusline.$cmd "$@"
      ;;
    *)
      error.log "Unknown statusline command: $cmd"
      echo "Available: toggle, on, off, status, set, preview, config"
      return 1
      ;;
  esac
}

claudeFlow.statusline.toggle() # # toggle Claude Flow V3 statusline footer on/off
{
  if claudeFlow.statusline.status --quiet; then
    claudeFlow.statusline.off
  else
    claudeFlow.statusline.on
  fi
}

claudeFlow.statusline.status() # <?--quiet> # check if statusline is configured
{
  local quiet=""
  [ "$1" = "--quiet" ] && quiet=1

  # Check project settings first (Claude Flow V3 footer)
  if [ -f "$CLAUDE_SETTINGS_PROJECT" ] && grep -q '"statusLine"' "$CLAUDE_SETTINGS_PROJECT" 2>/dev/null; then
    [ -z "$quiet" ] && echo "Statusline: ON (project - Claude Flow V3)"
    return 0
  fi

  # Fallback to global settings
  if [ -f "$CLAUDE_SETTINGS_GLOBAL" ] && grep -q '"statusLine"' "$CLAUDE_SETTINGS_GLOBAL" 2>/dev/null; then
    [ -z "$quiet" ] && echo "Statusline: ON (global)"
    return 0
  fi

  [ -z "$quiet" ] && echo "Statusline: OFF (not in config)"
  return 1
}

claudeFlow.statusline.off() # # disable statusline (removes statusLine from config)
{
  # Handle project settings (Claude Flow V3 footer)
  if [ -f "$CLAUDE_SETTINGS_PROJECT" ] && grep -q '"statusLine"' "$CLAUDE_SETTINGS_PROJECT"; then
    # Backup entire file
    cp "$CLAUDE_SETTINGS_PROJECT" "${CLAUDE_SETTINGS_PROJECT}.statusline-backup" 2>/dev/null || true

    if command -v jq &>/dev/null; then
      # Remove statusLine object entirely (proper way to disable)
      jq 'del(.statusLine)' "$CLAUDE_SETTINGS_PROJECT" > "${CLAUDE_SETTINGS_PROJECT}.tmp" && \
        mv "${CLAUDE_SETTINGS_PROJECT}.tmp" "$CLAUDE_SETTINGS_PROJECT"
      success.log "Claude Flow V3 footer disabled (removed from config)"
    else
      error.log "jq required to safely edit settings. Install with: oo cmd jq"
      return 1
    fi
    return 0
  fi

  # Fallback to global settings
  if [ -f "$CLAUDE_SETTINGS_GLOBAL" ] && grep -q '"statusLine"' "$CLAUDE_SETTINGS_GLOBAL"; then
    cp "$CLAUDE_SETTINGS_GLOBAL" "$CLAUDE_STATUSLINE_BACKUP" 2>/dev/null || true
    if command -v jq &>/dev/null; then
      jq 'del(.statusLine)' "$CLAUDE_SETTINGS_GLOBAL" > "${CLAUDE_SETTINGS_GLOBAL}.tmp" && \
        mv "${CLAUDE_SETTINGS_GLOBAL}.tmp" "$CLAUDE_SETTINGS_GLOBAL"
    else
      echo '{}' > "$CLAUDE_SETTINGS_GLOBAL"
    fi
    success.log "Global statusline disabled"
    return 0
  fi

  echo "Statusline already disabled (not in config)"
}

claudeFlow.statusline.on() # # enable statusline (restore from backup)
{
  # Check if already has statusLine
  if [ -f "$CLAUDE_SETTINGS_PROJECT" ] && grep -q '"statusLine"' "$CLAUDE_SETTINGS_PROJECT"; then
    echo "Statusline already enabled in project settings"
    return 0
  fi

  # Restore project settings from backup
  if [ -f "${CLAUDE_SETTINGS_PROJECT}.statusline-backup" ]; then
    if command -v jq &>/dev/null; then
      # Extract statusLine from backup and merge into current settings
      local statuslineJson=$(jq '.statusLine' "${CLAUDE_SETTINGS_PROJECT}.statusline-backup")
      if [ "$statuslineJson" != "null" ]; then
        jq --argjson sl "$statuslineJson" '.statusLine = $sl' "$CLAUDE_SETTINGS_PROJECT" > "${CLAUDE_SETTINGS_PROJECT}.tmp" && \
          mv "${CLAUDE_SETTINGS_PROJECT}.tmp" "$CLAUDE_SETTINGS_PROJECT"
        success.log "Claude Flow V3 footer restored from backup"
        return 0
      fi
    fi
  fi

  # Fallback to global settings
  if [ -f "$CLAUDE_STATUSLINE_BACKUP" ]; then
    local statuslineCmd=$(jq -r '.statusLine.command // empty' "$CLAUDE_STATUSLINE_BACKUP" 2>/dev/null)
    if [ -n "$statuslineCmd" ]; then
      [ ! -f "$CLAUDE_SETTINGS_GLOBAL" ] && echo '{}' > "$CLAUDE_SETTINGS_GLOBAL"
      jq --arg cmd "$statuslineCmd" '.statusLine = {"type": "command", "command": $cmd}' "$CLAUDE_SETTINGS_GLOBAL" > "${CLAUDE_SETTINGS_GLOBAL}.tmp" && \
        mv "${CLAUDE_SETTINGS_GLOBAL}.tmp" "$CLAUDE_SETTINGS_GLOBAL"
      success.log "Global statusline restored"
      return 0
    fi
  fi

  error.log "No backup found to restore statusline from"
  echo "Use 'claudeFlow statusline.set <command>' to configure a new statusline"
  return 1
}

claudeFlow.statusline.set() # <command> # set custom statusline command
{
  local cmd="$1"

  if [ -z "$cmd" ]; then
    error.log "Usage: claudeFlow statusline.set <command>"
    echo "Example: claudeFlow statusline.set 'echo \$(pwd)'"
    return 1
  fi

  if [ ! -f "$CLAUDE_SETTINGS_FILE" ]; then
    echo '{}' > "$CLAUDE_SETTINGS_FILE"
  fi

  if command -v jq &>/dev/null; then
    jq --arg cmd "$cmd" '.statusLine = {"type": "command", "command": $cmd}' "$CLAUDE_SETTINGS_FILE" > "$CLAUDE_SETTINGS_FILE.tmp" && \
      mv "$CLAUDE_SETTINGS_FILE.tmp" "$CLAUDE_SETTINGS_FILE"
  else
    local statuslineConfig="\"statusLine\": {\"type\": \"command\", \"command\": \"$cmd\"}"
    if grep -q '"statusLine"' "$CLAUDE_SETTINGS_FILE" 2>/dev/null; then
      sed -i "s/\"statusLine\"[^}]*}/$statuslineConfig/g" "$CLAUDE_SETTINGS_FILE" 2>/dev/null || \
      sed -i '' "s/\"statusLine\"[^}]*}/$statuslineConfig/g" "$CLAUDE_SETTINGS_FILE" 2>/dev/null
    else
      sed -i "s/}$/, $statuslineConfig}/g" "$CLAUDE_SETTINGS_FILE" 2>/dev/null || \
      sed -i '' "s/}$/, $statuslineConfig}/g" "$CLAUDE_SETTINGS_FILE" 2>/dev/null
    fi
  fi

  success.log "Statusline set: $cmd (changes apply on next prompt)"
}

claudeFlow.statusline.preview() # # preview what the statusline would display
{
  local cmd=""

  # Check project settings first
  if [ -f "$CLAUDE_SETTINGS_PROJECT" ]; then
    cmd=$(grep -o '"command"[^"]*"[^"]*"' "$CLAUDE_SETTINGS_PROJECT" 2>/dev/null | head -1 | cut -d'"' -f4)
  fi

  # Fallback to global
  if [ -z "$cmd" ] && [ -f "$CLAUDE_SETTINGS_GLOBAL" ]; then
    cmd=$(grep -o '"command"[^"]*"[^"]*"' "$CLAUDE_SETTINGS_GLOBAL" 2>/dev/null | head -1 | cut -d'"' -f4)
  fi

  if [ -z "$cmd" ]; then
    echo "Statusline: OFF (no command configured)"
    return 1
  fi

  echo "Statusline command: $cmd"
  echo "Preview output:"
  echo "─────────────────────────────────────────"
  eval "$cmd" 2>&1
  echo ""
  echo "─────────────────────────────────────────"
}

claudeFlow.statusline.config() # # show current statusline configuration
{
  echo "Project settings: $CLAUDE_SETTINGS_PROJECT"
  echo "Global settings:  $CLAUDE_SETTINGS_GLOBAL"
  echo ""

  if [ -f "$CLAUDE_SETTINGS_PROJECT" ]; then
    echo "Project .claude/settings.json (statusLine section):"
    echo "─────────────────────────────────────────"
    grep -A10 '"statusLine"' "$CLAUDE_SETTINGS_PROJECT" 2>/dev/null | head -12 || echo "(no statusLine)"
    echo "─────────────────────────────────────────"
  fi

  echo ""
  if [ -f "$CLAUDE_SETTINGS_GLOBAL" ]; then
    echo "Global ~/.claude/settings.json:"
    echo "─────────────────────────────────────────"
    cat "$CLAUDE_SETTINGS_GLOBAL"
    echo ""
    echo "─────────────────────────────────────────"
  fi
}

# ─────────────────────────────────────────────────────────────────────────────
# HOOKS COMMANDS
# ─────────────────────────────────────────────────────────────────────────────

claudeFlow.hooks() # <subcommand> # self-learning hooks system
{
  claude-flow hooks "$@"
}

# ─────────────────────────────────────────────────────────────────────────────
# EMBEDDINGS COMMANDS
# ─────────────────────────────────────────────────────────────────────────────

claudeFlow.embeddings() # <subcommand> # vector embeddings and semantic search
{
  claude-flow embeddings "$@"
}

# ─────────────────────────────────────────────────────────────────────────────
# NEURAL COMMANDS
# ─────────────────────────────────────────────────────────────────────────────

claudeFlow.neural() # <subcommand> # neural pattern training and MoE
{
  claude-flow neural "$@"
}

# ─────────────────────────────────────────────────────────────────────────────
# PERFORMANCE COMMANDS
# ─────────────────────────────────────────────────────────────────────────────

claudeFlow.performance() # <subcommand> # profiling and benchmarking
{
  claude-flow performance "$@"
}

claudeFlow.perf() # <subcommand> # shorthand for performance
{
  claudeFlow.performance "$@"
}

# ─────────────────────────────────────────────────────────────────────────────
# SECURITY COMMANDS
# ─────────────────────────────────────────────────────────────────────────────

claudeFlow.security() # <subcommand> # security scanning and threat modeling
{
  claude-flow security "$@"
}

# ─────────────────────────────────────────────────────────────────────────────
# OUTPUT OPTIONS
# ─────────────────────────────────────────────────────────────────────────────

claudeFlow.verbose() # <command> # run with verbose output
{
  claude-flow --verbose "$@"
}

claudeFlow.quiet() # <command> # run with suppressed output
{
  claude-flow --quiet "$@"
}

claudeFlow.json() # <command> # output as JSON
{
  claude-flow --format json "$@"
}

claudeFlow.table() # <command> # output as table
{
  claude-flow --format table "$@"
}

claudeFlow.interactive() # <command> # enable interactive mode
{
  claude-flow --interactive "$@"
}

claudeFlow.i() # <command> # shorthand for interactive
{
  claudeFlow.interactive "$@"
}

# ─────────────────────────────────────────────────────────────────────────────
# USAGE & HELP
# ─────────────────────────────────────────────────────────────────────────────

claudeFlow.usage()
{
  local this=${0##*/}
  echo "You started"
  echo "$0

  claudeFlow - Claude Flow wrapper for oosh
  Makes cryptic commands easy to remember!

  Usage:
  $this: command     Description
  ─────────────────────────────────────────────────────
  SYSTEM:
      init            initialize claude flow
      start           start orchestration system
      stop            stop orchestration system
      restart         restart the system
      quick           quick start with defaults
      daemon          start as background daemon
      status          show system status
      doctor          run diagnostics
      v               show version

  INSTALLATION:
      install         install claude-flow via npm
      uninstall       remove claude-flow installation
      update          update to latest version

  AGENTS:
      agent.spawn     spawn a new agent
      agent.list      list all active agents
      agent.status    show agent status
      agent.stop      stop a running agent
      agent.metrics   show performance metrics
      agent.logs      show agent logs

  TASKS:
      task.create     create a new task
      task.list       list tasks
      task.status     get task status
      task.cancel     cancel a running task
      task.assign     assign task to agent(s)
      task.retry      retry a failed task

  SESSIONS:
      session.list    list all sessions
      session.save    save current session
      session.restore restore a session
      session.delete  delete a session
      session.export  export to file
      session.import  import from file

  SWARM:
      swarm.init      initialize swarm
      swarm.v3        initialize V3 swarm
      swarm.start     start swarm
      swarm.status    show swarm status
      swarm.stop      stop swarm
      swarm.scale     scale agent count
      swarm.coordinate V3 mesh coordination

  MEMORY:
      memory.init     initialize memory DB
      memory.store    store data
      memory.get      retrieve data
      memory.search   semantic search
      memory.stats    show statistics
      memory.cleanup  clean up stale data

  MCP:
      mcp.start       start MCP server
      mcp.stop        stop MCP server
      mcp.status      show server status
      mcp.tools       list available tools
      mcp.exec        execute a tool

  HIVE-MIND:
      hive.init       initialize hive mind
      hive.spawn      spawn worker agents
      hive.task       submit tasks
      hive.consensus  manage voting
      hive.broadcast  broadcast message
      hive.shutdown   shutdown hive

  TMUX AGENTS:
      tmux.init       initialize agent workspace
      tmux.spawn      spawn agent in tmux pane
      tmux.agents     list agent panes
      tmux.focus      focus on agent pane
      tmux.kill       kill agent and pane
      tmux.kill.all   kill all agent panes
      tmux.main       return to main pane
      tmux.layout     change pane layout

  OUTPUT:
      verbose         verbose output
      quiet           suppressed output
      json            JSON format
      table           table format
      i               interactive mode
  ─────────────────────────────────────────────────────

  Examples:
    $this start                        # start system
    $this agent.spawn -t coder         # spawn coder agent
    $this task.create -d 'Add auth'    # create task
    $this swarm.v3                     # init V3 swarm
    $this memory.search 'patterns'     # semantic search
    $this hive.spawn -n 5              # spawn 5 workers
    $this tmux.init                    # setup agent workspace
    $this tmux.spawn coder 'Add auth'  # spawn in tmux pane
  "
}

claudeFlow.start()
{
  #echo "sourcing init"
  source this

  if [ -z "$1" ]; then
    # No arguments - show status
    claudeFlow.status
    return 0
  fi

  this.start "$@"
}

claudeFlow.start "$@"
