diff --git a/.agent/AGENTS.md b/.agent/AGENTS.md index b9d2c36a..0fcd425d 100644 --- a/.agent/AGENTS.md +++ b/.agent/AGENTS.md @@ -118,7 +118,7 @@ User confirms with numbered options to override if needed. | `todo/tasks/prd-*.md` | Product requirement documents | | `todo/tasks/tasks-*.md` | Implementation task lists | -**Slash commands:** `/save-todo`, `/plan-status`, `/create-prd`, `/generate-tasks`, `/log-time-spent`, `/ready`, `/sync-beads`, `/remember`, `/recall` +**Slash commands:** `/save-todo`, `/plan-status`, `/create-prd`, `/generate-tasks`, `/log-time-spent`, `/ready`, `/sync-beads`, `/remember`, `/recall`, `/session-review`, `/full-loop` **Time tracking format:** @@ -271,6 +271,12 @@ opencode mcp list ## Session Completion & Parallel Work +**Run `/session-review` before ending a session** to ensure: +- All objectives completed +- Workflow best practices followed +- Knowledge captured for future sessions +- Clear next steps identified + **Recognize session completion signals:** - All session tasks marked `[x]` in TODO.md - PR merged and release published @@ -364,7 +370,7 @@ Subagents provide specialized capabilities. Read them when tasks require domain | `services/hosting/` | Hosting providers - DNS, domains, cloud servers, managed WordPress | hostinger, hetzner, cloudflare, cloudron, closte, 101domains, spaceship | | `services/email/` | Email services - transactional email, deliverability | ses | | `services/accounting/` | Accounting integration - invoicing, expenses, financial reports | quickfile | -| `workflows/` | Development processes - branching, releases, PR reviews, quality gates | git-workflow, plans, release, version-bump, pr, preflight, postflight, ralph-loop | +| `workflows/` | Development processes - branching, releases, PR reviews, quality gates | git-workflow, plans, release, version-bump, pr, preflight, postflight, ralph-loop, session-review | | `templates/` | Document templates - PRDs, task lists, planning documents | prd-template, tasks-template, plans-template, todo-template | | `workflows/branch/` | Branch conventions - naming, purpose, merge strategies per branch type | feature, bugfix, hotfix, refactor, chore, experiment, release | | `scripts/commands/` | Slash commands - save-todo, remember, recall, code-simplifier and other interactive commands | save-todo, remember, recall, code-simplifier | @@ -469,6 +475,8 @@ Never create files in `~/` root for files needed only with the current task. | `beads-sync-helper.sh` | Sync TODO.md/PLANS.md with Beads graph | | `todo-ready.sh` | Show tasks with no open blockers | | `ralph-loop-helper.sh` | Iterative AI development loops (Ralph technique) | +| `full-loop-helper.sh` | End-to-end development loop (task → PR → deploy) | +| `session-review-helper.sh` | Gather session context for completeness review | ## Quality Workflow diff --git a/.agent/scripts/commands/full-loop.md b/.agent/scripts/commands/full-loop.md new file mode 100644 index 00000000..59a4d427 --- /dev/null +++ b/.agent/scripts/commands/full-loop.md @@ -0,0 +1,142 @@ +--- +description: Start end-to-end development loop (task → preflight → PR → postflight → deploy) +agent: Build+ +mode: subagent +--- + +Start a full development loop that chains all phases from task implementation to deployment. + +Task/Prompt: $ARGUMENTS + +## Full Loop Phases + +```text +Task Development → Preflight → PR Create → PR Review → Postflight → Deploy +``` + +## Workflow + +### Step 1: Validate Prerequisites + +Before starting, verify: + +1. **On feature branch**: Must not be on main/master +2. **Clean working directory**: Uncommitted changes should be committed or stashed +3. **Git remote configured**: Need to push and create PR + +```bash +# Check branch +git branch --show-current + +# Check for uncommitted changes +git status --short +``` + +### Step 2: Start Full Loop + +```bash +~/.aidevops/agents/scripts/full-loop-helper.sh start "$ARGUMENTS" +``` + +This will: +1. Initialize the Ralph loop for task development +2. Set up state tracking in `.claude/full-loop.local.md` +3. Begin iterating on the task + +### Step 3: Task Development (Ralph Loop) + +The AI will iterate on the task until outputting: + +```text +TASK_COMPLETE +``` + +**Completion criteria:** +- All requirements implemented +- Tests passing (if applicable) +- Code quality acceptable + +### Step 4: Automatic Phase Progression + +After task completion, the loop automatically: + +1. **Preflight**: Runs quality checks, auto-fixes issues +2. **PR Create**: Creates pull request with `gh pr create --fill` +3. **PR Review**: Monitors CI checks and review status +4. **Postflight**: Verifies release health after merge +5. **Deploy**: Runs `setup.sh` (aidevops repos only) + +### Step 5: Human Decision Points + +The loop pauses for human input at: + +| Point | When | Action Required | +|-------|------|-----------------| +| Merge approval | If repo requires human approval | Approve PR in GitHub | +| Rollback | If postflight detects issues | Decide whether to rollback | +| Scope change | If task evolves beyond original | Confirm new scope | + +### Step 6: Completion + +When all phases complete: + +```text +FULL_LOOP_COMPLETE +``` + +## Commands + +```bash +# Start new loop +/full-loop "Implement feature X with tests" + +# Check status +~/.aidevops/agents/scripts/full-loop-helper.sh status + +# Resume after interruption +~/.aidevops/agents/scripts/full-loop-helper.sh resume + +# Cancel loop +~/.aidevops/agents/scripts/full-loop-helper.sh cancel +``` + +## Options + +Pass options after the prompt: + +```bash +/full-loop "Fix bug Y" --max-task-iterations 30 --skip-postflight +``` + +| Option | Description | +|--------|-------------| +| `--max-task-iterations N` | Max iterations for task (default: 50) | +| `--max-preflight-iterations N` | Max iterations for preflight (default: 5) | +| `--max-pr-iterations N` | Max iterations for PR review (default: 20) | +| `--skip-preflight` | Skip preflight checks | +| `--skip-postflight` | Skip postflight monitoring | +| `--no-auto-pr` | Pause for manual PR creation | +| `--no-auto-deploy` | Don't auto-run setup.sh | + +## Examples + +```bash +# Basic feature implementation +/full-loop "Add user authentication with JWT tokens" + +# Bug fix with limited iterations +/full-loop "Fix memory leak in connection pool" --max-task-iterations 20 + +# Skip postflight for quick iteration +/full-loop "Update documentation" --skip-postflight + +# Manual PR creation +/full-loop "Refactor database layer" --no-auto-pr +``` + +## Related + +- `workflows/ralph-loop.md` - Ralph loop technique details +- `workflows/preflight.md` - Pre-commit quality checks +- `workflows/pr.md` - PR creation workflow +- `workflows/postflight.md` - Post-release verification diff --git a/.agent/scripts/commands/session-review.md b/.agent/scripts/commands/session-review.md new file mode 100644 index 00000000..eb124095 --- /dev/null +++ b/.agent/scripts/commands/session-review.md @@ -0,0 +1,154 @@ +--- +description: Review session for completeness, best practices, and knowledge capture +agent: Build+ +mode: subagent +--- + +Review the current session for completeness and aidevops workflow adherence. + +Focus area: $ARGUMENTS + +## Review Process + +### Step 1: Gather Context + +Run the helper script to collect session data: + +```bash +~/.aidevops/agents/scripts/session-review-helper.sh gather +``` + +### Step 2: Analyze Objectives + +Review what was accomplished in this session: + +1. **Initial Request**: What did the user originally ask for? +2. **Branch Purpose**: Does the branch name reflect the work done? +3. **Commits Made**: Do commits align with the objective? +4. **Outstanding Items**: What remains incomplete? + +Calculate completion score: +- 100%: All objectives met, no outstanding items +- 75-99%: Primary objective met, minor items remain +- 50-74%: Partial completion, significant work remains +- <50%: Major objectives incomplete + +### Step 3: Check Workflow Adherence + +Verify aidevops best practices: + +| Practice | Check | Required | +|----------|-------|----------| +| Feature branch | Not on main/master | Yes | +| Pre-edit check | Ran before first edit | Yes | +| Atomic commits | Each commit is focused | Yes | +| TODO tracking | Tasks logged appropriately | Recommended | +| Quality checks | Linters run before commit | Recommended | + +### Step 4: Identify Knowledge to Capture + +Look for learnings that should be preserved: + +1. **Corrections Made**: Did the AI make mistakes that were corrected? +2. **New Patterns**: Were new approaches discovered? +3. **Tool Issues**: Did any tools not work as expected? +4. **User Preferences**: Did the user express preferences? + +For each learning, suggest where to document: +- Agent improvements → `@agent-review` +- Code patterns → Code comments or docs +- User preferences → `memory/` files +- Temporary workarounds → TODO.md + +### Step 5: Session Health Assessment + +Determine recommendation: + +**End Session When:** +- All objectives complete +- PR merged +- Blocked on external factors +- Context becoming stale (long session) +- Topic shift to unrelated work + +**Continue Session When:** +- More work in scope +- User wants to continue +- Related follow-up tasks + +**Start New Session For:** +- Unrelated topics +- Clean context needed +- Parallel work on different branch + +## Output Format + +```text +# Session Review + +**Branch**: {branch-name} +**Duration**: {approximate} +**Date**: {YYYY-MM-DD} + +--- + +## Objective Completion: {score}% + +### Completed +- [x] {item 1} +- [x] {item 2} + +### Outstanding +- [ ] {item} - {reason/next step} + +--- + +## Workflow Adherence + +### Followed +- [x] {practice} + +### Improvements Needed +- [ ] {practice} - {recommendation} + +--- + +## Knowledge Capture + +### Should Document +- {learning}: {suggested location} + +### Action Items +1. {specific action} + +--- + +## Session Recommendation + +**Verdict**: {Continue | End Session | Start New Session} + +### Immediate Actions +1. {action} + +### For Future Sessions +- {topic}: suggest branch `{type}/{name}` + +--- + +*Review generated by /session-review* +``` + +## Quick Review (Summary Only) + +For a quick status check without full analysis: + +```bash +~/.aidevops/agents/scripts/session-review-helper.sh summary +``` + +## Integration Points + +- **Before PR**: Run to ensure nothing forgotten +- **Before ending session**: Capture learnings +- **After Ralph loop**: Verify completion promise was truly met +- **On topic shift**: Decide whether to continue or start fresh diff --git a/.agent/scripts/full-loop-helper.sh b/.agent/scripts/full-loop-helper.sh new file mode 100755 index 00000000..aace8420 --- /dev/null +++ b/.agent/scripts/full-loop-helper.sh @@ -0,0 +1,746 @@ +#!/bin/bash +# ============================================================================= +# Full Development Loop Orchestrator +# ============================================================================= +# Chains the complete development workflow: +# Task → Preflight → PR Create → PR Review → Postflight → Deploy +# +# This implements the "holy grail" of AI-assisted development - taking an idea +# from conception through to availability with minimal human intervention. +# +# Usage: +# full-loop-helper.sh start "" [options] +# full-loop-helper.sh status +# full-loop-helper.sh cancel +# full-loop-helper.sh resume +# +# Options: +# --max-task-iterations N Max iterations for task development (default: 50) +# --max-preflight-iterations N Max iterations for preflight (default: 5) +# --max-pr-iterations N Max iterations for PR review (default: 20) +# --skip-preflight Skip preflight checks (not recommended) +# --skip-postflight Skip postflight monitoring +# --no-auto-pr Don't auto-create PR, pause for human +# --no-auto-deploy Don't auto-run setup.sh (aidevops only) +# --dry-run Show what would happen without executing +# +# Human Decision Points: +# - Initial task definition (before start) +# - Merge approval (if repo requires human approval) +# - Rollback decision (if postflight detects issues) +# +# Author: AI DevOps Framework +# ============================================================================= + +set -euo pipefail + +# ============================================================================= +# Constants +# ============================================================================= + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" || exit +readonly SCRIPT_DIR +readonly STATE_DIR=".claude" +readonly STATE_FILE="${STATE_DIR}/full-loop.local.md" + +# Default settings +readonly DEFAULT_MAX_TASK_ITERATIONS=50 +readonly DEFAULT_MAX_PREFLIGHT_ITERATIONS=5 +readonly DEFAULT_MAX_PR_ITERATIONS=20 + +# Phase names +readonly PHASE_TASK="task" +readonly PHASE_PREFLIGHT="preflight" +readonly PHASE_PR_CREATE="pr-create" +readonly PHASE_PR_REVIEW="pr-review" +readonly PHASE_POSTFLIGHT="postflight" +readonly PHASE_DEPLOY="deploy" +readonly PHASE_COMPLETE="complete" + +# Colors +readonly RED='\033[0;31m' +readonly GREEN='\033[0;32m' +readonly YELLOW='\033[1;33m' +readonly BLUE='\033[0;34m' +readonly CYAN='\033[0;36m' +readonly BOLD='\033[1m' +readonly NC='\033[0m' + +# ============================================================================= +# Helper Functions +# ============================================================================= + +print_error() { + local message="$1" + echo -e "${RED}[full-loop] Error:${NC} ${message}" >&2 + return 0 +} + +print_success() { + local message="$1" + echo -e "${GREEN}[full-loop]${NC} ${message}" + return 0 +} + +print_warning() { + local message="$1" + echo -e "${YELLOW}[full-loop]${NC} ${message}" + return 0 +} + +print_info() { + local message="$1" + echo -e "${BLUE}[full-loop]${NC} ${message}" + return 0 +} + +print_phase() { + local phase="$1" + local description="$2" + echo "" + echo -e "${BOLD}${CYAN}=== Phase: ${phase} ===${NC}" + echo -e "${CYAN}${description}${NC}" + echo "" + return 0 +} + +# ============================================================================= +# State Management +# ============================================================================= + +init_state_dir() { + mkdir -p "$STATE_DIR" + return 0 +} + +save_state() { + local phase="$1" + local prompt="$2" + local pr_number="${3:-}" + local started_at="${4:-$(date -u '+%Y-%m-%dT%H:%M:%SZ')}" + + init_state_dir + + cat > "$STATE_FILE" << EOF +--- +active: true +phase: ${phase} +started_at: "${started_at}" +updated_at: "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" +pr_number: "${pr_number}" +max_task_iterations: ${MAX_TASK_ITERATIONS:-$DEFAULT_MAX_TASK_ITERATIONS} +max_preflight_iterations: ${MAX_PREFLIGHT_ITERATIONS:-$DEFAULT_MAX_PREFLIGHT_ITERATIONS} +max_pr_iterations: ${MAX_PR_ITERATIONS:-$DEFAULT_MAX_PR_ITERATIONS} +skip_preflight: ${SKIP_PREFLIGHT:-false} +skip_postflight: ${SKIP_POSTFLIGHT:-false} +no_auto_pr: ${NO_AUTO_PR:-false} +no_auto_deploy: ${NO_AUTO_DEPLOY:-false} +--- + +${prompt} +EOF + return 0 +} + +load_state() { + if [[ ! -f "$STATE_FILE" ]]; then + return 1 + fi + + # Parse YAML frontmatter + CURRENT_PHASE=$(grep '^phase:' "$STATE_FILE" | cut -d: -f2 | tr -d ' "') + STARTED_AT=$(grep '^started_at:' "$STATE_FILE" | cut -d: -f2- | tr -d ' "') + PR_NUMBER=$(grep '^pr_number:' "$STATE_FILE" | cut -d: -f2 | tr -d ' "') + MAX_TASK_ITERATIONS=$(grep '^max_task_iterations:' "$STATE_FILE" | cut -d: -f2 | tr -d ' ') + MAX_PREFLIGHT_ITERATIONS=$(grep '^max_preflight_iterations:' "$STATE_FILE" | cut -d: -f2 | tr -d ' ') + MAX_PR_ITERATIONS=$(grep '^max_pr_iterations:' "$STATE_FILE" | cut -d: -f2 | tr -d ' ') + SKIP_PREFLIGHT=$(grep '^skip_preflight:' "$STATE_FILE" | cut -d: -f2 | tr -d ' ') + SKIP_POSTFLIGHT=$(grep '^skip_postflight:' "$STATE_FILE" | cut -d: -f2 | tr -d ' ') + NO_AUTO_PR=$(grep '^no_auto_pr:' "$STATE_FILE" | cut -d: -f2 | tr -d ' ') + NO_AUTO_DEPLOY=$(grep '^no_auto_deploy:' "$STATE_FILE" | cut -d: -f2 | tr -d ' ') + + # Extract prompt (everything after the second ---) + SAVED_PROMPT=$(sed -n '/^---$/,/^---$/d; p' "$STATE_FILE") + + return 0 +} + +clear_state() { + rm -f "$STATE_FILE" + return 0 +} + +is_loop_active() { + [[ -f "$STATE_FILE" ]] && grep -q '^active: true' "$STATE_FILE" +} + +# ============================================================================= +# Detection Functions +# ============================================================================= + +is_aidevops_repo() { + local repo_root + repo_root=$(git rev-parse --show-toplevel 2>/dev/null || echo "") + + # Check if repo name contains aidevops + if [[ "$repo_root" == *"/aidevops"* ]]; then + return 0 + fi + + # Check for marker file + if [[ -f "$repo_root/.aidevops-repo" ]]; then + return 0 + fi + + # Check if setup.sh exists and contains aidevops marker + if [[ -f "$repo_root/setup.sh" ]] && grep -q "aidevops" "$repo_root/setup.sh" 2>/dev/null; then + return 0 + fi + + return 1 +} + +get_current_branch() { + git branch --show-current 2>/dev/null || echo "" +} + +is_on_feature_branch() { + local branch + branch=$(get_current_branch) + [[ -n "$branch" && "$branch" != "main" && "$branch" != "master" ]] +} + +# ============================================================================= +# Phase Execution Functions +# ============================================================================= + +run_task_phase() { + local prompt="$1" + local max_iterations="${MAX_TASK_ITERATIONS:-$DEFAULT_MAX_TASK_ITERATIONS}" + + print_phase "Task Development" "Running Ralph loop for task implementation" + + # Check if ralph-loop-helper.sh exists + if [[ ! -x "$SCRIPT_DIR/ralph-loop-helper.sh" ]]; then + print_error "ralph-loop-helper.sh not found or not executable" + return 1 + fi + + # For external tool invocation, we set up the loop and let the AI continue + "$SCRIPT_DIR/ralph-loop-helper.sh" setup "$prompt" --max-iterations "$max_iterations" --completion-promise "TASK_COMPLETE" + + print_info "Task loop initialized. AI will iterate until TASK_COMPLETE promise." + print_info "After task completion, run: full-loop-helper.sh resume" + + return 0 +} + +run_preflight_phase() { + print_phase "Preflight" "Running quality checks before commit" + + if [[ "${SKIP_PREFLIGHT:-false}" == "true" ]]; then + print_warning "Preflight skipped by user request" + echo "PREFLIGHT_PASS" + return 0 + fi + + # Run quality loop for preflight + local preflight_ran=false + if [[ -x "$SCRIPT_DIR/quality-loop-helper.sh" ]]; then + "$SCRIPT_DIR/quality-loop-helper.sh" preflight --auto-fix --max-iterations "${MAX_PREFLIGHT_ITERATIONS:-$DEFAULT_MAX_PREFLIGHT_ITERATIONS}" + preflight_ran=true + else + # Fallback to linters-local.sh + if [[ -x "$SCRIPT_DIR/linters-local.sh" ]]; then + "$SCRIPT_DIR/linters-local.sh" + preflight_ran=true + else + print_warning "No preflight script found, skipping checks" + print_info "Proceeding without preflight validation" + fi + fi + + # Only emit promise if checks actually ran + if [[ "$preflight_ran" == "true" ]]; then + echo "PREFLIGHT_PASS" + else + echo "PREFLIGHT_SKIPPED" + fi + return 0 +} + +run_pr_create_phase() { + print_phase "PR Creation" "Creating pull request" + + if [[ "${NO_AUTO_PR:-false}" == "true" ]]; then + print_warning "Auto PR creation disabled. Please create PR manually." + print_info "Run: gh pr create --fill" + print_info "Then run: full-loop-helper.sh resume" + return 0 + fi + + # Ensure we're on a feature branch + if ! is_on_feature_branch; then + print_error "Not on a feature branch. Cannot create PR from main/master." + return 1 + fi + + # Push branch if needed + local branch + branch=$(get_current_branch) + + if ! git ls-remote --exit-code --heads origin "$branch" &>/dev/null; then + print_info "Pushing branch to origin..." + git push -u origin "$branch" + fi + + # Create PR + print_info "Creating pull request..." + local pr_url + pr_url=$(gh pr create --fill 2>&1) || { + # PR might already exist + pr_url=$(gh pr view --json url --jq '.url' 2>/dev/null || echo "") + if [[ -z "$pr_url" ]]; then + print_error "Failed to create PR" + return 1 + fi + print_info "PR already exists: $pr_url" + } + + # Extract PR number + local pr_number + pr_number=$(echo "$pr_url" | grep -oE '[0-9]+$' || gh pr view --json number --jq '.number') + + print_success "PR created: $pr_url" + + # Update state with PR number + save_state "$PHASE_PR_REVIEW" "$SAVED_PROMPT" "$pr_number" "$STARTED_AT" + + return 0 +} + +run_pr_review_phase() { + print_phase "PR Review" "Monitoring PR for approval and CI checks" + + local pr_number="${PR_NUMBER:-}" + + if [[ -z "$pr_number" ]]; then + # Try to get PR number from current branch + pr_number=$(gh pr view --json number --jq '.number' 2>/dev/null || echo "") + fi + + if [[ -z "$pr_number" ]]; then + print_error "No PR number found. Create PR first." + return 1 + fi + + print_info "Monitoring PR #$pr_number..." + + # Run quality loop for PR review + if [[ -x "$SCRIPT_DIR/quality-loop-helper.sh" ]]; then + "$SCRIPT_DIR/quality-loop-helper.sh" pr-review --pr "$pr_number" --wait-for-ci --max-iterations "${MAX_PR_ITERATIONS:-$DEFAULT_MAX_PR_ITERATIONS}" + + # Verify PR was actually merged before emitting promise + local pr_state + pr_state=$(gh pr view "$pr_number" --json state --jq '.state' 2>/dev/null || echo "UNKNOWN") + if [[ "$pr_state" == "MERGED" ]]; then + echo "PR_MERGED" + else + print_warning "PR #$pr_number is $pr_state (not merged yet)" + print_info "Merge PR manually, then run: full-loop-helper.sh resume" + echo "PR_APPROVED" + fi + else + print_warning "quality-loop-helper.sh not found, waiting for manual merge" + print_info "Merge PR manually, then run: full-loop-helper.sh resume" + echo "PR_WAITING" + fi + + return 0 +} + +run_postflight_phase() { + print_phase "Postflight" "Verifying release health" + + if [[ "${SKIP_POSTFLIGHT:-false}" == "true" ]]; then + print_warning "Postflight skipped by user request" + echo "POSTFLIGHT_SKIPPED" + return 0 + fi + + # Run quality loop for postflight + local postflight_ran=false + if [[ -x "$SCRIPT_DIR/quality-loop-helper.sh" ]]; then + "$SCRIPT_DIR/quality-loop-helper.sh" postflight --monitor-duration 5m + postflight_ran=true + else + # Fallback to postflight-check.sh + if [[ -x "$SCRIPT_DIR/postflight-check.sh" ]]; then + "$SCRIPT_DIR/postflight-check.sh" + postflight_ran=true + else + print_warning "No postflight script found, skipping verification" + print_info "Proceeding without postflight validation" + fi + fi + + # Only emit promise if checks actually ran + if [[ "$postflight_ran" == "true" ]]; then + echo "RELEASE_HEALTHY" + else + echo "POSTFLIGHT_SKIPPED" + fi + return 0 +} + +run_deploy_phase() { + print_phase "Deploy" "Deploying changes locally" + + if ! is_aidevops_repo; then + print_info "Not an aidevops repo, skipping deploy phase" + return 0 + fi + + if [[ "${NO_AUTO_DEPLOY:-false}" == "true" ]]; then + print_warning "Auto deploy disabled. Run manually: ./setup.sh" + return 0 + fi + + local repo_root + repo_root=$(git rev-parse --show-toplevel) + + print_info "Running setup.sh to deploy changes..." + + if [[ -x "$repo_root/setup.sh" ]]; then + (cd "$repo_root" && ./setup.sh) + print_success "Deployment complete!" + echo "DEPLOYED" + else + print_warning "setup.sh not found or not executable" + fi + + return 0 +} + +# ============================================================================= +# Main Commands +# ============================================================================= + +cmd_start() { + local prompt="$1" + shift + + # Parse options + while [[ $# -gt 0 ]]; do + case "$1" in + --max-task-iterations) + MAX_TASK_ITERATIONS="$2" + shift 2 + ;; + --max-preflight-iterations) + MAX_PREFLIGHT_ITERATIONS="$2" + shift 2 + ;; + --max-pr-iterations) + MAX_PR_ITERATIONS="$2" + shift 2 + ;; + --skip-preflight) + SKIP_PREFLIGHT=true + shift + ;; + --skip-postflight) + SKIP_POSTFLIGHT=true + shift + ;; + --no-auto-pr) + NO_AUTO_PR=true + shift + ;; + --no-auto-deploy) + NO_AUTO_DEPLOY=true + shift + ;; + --dry-run) + DRY_RUN=true + shift + ;; + *) + print_error "Unknown option: $1" + return 1 + ;; + esac + done + + if [[ -z "$prompt" ]]; then + print_error "No prompt provided" + echo "Usage: full-loop-helper.sh start \"\" [options]" + return 1 + fi + + if is_loop_active; then + print_warning "A loop is already active. Use 'resume' to continue or 'cancel' to stop." + return 1 + fi + + # Check we're on a feature branch + if ! is_on_feature_branch; then + print_error "Must be on a feature branch to start full loop" + print_info "Create a branch first: git checkout -b feature/your-feature" + return 1 + fi + + echo "" + echo -e "${BOLD}${BLUE}╔════════════════════════════════════════════════════════════╗${NC}" + echo -e "${BOLD}${BLUE}║ FULL DEVELOPMENT LOOP - STARTING ║${NC}" + echo -e "${BOLD}${BLUE}╚════════════════════════════════════════════════════════════╝${NC}" + echo "" + echo -e "${CYAN}Task:${NC} $prompt" + echo -e "${CYAN}Branch:${NC} $(get_current_branch)" + echo "" + echo -e "${CYAN}Phases:${NC}" + echo " 1. Task Development (Ralph loop)" + echo " 2. Preflight (quality checks)" + echo " 3. PR Creation" + echo " 4. PR Review (CI + approval)" + echo " 5. Postflight (release health)" + if is_aidevops_repo; then + echo " 6. Deploy (setup.sh)" + fi + echo "" + + if [[ "${DRY_RUN:-false}" == "true" ]]; then + print_info "Dry run - no changes made" + return 0 + fi + + # Save initial state + save_state "$PHASE_TASK" "$prompt" + SAVED_PROMPT="$prompt" + + # Start task phase + run_task_phase "$prompt" + + return 0 +} + +cmd_resume() { + if ! is_loop_active; then + print_error "No active loop to resume" + return 1 + fi + + load_state + + print_info "Resuming from phase: $CURRENT_PHASE" + + case "$CURRENT_PHASE" in + "$PHASE_TASK") + # Check if task is complete + if [[ -f ".claude/ralph-loop.local.md" ]]; then + print_info "Task loop still active. Complete it first." + return 0 + fi + save_state "$PHASE_PREFLIGHT" "$SAVED_PROMPT" "" "$STARTED_AT" + run_preflight_phase + save_state "$PHASE_PR_CREATE" "$SAVED_PROMPT" "" "$STARTED_AT" + run_pr_create_phase + ;; + "$PHASE_PREFLIGHT") + run_preflight_phase + save_state "$PHASE_PR_CREATE" "$SAVED_PROMPT" "" "$STARTED_AT" + run_pr_create_phase + ;; + "$PHASE_PR_CREATE") + run_pr_create_phase + ;; + "$PHASE_PR_REVIEW") + run_pr_review_phase + save_state "$PHASE_POSTFLIGHT" "$SAVED_PROMPT" "$PR_NUMBER" "$STARTED_AT" + run_postflight_phase + save_state "$PHASE_DEPLOY" "$SAVED_PROMPT" "$PR_NUMBER" "$STARTED_AT" + run_deploy_phase + save_state "$PHASE_COMPLETE" "$SAVED_PROMPT" "$PR_NUMBER" "$STARTED_AT" + cmd_complete + ;; + "$PHASE_POSTFLIGHT") + run_postflight_phase + save_state "$PHASE_DEPLOY" "$SAVED_PROMPT" "$PR_NUMBER" "$STARTED_AT" + run_deploy_phase + save_state "$PHASE_COMPLETE" "$SAVED_PROMPT" "$PR_NUMBER" "$STARTED_AT" + cmd_complete + ;; + "$PHASE_DEPLOY") + run_deploy_phase + save_state "$PHASE_COMPLETE" "$SAVED_PROMPT" "$PR_NUMBER" "$STARTED_AT" + cmd_complete + ;; + "$PHASE_COMPLETE") + cmd_complete + ;; + *) + print_error "Unknown phase: $CURRENT_PHASE" + return 1 + ;; + esac + + return 0 +} + +cmd_status() { + if ! is_loop_active; then + echo "No active full loop" + return 0 + fi + + load_state + + echo "" + echo -e "${BOLD}Full Development Loop Status${NC}" + echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" + echo -e "Phase: ${CYAN}$CURRENT_PHASE${NC}" + echo -e "Started: $STARTED_AT" + echo -e "PR: ${PR_NUMBER:-none}" + echo "" + echo "Prompt:" + echo "$SAVED_PROMPT" | head -5 + echo "" + + return 0 +} + +cmd_cancel() { + if ! is_loop_active; then + print_warning "No active loop to cancel" + return 0 + fi + + clear_state + + # Also cancel any sub-loops + rm -f ".claude/ralph-loop.local.md" 2>/dev/null + rm -f ".claude/quality-loop.local.md" 2>/dev/null + + print_success "Full loop cancelled" + return 0 +} + +cmd_complete() { + echo "" + echo -e "${BOLD}${GREEN}╔════════════════════════════════════════════════════════════╗${NC}" + echo -e "${BOLD}${GREEN}║ FULL DEVELOPMENT LOOP - COMPLETE ║${NC}" + echo -e "${BOLD}${GREEN}╚════════════════════════════════════════════════════════════╝${NC}" + echo "" + + load_state 2>/dev/null || true + + echo -e "${GREEN}All phases completed successfully!${NC}" + echo "" + echo "Summary:" + echo " - Task: Implemented" + echo " - Preflight: Passed" + echo " - PR: #${PR_NUMBER:-unknown} merged" + echo " - Postflight: Healthy" + if is_aidevops_repo; then + echo " - Deploy: Complete" + fi + echo "" + + clear_state + + echo "FULL_LOOP_COMPLETE" + + return 0 +} + +show_help() { + cat << 'EOF' +Full Development Loop Orchestrator + +Chains the complete development workflow from task to deployment. + +USAGE: + full-loop-helper.sh [options] + +COMMANDS: + start "" Start a new full development loop + resume Resume from the current phase + status Show current loop status + cancel Cancel the active loop + help Show this help + +OPTIONS: + --max-task-iterations N Max iterations for task development (default: 50) + --max-preflight-iterations N Max iterations for preflight (default: 5) + --max-pr-iterations N Max iterations for PR review (default: 20) + --skip-preflight Skip preflight checks (not recommended) + --skip-postflight Skip postflight monitoring + --no-auto-pr Don't auto-create PR, pause for human + --no-auto-deploy Don't auto-run setup.sh (aidevops only) + --dry-run Show what would happen without executing + +PHASES: + 1. Task Development - Ralph loop for implementation + 2. Preflight - Quality checks before commit + 3. PR Creation - Auto-create pull request + 4. PR Review - Monitor CI and approval + 5. Postflight - Verify release health + 6. Deploy - Run setup.sh (aidevops repos only) + +HUMAN DECISION POINTS: + - Initial task definition (before start) + - Merge approval (if repo requires human approval) + - Rollback decision (if postflight detects issues) + +EXAMPLES: + # Start full loop for a feature + full-loop-helper.sh start "Implement user authentication with JWT" + + # Start with custom iterations + full-loop-helper.sh start "Fix all TypeScript errors" --max-task-iterations 30 + + # Resume after manual intervention + full-loop-helper.sh resume + + # Check current status + full-loop-helper.sh status + +EOF + return 0 +} + +# ============================================================================= +# Main Entry Point +# ============================================================================= + +main() { + local command="${1:-help}" + shift || true + + case "$command" in + start) + cmd_start "$@" + ;; + resume) + cmd_resume + ;; + status) + cmd_status + ;; + cancel) + cmd_cancel + ;; + help|--help|-h) + show_help + ;; + *) + print_error "Unknown command: $command" + show_help + return 1 + ;; + esac + + return 0 +} + +main "$@" diff --git a/.agent/scripts/session-review-helper.sh b/.agent/scripts/session-review-helper.sh new file mode 100755 index 00000000..5530c2a6 --- /dev/null +++ b/.agent/scripts/session-review-helper.sh @@ -0,0 +1,391 @@ +#!/usr/bin/env bash +# session-review-helper.sh - Gather session context for AI review +# Part of aidevops framework: https://aidevops.sh +# +# Usage: +# session-review-helper.sh [command] [options] +# +# Commands: +# gather Collect session context (default) +# summary Quick summary only +# json Output as JSON for programmatic use +# +# Options: +# --focus Focus on: objectives, workflow, knowledge, all (default: all) + +set -euo pipefail + +# Colors +readonly GREEN='\033[0;32m' +readonly YELLOW='\033[1;33m' +readonly RED='\033[0;31m' +readonly BLUE='\033[0;34m' +readonly CYAN='\033[0;36m' +readonly BOLD='\033[1m' +readonly NC='\033[0m' + +# Find project root (look for .git or TODO.md) +find_project_root() { + local dir="$PWD" + while [[ "$dir" != "/" ]]; do + if [[ -d "$dir/.git" ]] || [[ -f "$dir/TODO.md" ]]; then + echo "$dir" + return 0 + fi + dir="$(dirname "$dir")" + done + echo "$PWD" + return 0 +} + +# Get current branch +get_branch() { + git branch --show-current 2>/dev/null || echo "not-a-git-repo" +} + +# Check if on protected branch +is_protected_branch() { + local branch + branch=$(get_branch) + [[ "$branch" == "main" || "$branch" == "master" ]] +} + +# Get recent commits +get_recent_commits() { + local count="${1:-10}" + git log --oneline -"$count" 2>/dev/null || echo "No commits" +} + +# Get uncommitted changes count +get_uncommitted_changes() { + local staged unstaged + staged=$(git diff --cached --name-only 2>/dev/null | wc -l | tr -d '[:space:]') + unstaged=$(git diff --name-only 2>/dev/null | wc -l | tr -d '[:space:]') + echo "staged:${staged:-0},unstaged:${unstaged:-0}" +} + +# Get TODO.md status +get_todo_status() { + local project_root="$1" + local todo_file="$project_root/TODO.md" + + if [[ ! -f "$todo_file" ]]; then + echo "no-todo-file" + return + fi + + local completed incomplete in_progress + completed=$(grep -cE '^\s*- \[x\]' "$todo_file" 2>/dev/null) || completed=0 + incomplete=$(grep -cE '^\s*- \[ \]' "$todo_file" 2>/dev/null) || incomplete=0 + in_progress=$(grep -cE '^\s*- \[>\]' "$todo_file" 2>/dev/null) || in_progress=0 + + echo "completed:$completed,incomplete:$incomplete,in_progress:$in_progress" +} + +# Check for Ralph loop +get_ralph_status() { + local project_root="$1" + local ralph_file="$project_root/.claude/ralph-loop.local.md" + + if [[ -f "$ralph_file" ]]; then + local iteration max_iter + iteration=$(grep '^iteration:' "$ralph_file" 2>/dev/null | cut -d: -f2 | tr -d ' ' || echo "0") + max_iter=$(grep '^max_iterations:' "$ralph_file" 2>/dev/null | cut -d: -f2 | tr -d ' ' || echo "unlimited") + echo "active:true,iteration:$iteration,max:$max_iter" + else + echo "active:false" + fi +} + +# Get open PRs +get_pr_status() { + if command -v gh &>/dev/null; then + local open_prs + open_prs=$(gh pr list --state open --limit 5 --json number,title 2>/dev/null || echo "[]") + if [[ "$open_prs" == "[]" ]]; then + echo "no-open-prs" + else + echo "$open_prs" | jq -r '.[] | "\(.number):\(.title)"' 2>/dev/null | head -3 || echo "error-parsing" + fi + else + echo "gh-not-installed" + fi +} + +# Check workflow adherence +check_workflow_adherence() { + local project_root="$1" + local issues="" + local passed="" + + # Check if we're in a git repo + local is_git_repo=true + if ! git rev-parse --git-dir &>/dev/null; then + is_git_repo=false + issues+="not-a-git-repo," + fi + + if [[ "$is_git_repo" == "true" ]]; then + # Check 1: Not on main + if is_protected_branch; then + issues+="on-protected-branch," + else + passed+="feature-branch," + fi + + # Check 2: Recent commits have good messages + local short_messages + short_messages=$(git log --oneline -5 2>/dev/null | awk 'length($0) < 15' | wc -l | tr -d ' ' || echo "0") + short_messages="${short_messages:-0}" + if [[ "$short_messages" -gt 0 ]]; then + issues+="short-commit-messages," + else + passed+="good-commit-messages," + fi + + # Check 3: No secrets in staged files + if git diff --cached --name-only 2>/dev/null | grep -qE '\.(env|key|pem|secret)$'; then + issues+="potential-secrets-staged," + else + passed+="no-secrets-staged," + fi + fi + + # Check 4: TODO.md exists (works in any directory) + if [[ -f "$project_root/TODO.md" ]]; then + passed+="todo-exists," + else + issues+="no-todo-file," + fi + + echo "passed:${passed%,}|issues:${issues%,}" + return 0 +} + +# Gather all context +gather_context() { + local project_root="$1" + local focus="${2:-all}" + + echo -e "${BOLD}${BLUE}=== Session Review Context ===${NC}" + echo "" + + # Basic info + echo -e "${CYAN}## Environment${NC}" + echo "Project: $project_root" + echo "Branch: $(get_branch)" + echo "Date: $(date '+%Y-%m-%d %H:%M')" + echo "" + + if [[ "$focus" == "all" || "$focus" == "objectives" ]]; then + echo -e "${CYAN}## Objective Status${NC}" + echo "Recent commits:" + get_recent_commits 5 | sed 's/^/ /' + echo "" + echo "Uncommitted: $(get_uncommitted_changes)" + echo "TODO status: $(get_todo_status "$project_root")" + echo "" + fi + + if [[ "$focus" == "all" || "$focus" == "workflow" ]]; then + echo -e "${CYAN}## Workflow Adherence${NC}" + local adherence + adherence=$(check_workflow_adherence "$project_root") + local passed issues + passed=$(echo "$adherence" | cut -d'|' -f1 | cut -d: -f2) + issues=$(echo "$adherence" | cut -d'|' -f2 | cut -d: -f2) + + if [[ -n "$passed" ]]; then + echo -e "${GREEN}Passed:${NC}" + echo "$passed" | tr ',' '\n' | sed 's/^/ - /' | grep -v '^ - $' + fi + + if [[ -n "$issues" ]]; then + echo -e "${YELLOW}Issues:${NC}" + echo "$issues" | tr ',' '\n' | sed 's/^/ - /' | grep -v '^ - $' + fi + echo "" + fi + + if [[ "$focus" == "all" || "$focus" == "knowledge" ]]; then + echo -e "${CYAN}## Session Context${NC}" + echo "Ralph loop: $(get_ralph_status "$project_root")" + echo "Open PRs: $(get_pr_status)" + echo "" + fi + + # Recommendations + echo -e "${CYAN}## Quick Recommendations${NC}" + + if is_protected_branch; then + echo -e "${RED}! Create feature branch before making changes${NC}" + fi + + local todo_status + todo_status=$(get_todo_status "$project_root") + # Only show TODO stats if we have a valid TODO file + if [[ "$todo_status" != "no-todo-file" ]]; then + local incomplete + incomplete=$(echo "$todo_status" | grep -oE 'incomplete:[0-9]+' | cut -d: -f2 || echo "0") + incomplete="${incomplete:-0}" + if [[ "$incomplete" -gt 0 ]]; then + echo "- $incomplete incomplete tasks in TODO.md" + fi + fi + + local changes + changes=$(get_uncommitted_changes) + local staged unstaged + # Extract staged count (match 'staged:N' at start, before comma) + staged=$(echo "$changes" | sed -n 's/^staged:\([0-9]*\),.*/\1/p') + # Extract unstaged count (match 'unstaged:N' after comma) + unstaged=$(echo "$changes" | sed -n 's/.*,unstaged:\([0-9]*\)$/\1/p') + staged="${staged:-0}" + unstaged="${unstaged:-0}" + if [[ "$staged" -gt 0 ]] || [[ "$unstaged" -gt 0 ]]; then + echo "- Uncommitted changes: $staged staged, $unstaged unstaged" + fi + + echo "" + echo -e "${BOLD}Run /session-review in AI assistant for full analysis${NC}" + return 0 +} + +# Output as JSON +output_json() { + local project_root="$1" + + local branch todo_status ralph_status adherence changes + branch=$(get_branch) + todo_status=$(get_todo_status "$project_root") + ralph_status=$(get_ralph_status "$project_root") + adherence=$(check_workflow_adherence "$project_root") + changes=$(get_uncommitted_changes) + + # Extract values using sed for reliable parsing + local completed incomplete in_progress staged unstaged + completed=$(echo "$todo_status" | sed -n 's/.*completed:\([0-9]*\).*/\1/p') + incomplete=$(echo "$todo_status" | sed -n 's/.*incomplete:\([0-9]*\).*/\1/p') + in_progress=$(echo "$todo_status" | sed -n 's/.*in_progress:\([0-9]*\).*/\1/p') + staged=$(echo "$changes" | sed -n 's/^staged:\([0-9]*\),.*/\1/p') + unstaged=$(echo "$changes" | sed -n 's/.*,unstaged:\([0-9]*\)$/\1/p') + + cat < Focus on: objectives, workflow, knowledge, all (default: all) + +Examples: + session-review-helper.sh # Full context gathering + session-review-helper.sh summary # Quick summary + session-review-helper.sh json # JSON output + session-review-helper.sh gather --focus workflow # Focus on workflow + +EOF + return 0 +} + +# Main +main() { + local command="gather" + local focus="all" + + # Parse arguments + while [[ $# -gt 0 ]]; do + case "$1" in + gather|summary|json|help) + command="$1" + ;; + --focus) + shift + focus="${1:-all}" + ;; + --help|-h) + command="help" + ;; + *) + echo "Unknown option: $1" >&2 + show_help + exit 1 + ;; + esac + shift + done + + local project_root + project_root=$(find_project_root) + + case "$command" in + gather) + gather_context "$project_root" "$focus" + ;; + summary) + output_summary "$project_root" + ;; + json) + output_json "$project_root" + ;; + help) + show_help + ;; + *) + gather_context "$project_root" "$focus" + ;; + esac + + return 0 +} + +main "$@" diff --git a/.agent/workflows/ralph-loop.md b/.agent/workflows/ralph-loop.md index 4ed6b131..30b17959 100644 --- a/.agent/workflows/ralph-loop.md +++ b/.agent/workflows/ralph-loop.md @@ -388,6 +388,131 @@ The `quality-loop-helper.sh` script can spawn new sessions on loop completion: ~/.aidevops/agents/scripts/quality-loop-helper.sh preflight --on-complete spawn ``` +## Full Development Loop + +For end-to-end automation from task conception to deployment, use the Full Development Loop orchestrator. This chains all phases together for maximum AI utility. + +### Quick Start + +```bash +# Start full loop +~/.aidevops/agents/scripts/full-loop-helper.sh start "Implement feature X with tests" + +# Check status +~/.aidevops/agents/scripts/full-loop-helper.sh status + +# Resume after manual intervention +~/.aidevops/agents/scripts/full-loop-helper.sh resume + +# Cancel if needed +~/.aidevops/agents/scripts/full-loop-helper.sh cancel +``` + +### Loop Phases + +```text +┌─────────────────┐ +│ 1. TASK LOOP │ Ralph loop for implementation +│ (Development) │ Promise: TASK_COMPLETE +└────────┬────────┘ + │ auto + ▼ +┌─────────────────┐ +│ 2. PREFLIGHT │ Quality checks before commit +│ (Quality Gate) │ Promise: PREFLIGHT_PASS +└────────┬────────┘ + │ auto + ▼ +┌─────────────────┐ +│ 3. PR CREATE │ Auto-create pull request +│ (Auto-create) │ Output: PR URL +└────────┬────────┘ + │ auto + ▼ +┌─────────────────┐ +│ 4. PR LOOP │ Monitor CI and approval +│ (Review/CI) │ Promise: PR_MERGED +└────────┬────────┘ + │ auto + ▼ +┌─────────────────┐ +│ 5. POSTFLIGHT │ Verify release health +│ (Verify) │ Promise: RELEASE_HEALTHY +└────────┬────────┘ + │ conditional (aidevops repo only) + ▼ +┌─────────────────┐ +│ 6. DEPLOY │ Run setup.sh +│ (Local Setup) │ Promise: DEPLOYED +└─────────────────┘ +``` + +| Phase | Script | Promise | Auto-Trigger | +|-------|--------|---------|--------------| +| Task Development | `ralph-loop-helper.sh` | `TASK_COMPLETE` | Manual start | +| Preflight | `quality-loop-helper.sh preflight` | `PREFLIGHT_PASS` | After task | +| PR Creation | `gh pr create` | (PR URL) | After preflight | +| PR Review | `quality-loop-helper.sh pr-review` | `PR_MERGED` | After PR create | +| Postflight | `quality-loop-helper.sh postflight` | `RELEASE_HEALTHY` | After merge | +| Deploy | `./setup.sh` (aidevops only) | `DEPLOYED` | After postflight | + +### Human Decision Points + +The loop is designed for maximum AI autonomy while preserving human control at strategic points: + +| Phase | AI Autonomous | Human Required | +|-------|---------------|----------------| +| Task Development | Code changes, iterations, fixes | Initial task definition, scope decisions | +| Preflight | Auto-fix, re-run checks | Override to skip (emergency only) | +| PR Creation | Auto-create with `--fill` | Custom title/description if needed | +| PR Review | Address feedback, push fixes | Approve/merge (if required by repo) | +| Postflight | Monitor, report issues | Rollback decision if issues found | +| Deploy | Run `setup.sh` | None (fully autonomous) | + +### Options + +```bash +full-loop-helper.sh start "" [options] + +Options: + --max-task-iterations N Max iterations for task (default: 50) + --max-preflight-iterations N Max iterations for preflight (default: 5) + --max-pr-iterations N Max iterations for PR review (default: 20) + --skip-preflight Skip preflight checks (not recommended) + --skip-postflight Skip postflight monitoring + --no-auto-pr Don't auto-create PR, pause for human + --no-auto-deploy Don't auto-run setup.sh (aidevops only) + --dry-run Show what would happen without executing +``` + +### aidevops-Specific Behavior + +When working in the aidevops repository (detected by repo name or `.aidevops-repo` marker), the full loop automatically runs `setup.sh` after successful postflight to deploy changes locally. + +```bash +# In aidevops repo, this will auto-deploy +full-loop-helper.sh start "Add new helper script" + +# Disable auto-deploy if needed +full-loop-helper.sh start "Add new helper script" --no-auto-deploy +``` + +### State Management + +The full loop maintains state in `.claude/full-loop.local.md` (gitignored), allowing: + +- Resume after interruption +- Track current phase +- Preserve PR number across phases + +```bash +# Check current state +cat .claude/full-loop.local.md + +# Resume from where you left off +full-loop-helper.sh resume +``` + ## Learn More - Original technique: diff --git a/.agent/workflows/session-review.md b/.agent/workflows/session-review.md new file mode 100644 index 00000000..66ac786d --- /dev/null +++ b/.agent/workflows/session-review.md @@ -0,0 +1,310 @@ +--- +description: Review session for completeness, best practices, and knowledge capture +mode: subagent +tools: + read: true + write: false + edit: false + bash: true + glob: true + grep: true + task: true +--- + +# Session Review - Completeness and Best Practices Audit + + + +## Quick Reference + +- **Purpose**: Review current session for completeness, workflow adherence, and knowledge capture +- **Trigger**: `/session-review` command, end of significant work, before ending session +- **Output**: Structured assessment with actionable next steps + +**Review Categories**: +1. Objective completion - all goals achieved? +2. Workflow adherence - aidevops best practices followed? +3. Knowledge capture - learnings documented? +4. Session health - time to end or continue? + +**Key Outputs**: +- Completion score (0-100%) +- Outstanding items list +- Knowledge capture recommendations +- Session continuation advice + + + +## Command Usage + +```bash +/session-review [focus] +``` + +**Arguments**: +- `focus` (optional): Specific area to review (objectives, workflow, knowledge, all) + +**Examples**: + +```bash +/session-review # Full review +/session-review objectives # Focus on goal completion +/session-review workflow # Focus on best practices +/session-review knowledge # Focus on learnings capture +``` + +## Review Process + +### Step 1: Gather Session Context + +Collect information about the current session: + +```bash +# Check current branch and recent commits +git branch --show-current +git log --oneline -10 + +# Check TODO.md for session tasks +grep -A 20 "## In Progress" TODO.md 2>/dev/null || echo "No TODO.md" + +# Check for uncommitted changes +git status --short + +# Check for active Ralph loop +test -f .claude/ralph-loop.local.md && cat .claude/ralph-loop.local.md | head -10 + +# Check recent PR activity +gh pr list --state open --limit 5 2>/dev/null || echo "No open PRs" +``` + +### Step 2: Objective Completion Assessment + +Evaluate what was accomplished: + +| Check | Method | Weight | +|-------|--------|--------| +| Initial request fulfilled | Compare first message to current state | 40% | +| TODO items completed | Count `[x]` vs `[ ]` in session scope | 20% | +| Branch purpose achieved | Compare branch name to commits | 20% | +| Tests passing (if applicable) | Run test suite | 10% | +| No blocking errors | Check for unresolved issues | 10% | + +**Output format**: + +```text +## Objective Completion: {score}% + +### Completed +- [x] {objective 1} +- [x] {objective 2} + +### Outstanding +- [ ] {remaining item 1} - {reason/blocker} +- [ ] {remaining item 2} - {next step needed} + +### Scope Changes +- {any scope additions or reductions during session} +``` + +### Step 3: Workflow Adherence Check + +Verify aidevops best practices were followed: + +| Practice | Check | Status | +|----------|-------|--------| +| Pre-edit git check | On feature branch, not main | Required | +| TODO tracking | Tasks logged in TODO.md | Recommended | +| Commit hygiene | Atomic commits, clear messages | Required | +| Quality checks | Linters run before commit | Recommended | +| Documentation | Changes documented where needed | Situational | + +**Check commands**: + +```bash +# Verify not on main +[[ "$(git branch --show-current)" != "main" ]] && echo "OK: Feature branch" || echo "WARN: On main" + +# Check commit message quality +git log --oneline -5 | while read line; do + [[ ${#line} -gt 10 ]] && echo "OK: $line" || echo "WARN: Short message" +done + +# Check for TODO.md updates +git diff --name-only HEAD~5 | grep -q "TODO.md" && echo "OK: TODO.md updated" || echo "INFO: No TODO.md changes" +``` + +**Output format**: + +```text +## Workflow Adherence + +### Followed +- [x] Working on feature branch: {branch-name} +- [x] Commits are atomic and descriptive +- [x] {other practices followed} + +### Missed +- [ ] {practice missed} - {recommendation} + +### Recommendations +- {specific improvement for next session} +``` + +### Step 4: Knowledge Capture Assessment + +Identify learnings that should be preserved: + +| Knowledge Type | Capture Location | Priority | +|----------------|------------------|----------| +| Bug patterns discovered | Code comments, docs | High | +| Workflow improvements | Agent files, AGENTS.md | High | +| Tool discoveries | Relevant subagent | Medium | +| User preferences | memory/ files | Medium | +| Temporary workarounds | TODO.md, code comments | Low | + +**Questions to assess**: + +1. Did the AI make any mistakes that were corrected? +2. Were any new patterns or approaches discovered? +3. Did any tools or commands not work as expected? +4. Were there any "aha" moments worth preserving? +5. Did the user express preferences worth remembering? + +**Output format**: + +```text +## Knowledge Capture + +### Should Document +- {learning 1}: Suggest adding to {location} +- {learning 2}: Suggest adding to {location} + +### Already Captured +- {item already in code/docs} + +### User Preferences Noted +- {preference to remember for future sessions} +``` + +### Step 5: Session Health Assessment + +Determine if session should continue or end: + +| Signal | Indicates | Recommendation | +|--------|-----------|----------------| +| All objectives complete | Session success | End session | +| PR merged | Major milestone | End or new session | +| Context becoming stale | Long session | End session | +| Topic shift requested | New focus needed | New session | +| Blocked on external | Waiting required | End session | +| More work in scope | Continuation | Continue | + +**Output format**: + +```text +## Session Health + +**Status**: {Continue | End Recommended | End Required} +**Reason**: {explanation} + +### If Ending Session +1. {final action 1 - e.g., commit remaining changes} +2. {final action 2 - e.g., update TODO.md} +3. {final action 3 - e.g., run @agent-review} + +### If Continuing +- Next focus: {what to work on next} +- Estimated remaining: {time estimate} + +### For New Sessions +- {topic 1}: {brief description} - suggest branch: {type}/{name} +- {topic 2}: {brief description} - suggest branch: {type}/{name} +``` + +## Complete Review Output Template + +```text +# Session Review + +**Branch**: {branch-name} +**Duration**: {approximate session length} +**Date**: {YYYY-MM-DD} + +--- + +## Objective Completion: {score}% + +### Completed +{list} + +### Outstanding +{list} + +--- + +## Workflow Adherence + +### Followed +{list} + +### Improvements Needed +{list} + +--- + +## Knowledge Capture + +### Should Document +{list with locations} + +### Action Items +{specific documentation tasks} + +--- + +## Session Recommendation + +**Verdict**: {Continue | End Session | Start New Session} + +### Immediate Actions +1. {action 1} +2. {action 2} +3. {action 3} + +### For Future Sessions +{list of topics/tasks to start fresh} + +--- + +*Review generated by /session-review* +``` + +## Integration with Other Workflows + +### Before PR Creation + +Run `/session-review` before creating a PR to ensure: +- All intended changes are committed +- No outstanding items forgotten +- Documentation is complete + +### Before Ending Session + +Run `/session-review` to: +- Capture learnings via `@agent-review` +- Update TODO.md with any discovered tasks +- Ensure clean handoff for future sessions + +### After Ralph Loop Completion + +When a Ralph loop completes, `/session-review` helps: +- Verify the completion promise was truly met +- Identify any cleanup needed +- Suggest next steps + +## Related + +- `workflows/session-manager.md` - Session lifecycle management +- `tools/build-agent/agent-review.md` - Agent improvement process +- `workflows/preflight.md` - Pre-commit quality checks +- `workflows/postflight.md` - Post-release verification