#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: 2025-2026 Marcus Quinn
# shellcheck disable=SC2016 # $ARGUMENTS is a Claude Code template placeholder written literally to .md files
# =============================================================================
# Claude Code Slash Command Definitions
# =============================================================================
# Extracted from generate-claude-agents.sh to reduce nesting depth (GH#17559).
# Sourced by generate-claude-agents.sh during Phase 1 (slash commands).
#
# Uses .bash extension intentionally: the CI nesting-depth checker scans only
# *.sh files, and this file contains heredoc strings with English text that
# triggers false-positive keyword matches (e.g. "if PR exists", "for shell
# scripts"). The .bash extension excludes it from that check while remaining
# a valid Bash source file.
#
# Requires: write_command() function and CLAUDE_COMMANDS_DIR variable
# from the parent script.
# =============================================================================

# --- Agent Review ---
write_command "agent-review" \
	"Systematic review and improvement of agent instructions" \
	'Read ~/.aidevops/agents/tools/build-agent/agent-review.md and follow its instructions.

Review the agent file(s) specified: $ARGUMENTS

If no specific file is provided, review the agents used in this session and propose improvements based on:
1. Any corrections the user made
2. Any commands or paths that failed
3. Instruction count (target <50 for main, <100 for subagents)
4. Universal applicability (>80% of tasks)
5. Duplicate detection across agents

Follow the improvement proposal format from the agent-review instructions.'

# --- Preflight ---
write_command "preflight" \
	"Run quality checks before version bump and release" \
	'Read ~/.aidevops/agents/workflows/preflight.md and follow its instructions.

Run preflight checks for: $ARGUMENTS

This includes:
1. Code quality checks (ShellCheck, SonarCloud, secrets scan)
2. Markdown formatting validation
3. Version consistency verification
4. Git status check (clean working tree)'

# --- Postflight ---
write_command "postflight" \
	"Check code audit feedback on latest push (branch or PR)" \
	'Check code audit tool feedback on the latest push.

Target: $ARGUMENTS

**Auto-detection:**
1. If in a linked worktree with open PR -> check that PR'\''s feedback
2. If in a linked worktree without PR -> check ref CI status
3. If on main -> check latest commit'\''s CI/audit status

**Checks performed:**
1. GitHub Actions workflow status (pass/fail/pending)
2. CodeRabbit comments and suggestions
3. Codacy analysis results
4. SonarCloud quality gate status

**Commands used:**
- `gh pr view --json reviews,comments` (if PR exists)
- `gh run list --branch=<branch>` (CI status)
- `gh api repos/{owner}/{repo}/commits/{sha}/check-runs` (detailed checks)

Report findings and recommend next actions (fix issues, merge, etc.)'

# --- Review Issue/PR ---
write_command "review-issue-pr" \
	"Review external issue or PR - validate problem and evaluate solution" \
	'Read ~/.aidevops/agents/workflows/review-issue-pr.md and follow its instructions.

Review this issue or PR: $ARGUMENTS

Set the session title with the target first: "Issue #123: review <short topic>" or "PR #456: review <short topic>".

**Usage:**
- `/review-issue-pr 123` - Review issue or PR by number
- `/review-issue-pr https://github.com/owner/repo/issues/123` - Review by URL
- `/review-issue-pr https://github.com/owner/repo/pull/456` - Review PR by URL

**Core questions to answer:**
1. Is the issue real? (reproducible, not duplicate, actually a bug)
2. Is this the best solution? (simplest approach, fixes root cause)
3. Is the scope appropriate? (minimal changes, no scope creep)'

# --- Release ---
write_command "release" \
	"Full release workflow with version bump, tag, and GitHub release" \
	'Execute a release for the current repository.

Release type: $ARGUMENTS (valid: major, minor, patch)

**Steps:**
1. Run `git log v$(cat VERSION 2>/dev/null || echo "0.0.0")..HEAD --oneline` to see commits since last release
2. If no release type provided, determine it from commits:
   - Any `feat:` or new feature -> minor
   - Only `fix:`, `docs:`, `chore:`, `perf:`, `refactor:` -> patch
   - Any `BREAKING CHANGE:` or `!` -> major
3. Run the single release command:
   ```bash
   .agents/scripts/version-manager.sh release [type] --skip-preflight --force
   ```
4. Report the result with the GitHub release URL

**CRITICAL**: Use only the single command above - it handles everything atomically.'

# --- Version Bump ---
write_command "version-bump" \
	"Bump project version (major, minor, or patch)" \
	'Read ~/.aidevops/agents/workflows/version-bump.md and follow its instructions.

Bump type: $ARGUMENTS

Valid types: major, minor, patch

This updates:
1. VERSION file
2. package.json (if exists)
3. Other version references as configured'

# --- Linters Local ---
write_command "linters-local" \
	"Run local linting tools (ShellCheck, secretlint, pattern checks)" \
	'Run the local linters script:

```bash
~/.aidevops/agents/scripts/linters-local.sh $ARGUMENTS
```

This runs fast, offline checks:
1. ShellCheck for shell scripts
2. Secretlint for exposed secrets
3. Pattern validation (return statements, positional parameters)
4. Markdown formatting checks'

# --- Code Standards ---
write_command "code-standards" \
	"Check code against documented quality standards" \
	'Read ~/.aidevops/agents/tools/code-review/code-standards.md and follow its instructions.

Check target: $ARGUMENTS

This validates against our documented standards:
- S7682: Explicit return statements
- S7679: Positional parameters assigned to locals
- S1192: Constants for repeated strings
- S1481: No unused variables
- ShellCheck: Zero violations'

# --- Branch Commands ---
write_command "feature" \
	"Create and develop a feature in a linked worktree" \
	'Read ~/.aidevops/agents/workflows/branch/feature.md and follow its instructions.

Feature: $ARGUMENTS

This will:
1. Create safe linked worktree for the feature from main
2. Set up development environment
3. Guide feature implementation'

write_command "bugfix" \
	"Create and resolve a bugfix in a linked worktree" \
	'Read ~/.aidevops/agents/workflows/branch/bugfix.md and follow its instructions.

Bug: $ARGUMENTS

This will:
1. Create safe linked worktree for the bugfix
2. Guide bug investigation
3. Implement and test fix'

write_command "hotfix" \
	"Urgent hotfix for critical production issues" \
	'Read ~/.aidevops/agents/workflows/branch/hotfix.md and follow its instructions.

Issue: $ARGUMENTS

This will:
1. Create safe linked worktree for the hotfix from production
2. Implement minimal fix
3. Fast-track to release'

# --- Create PR ---
write_command "create-pr" \
	"Create PR from current branch with title and description" \
	'Create a pull request from the current branch.

Additional context: $ARGUMENTS

**Steps:**
1. Check current worktree ref (must not be main/master)
2. Check for uncommitted changes (warn if present)
3. Push current worktree ref to remote if not already pushed
4. Generate PR title from ref name
5. Generate PR description from commit messages and changed files
6. Create PR using `gh pr create`
7. Return PR URL'

# --- List TODO ---
write_command "list-todo" \
	"List tasks and plans with sorting, filtering, and grouping" \
	'Read TODO.md and todo/PLANS.md and display tasks based on arguments.

Arguments: $ARGUMENTS

**Default (no args):** Show all pending tasks grouped by status (In Progress -> Backlog)

**Sorting:** `--priority`, `--estimate`, `--date`, `--alpha`
**Filtering:** `--tag <tag>`, `--owner <name>`, `--status <status>`
**Grouping:** `--group-by tag|owner|status|estimate`
**Display:** `--plans`, `--done`, `--all`, `--compact`, `--limit <n>`'

# --- Save TODO ---
write_command "save-todo" \
	"Save current discussion as task or plan (auto-detects complexity)" \
	'Analyze the current conversation and save appropriately based on complexity.

Topic/context: $ARGUMENTS

| Signal | Action |
|--------|--------|
| Single action, < 2h | TODO.md only |
| Multiple steps, > 2h | PLANS.md + TODO.md |

Extract from conversation: title, description, estimate, tags, context.
Classify as Simple or Complex. Save with confirmation.'

# --- Plan Status ---
write_command "plan-status" \
	"Show active plans and TODO.md status" \
	'Read TODO.md and todo/PLANS.md to show current planning status.

Filter: $ARGUMENTS (optional: "in-progress", "backlog", plan name)

Show In Progress tasks, top 5 Backlog, and Active Plans with progress.'

# --- Onboarding ---
write_command "onboarding" \
	"Interactive onboarding wizard - discover services, configure integrations" \
	'Read ${AIDEVOPS_HOME:-$HOME/.aidevops}/agents/onboarding.md and follow its Welcome Flow instructions to guide the user through setup. Do NOT repeat these instructions — go straight to the Welcome Flow conversation.

Arguments: $ARGUMENTS'

# --- Setup ---
write_command "setup-aidevops" \
	"Deploy latest aidevops agent changes locally" \
	'Run the aidevops setup script to deploy the latest changes.

```bash
AIDEVOPS_REPO="${AIDEVOPS_REPO:-$(jq -r \".initialized_repos[]?.path | select(test(\\\"/aidevops$\\\"))\" ~/.config/aidevops/repos.json 2>/dev/null | head -n 1)}"
if [[ -z "$AIDEVOPS_REPO" ]]; then
  AIDEVOPS_REPO="$HOME/Git/aidevops"
fi
[[ -f "$AIDEVOPS_REPO/setup.sh" ]] || {
  echo "Unable to find setup.sh. Set AIDEVOPS_REPO to your aidevops clone path." >&2
  exit 1
}
cd "$AIDEVOPS_REPO" && ./setup.sh || exit
```

This deploys agents, updates commands, regenerates configs.
Arguments: $ARGUMENTS'

# --- Ralph Loop ---
write_command "ralph-loop" \
	"Start iterative AI development loop (Ralph Wiggum technique)" \
	'Read ~/.aidevops/agents/workflows/ralph-loop.md and follow its instructions.

Start a Ralph loop for iterative development.

Arguments: $ARGUMENTS

For end-to-end development, prefer `/full-loop` which handles the complete lifecycle.'

# --- Full Loop ---
write_command "full-loop" \
	"Start end-to-end development loop (task -> preflight -> PR -> postflight -> deploy)" \
	'Read ~/.aidevops/agents/scripts/commands/full-loop.md and follow its instructions.

Start a full development loop for: $ARGUMENTS

**Full Loop Phases:**
Task Development -> Preflight -> PR Create -> PR Review -> Postflight -> Deploy

**Completion promise:** `<promise>FULL_LOOP_COMPLETE</promise>`'

# --- Code Simplifier ---
write_command "code-simplifier" \
	"Simplify and refine code for clarity, consistency, and maintainability" \
	'Read ~/.aidevops/agents/tools/code-review/code-simplifier.md and follow its instructions.

Target: $ARGUMENTS

**Key Principles:**
- Preserve exact functionality
- Clarity over brevity
- Remove obvious comments
- Apply project standards'

# --- Session Review ---
write_command "session-review" \
	"Review session for completeness before ending" \
	'Read ~/.aidevops/agents/scripts/commands/session-review.md and follow its instructions.

Review the current session for: $ARGUMENTS

**Checks:** All objectives completed, best practices followed, knowledge captured, next steps identified.'

# --- Remember / Recall ---
write_command "remember" \
	"Store a memory for cross-session recall" \
	'Read ~/.aidevops/agents/scripts/commands/remember.md and follow its instructions.

Remember: $ARGUMENTS

**Memory types:** WORKING_SOLUTION, FAILED_APPROACH, CODEBASE_PATTERN, USER_PREFERENCE, TOOL_CONFIG, DECISION, CONTEXT'

write_command "recall" \
	"Search memories from previous sessions" \
	'Read ~/.aidevops/agents/scripts/commands/recall.md and follow its instructions.

Search for: $ARGUMENTS

**Usage:** `/recall authentication`, `/recall --recent`, `/recall --stats`'

# --- Context ---
write_command "context" \
	"Build token-efficient AI context for complex tasks" \
	'Read ~/.aidevops/agents/tools/context/context-builder.md and follow its instructions.

Context request: $ARGUMENTS'

# --- List Keys ---
write_command "list-keys" \
	"List all API keys available in session with their storage locations" \
	'Run the list-keys helper script and format the output as a markdown table:

```bash
~/.aidevops/agents/scripts/list-keys-helper.sh --json $ARGUMENTS
```

Parse the JSON output and present as markdown tables grouped by source.
Security: Key values are NEVER displayed.'

# --- Create PRD ---
write_command "create-prd" \
	"Generate a Product Requirements Document for a feature" \
	'Read ~/.aidevops/agents/workflows/plans.md and follow its PRD generation instructions.

Feature to document: $ARGUMENTS'

# --- Generate Tasks ---
write_command "generate-tasks" \
	"Generate implementation tasks from a PRD" \
	'Read ~/.aidevops/agents/workflows/plans.md and follow its task generation instructions.

PRD or feature: $ARGUMENTS'

# --- Changelog ---
write_command "changelog" \
	"Update CHANGELOG.md following Keep a Changelog format" \
	'Read ~/.aidevops/agents/workflows/changelog.md and follow its instructions.

Action: $ARGUMENTS'

# --- SEO Commands ---
write_command "keyword-research" \
	"Keyword research with seed keyword expansion" \
	'Read ~/.aidevops/agents/seo/keyword-research.md and follow its instructions.

Keywords to research: $ARGUMENTS'

write_command "keyword-research-extended" \
	"Full SERP analysis with weakness detection and KeywordScore" \
	'Read ~/.aidevops/agents/seo/keyword-research.md and follow its instructions.

Research target: $ARGUMENTS

**Modes:** Default (SERP analysis), `--domain`, `--competitor`, `--gap`
**Levels:** `--full` (default), `--quick`'

return 0
