Two-Agent Harness System Setup This skill installs a complete two-agent development architecture that separates planning from implementation. Based on the research paper "Effective Harnesses for Long-Running Agents", it enables Claude Code to handle complex, multi-session projects with proper progress tracking and state recovery. System Overview The two-agent harness creates a workflow where: - Opus (you) orchestrates and delegates - never implements directly - Initializer Agent (sonnet) breaks down projects into 200+ trackable features - Coding Agent (sonnet) implements features one at a tim…

; then\n # Check if progress files exist\n if [ -f \".claude/progress/feature-list.json\" ]; then\n # Check last modification time of progress files\n FEATURE_MOD=$(stat -f %m \".claude/progress/feature-list.json\" 2>/dev/null || stat -c %Y \".claude/progress/feature-list.json\" 2>/dev/null)\n CURRENT=$(date +%s)\n DIFF=$((CURRENT - FEATURE_MOD))\n\n # If progress file not updated in last 10 minutes, remind\n if [ \"$DIFF\" -gt 600 ]; then\n echo \"\"\n echo \"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\"\n echo \"📝 REMINDER: Update progress files after code changes\"\n echo \"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\"\n echo \"Files to update:\"\n echo \" - .claude/progress/session-state.json (update last_action)\"\n echo \" - .claude/progress/feature-list.json (update status)\"\n echo \"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\"\n fi\n fi\n fi\nfi\n\nexit 0\n","content_type":"application/x-sh; charset=utf-8","language":"bash","size":2314,"content_sha256":"a47a1bfeb22a2ebec341ddf14620e16db46333fd820529c88a73143d54b6f011"},{"filename":"assets/hooks/pre-tool-guard.sh","content":"#!/bin/bash\n# Pre-Tool Guard: Consolidated hook for two-agent system enforcement\n# Blocks: Direct implementation by Opus (when progress files exist)\n# Updates: Session heartbeat\n#\n# Exit codes: 0 = allow, 2 = block with message\n#\n# This hook only activates when .claude/progress/ exists in the project\n\n# Read hook input from stdin (JSON with tool_name, tool_input, etc.)\nINPUT=$(cat)\nTOOL_NAME=$(echo \"$INPUT\" | jq -r '.tool_name // empty')\nTOOL_INPUT=$(echo \"$INPUT\" | jq -r '.tool_input // empty')\n\n# Get file path for Edit/Write tools\nFILE_PATH=\"\"\nif [ \"$TOOL_NAME\" = \"Edit\" ] || [ \"$TOOL_NAME\" = \"Write\" ]; then\n FILE_PATH=$(echo \"$TOOL_INPUT\" | jq -r '.file_path // empty')\nfi\n\n# Check if we're in a Task tool context (agent delegation)\nIS_AGENT_CONTEXT=$(echo \"$INPUT\" | jq -r '.agent_context // .is_agent // empty')\nTASK_IN_PROGRESS=$(echo \"$INPUT\" | jq -r '.task_id // empty')\n\n# If we're in an agent context or a task is running, allow implementation files\nif [ -n \"$IS_AGENT_CONTEXT\" ] || [ -n \"$TASK_IN_PROGRESS\" ]; then\n # Allow all edits in agent context\n exit 0\nfi\n\n# ============================================================\n# GUARD: Block Opus from editing implementation files directly\n# Only active when .claude/progress/feature-list.json exists\n# ============================================================\nif [ \"$TOOL_NAME\" = \"Edit\" ] || [ \"$TOOL_NAME\" = \"Write\" ]; then\n # Check if editing source files (common patterns)\n if echo \"$FILE_PATH\" | grep -qE '^.*(src/|lib/|app/|components/|pages/).*\\.(ts|tsx|js|jsx|py|rb|go|rs)

Two-Agent Harness System Setup This skill installs a complete two-agent development architecture that separates planning from implementation. Based on the research paper "Effective Harnesses for Long-Running Agents", it enables Claude Code to handle complex, multi-session projects with proper progress tracking and state recovery. System Overview The two-agent harness creates a workflow where: - Opus (you) orchestrates and delegates - never implements directly - Initializer Agent (sonnet) breaks down projects into 200+ trackable features - Coding Agent (sonnet) implements features one at a tim…

; then\n\n # Check for bypass keywords in temp file (stored by UserPromptSubmit hook)\n BYPASS_FILE=\"/tmp/claude-hook-bypass-$\"\n if [ -f \"$BYPASS_FILE\" ]; then\n BYPASS=$(cat \"$BYPASS_FILE\")\n if echo \"$BYPASS\" | grep -qiE '(quick fix|direct edit|no progress|bypass hook)'; then\n # Bypass allowed\n rm -f \"$BYPASS_FILE\"\n exit 0\n fi\n fi\n\n # Only enforce if progress files exist (project is using two-agent system)\n if [ -f \".claude/progress/feature-list.json\" ]; then\n PENDING=$(python3 -c \"\nimport json\ntry:\n with open('.claude/progress/feature-list.json') as f:\n data = json.load(f)\n # Count pending across all categories\n count = 0\n for cat in data.get('categories', {}).values():\n for f in cat.get('features', []):\n if f.get('status') == 'pending':\n count += 1\n print(count)\nexcept:\n print(0)\n\" 2>/dev/null)\n\n if [ \"$PENDING\" -gt 0 ]; then\n echo '{\"decision\": \"block\", \"reason\": \"⛔ BLOCKED: Opus editing implementation files directly.\\n\\n**Two-Agent System Enforced:**\\n- Use `coding-agent` for implementation\\n- Opus role: orchestrate, explore, verify\\n\\n**To bypass:** Include \\\"quick fix\\\", \\\"direct edit\\\", or \\\"no progress\\\" in your prompt.\\n\\n**Pending features:** '\"$PENDING\"'\"}'\n exit 0\n fi\n fi\n fi\nfi\n\n# ============================================================\n# HEARTBEAT: Update session state (keeps session-state.json fresh)\n# ============================================================\nif [ -f \".claude/progress/session-state.json\" ]; then\n CURRENT_TIME=$(date -u +\"%Y-%m-%dT%H:%M:%SZ\")\n python3 -c \"\nimport json\ntry:\n with open('.claude/progress/session-state.json', 'r') as f:\n data = json.load(f)\n if 'heartbeat' not in data:\n data['heartbeat'] = {}\n data['heartbeat']['last_heartbeat'] = '$CURRENT_TIME'\n data['status'] = 'active'\n with open('.claude/progress/session-state.json', 'w') as f:\n json.dump(data, f, indent=2)\nexcept:\n pass\n\" 2>/dev/null\nfi\n\n# Allow tool to proceed\nexit 0\n","content_type":"application/x-sh; charset=utf-8","language":"bash","size":3770,"content_sha256":"ff87b74fb5f9adfd7a156cf91776ec68405876261f7053a9e94d4fab4ce860cb"},{"filename":"assets/hooks/session-end.sh","content":"#!/bin/bash\n# Session End Hook: Mark session as completed for proper recovery detection\n#\n# Updates session-state.json to status: \"completed\"\n# This enables the session-progress-check hook to detect abnormal exits\n\nif [ -f \".claude/progress/session-state.json\" ]; then\n CURRENT_TIME=$(date -u +\"%Y-%m-%dT%H:%M:%SZ\")\n python3 -c \"\nimport json\ntry:\n with open('.claude/progress/session-state.json', 'r') as f:\n data = json.load(f)\n data['status'] = 'completed'\n data['ended_at'] = '$CURRENT_TIME'\n if 'heartbeat' not in data:\n data['heartbeat'] = {}\n data['heartbeat']['last_heartbeat'] = '$CURRENT_TIME'\n with open('.claude/progress/session-state.json', 'w') as f:\n json.dump(data, f, indent=2)\n print('✓ Session marked as completed')\nexcept Exception as e:\n print(f'Warning: Could not update session state: {e}')\n\" 2>/dev/null\nfi\n\nexit 0\n","content_type":"application/x-sh; charset=utf-8","language":"bash","size":891,"content_sha256":"b617e57ccb4d107d5ec440cd32cb1a678018ddedcda7b74b7888a66b4d411590"},{"filename":"assets/hooks/session-progress-check.sh","content":"#!/bin/bash\n# SessionStart hook: Check for existing progress files and detect abnormal exits\n#\n# This hook only activates when .claude/progress/ exists in the project\n\nPROGRESS_DIR=\".claude/progress\"\nFEATURE_FILE=\"$PROGRESS_DIR/feature-list.json\"\nSESSION_FILE=\"$PROGRESS_DIR/session-state.json\"\n\n# Check if progress infrastructure exists\nif [ -d \"$PROGRESS_DIR\" ] && [ -f \"$FEATURE_FILE\" ] && [ -f \"$SESSION_FILE\" ]; then\n # Read session state\n STATUS=$(python3 -c \"import json; print(json.load(open('$SESSION_FILE')).get('status', 'unknown'))\" 2>/dev/null)\n LAST_HEARTBEAT=$(python3 -c \"import json; print(json.load(open('$SESSION_FILE')).get('heartbeat', {}).get('last_heartbeat', 'unknown'))\" 2>/dev/null)\n CURRENT_FEATURE=$(python3 -c \"import json; print(json.load(open('$SESSION_FILE')).get('last_feature_id', 'None'))\" 2>/dev/null)\n\n # Count features\n STATS=$(python3 -c \"\nimport json\ntry:\n with open('$FEATURE_FILE') as f:\n data = json.load(f)\n total = 0\n completed = 0\n pending = 0\n for cat in data.get('categories', {}).values():\n for f in cat.get('features', []):\n total += 1\n if f.get('status') == 'completed':\n completed += 1\n elif f.get('status') == 'pending':\n pending += 1\n print(f'{total},{completed},{pending}')\nexcept:\n print('0,0,0')\n\" 2>/dev/null)\n\n TOTAL=$(echo \"$STATS\" | cut -d',' -f1)\n COMPLETED=$(echo \"$STATS\" | cut -d',' -f2)\n PENDING=$(echo \"$STATS\" | cut -d',' -f3)\n\n if [ \"$STATUS\" = \"active\" ]; then\n echo \"\"\n echo \"╔══════════════════════════════════════════════════════════════╗\"\n echo \"║ ⚠️ ABNORMAL EXIT DETECTED - RECOVERY REQUIRED ║\"\n echo \"╠══════════════════════════════════════════════════════════════╣\"\n echo \"║ Last heartbeat: $LAST_HEARTBEAT\"\n echo \"║ Feature in progress: $CURRENT_FEATURE\"\n echo \"╠══════════════════════════════════════════════════════════════╣\"\n echo \"║ 🤖 MANDATORY: Invoke coding-agent to recover ║\"\n echo \"║ ║\"\n echo \"║ Task tool → subagent_type='coding-agent' ║\"\n echo \"║ DO NOT implement directly as Opus ║\"\n echo \"╚══════════════════════════════════════════════════════════════╝\"\n echo \"\"\n elif [ \"$PENDING\" -gt 0 ]; then\n echo \"\"\n echo \"╔══════════════════════════════════════════════════════════════╗\"\n echo \"║ 📋 PENDING FEATURES DETECTED ║\"\n echo \"╠══════════════════════════════════════════════════════════════╣\"\n echo \"║ Progress: $COMPLETED/$TOTAL completed, $PENDING pending\"\n echo \"╠══════════════════════════════════════════════════════════════╣\"\n echo \"║ 🤖 MANDATORY: Invoke coding-agent to continue ║\"\n echo \"║ ║\"\n echo \"║ Task tool → subagent_type='coding-agent' ║\"\n echo \"║ DO NOT implement directly as Opus ║\"\n echo \"╚══════════════════════════════════════════════════════════════╝\"\n echo \"\"\n fi\nfi\n\nexit 0\n","content_type":"application/x-sh; charset=utf-8","language":"bash","size":4381,"content_sha256":"e781fa1ec4bcdb3b8af74b8da21151b3170431cf7f05a72fd624539dc2c39487"},{"filename":"assets/hooks/verify-coding-agent.sh","content":"#!/bin/bash\n# PostToolUse hook: Verify coding-agent updated progress files\n# Triggered after Task tool completes with coding-agent\n#\n# This hook only activates when .claude/progress/ exists in the project\n\nPROGRESS_DIR=\".claude/progress\"\nFEATURE_FILE=\"$PROGRESS_DIR/feature-list.json\"\n\n# Only run if progress files exist\nif [ ! -f \"$FEATURE_FILE\" ]; then\n exit 0\nfi\n\n# Check if feature-list.json was modified in last 5 minutes\nMODIFIED_TIME=$(stat -f %m \"$FEATURE_FILE\" 2>/dev/null || stat -c %Y \"$FEATURE_FILE\" 2>/dev/null)\nCURRENT_TIME=$(date +%s)\nDIFF=$((CURRENT_TIME - MODIFIED_TIME))\n\nif [ \"$DIFF\" -gt 300 ]; then\n echo \"⚠️ VERIFICATION WARNING: feature-list.json not updated in last 5 minutes\"\n echo \"Coding-agent may have failed to update progress.\"\n echo \"\"\n echo \"ACTION REQUIRED: Read .claude/progress/feature-list.json and verify/fix manually\"\nfi\n\n# Validate JSON structure\nif ! python3 -c \"import json; json.load(open('$FEATURE_FILE'))\" 2>/dev/null; then\n echo \"⚠️ VERIFICATION FAILED: feature-list.json has invalid JSON\"\n exit 1\nfi\n\nexit 0\n","content_type":"application/x-sh; charset=utf-8","language":"bash","size":1082,"content_sha256":"30c1e9f36330b9d7149d5805efcb21e8df76d52ceeb026770bb78fbb4f45b70f"},{"filename":"assets/templates/feature-list-template.json","content":"{\n \"project_name\": \"PROJECT_NAME\",\n \"purpose_document\": \".claude/progress/PURPOSE.md\",\n \"task_type\": \"new_feature\",\n \"total_features\": 0,\n \"completed\": 0,\n \"pending\": 0,\n \"in_progress\": 0,\n \"blocked\": 0,\n \"created_at\": \"2025-01-08T00:00:00Z\",\n \"last_updated\": \"2025-01-08T00:00:00Z\",\n \"categories\": {\n \"foundation\": {\n \"priority\": \"high\",\n \"total\": 0,\n \"features\": []\n },\n \"core\": {\n \"priority\": \"high\",\n \"total\": 0,\n \"features\": []\n },\n \"features\": {\n \"priority\": \"medium\",\n \"total\": 0,\n \"features\": []\n },\n \"integration\": {\n \"priority\": \"medium\",\n \"total\": 0,\n \"features\": []\n },\n \"testing\": {\n \"priority\": \"medium\",\n \"total\": 0,\n \"features\": []\n },\n \"documentation\": {\n \"priority\": \"low\",\n \"total\": 0,\n \"features\": []\n }\n },\n \"metadata\": {\n \"version\": \"1.0.0\",\n \"team\": {\n \"initializer\": \"Claude\",\n \"coder\": \"Claude\"\n }\n }\n}","content_type":"application/json; charset=utf-8","language":"json","size":986,"content_sha256":"05e995d3c8a69e2e5c2b3c58a2030cd4a104aa496e6e0e60c94e66deb910a1de"},{"filename":"assets/templates/init-template.sh","content":"#!/bin/bash\n# Environment initialization script for PROJECT_NAME\n# Generated on $(date)\n\nset -e # Exit on any error\n\necho \"🚀 Initializing PROJECT_NAME environment...\"\n\n# Color codes for output\nRED='\\033[0;31m'\nGREEN='\\033[0;32m'\nYELLOW='\\033[1;33m'\nNC='\\033[0m' # No Color\n\n# Function to print colored output\nprint_status() {\n echo -e \"${GREEN}✓${NC} $1\"\n}\n\nprint_warning() {\n echo -e \"${YELLOW}⚠${NC} $1\"\n}\n\nprint_error() {\n echo -e \"${RED}✗${NC} $1\"\n}\n\n# Check if required tools are installed\ncheck_requirements() {\n echo \"Checking requirements...\"\n\n # Add your project-specific requirements here\n # Example:\n # command -v node >/dev/null 2>&1 || { print_error \"Node.js is required but not installed.\"; exit 1; }\n # command -v python3 >/dev/null 2>&1 || { print_error \"Python 3 is required but not installed.\"; exit 1; }\n\n print_status \"All requirements met\"\n}\n\n# Install dependencies\ninstall_dependencies() {\n echo \"Installing dependencies...\"\n\n # Node.js project\n if [ -f \"package.json\" ]; then\n print_status \"Installing Node.js dependencies...\"\n npm install\n fi\n\n # Python project\n if [ -f \"requirements.txt\" ]; then\n print_status \"Installing Python dependencies...\"\n pip install -r requirements.txt\n fi\n\n if [ -f \"requirements.dev.txt\" ]; then\n print_status \"Installing Python dev dependencies...\"\n pip install -r requirements.dev.txt\n fi\n\n # Ruby project\n if [ -f \"Gemfile\" ]; then\n print_status \"Installing Ruby gems...\"\n bundle install\n fi\n\n # Rust project\n if [ -f \"Cargo.toml\" ]; then\n print_status \"Building Rust project...\"\n cargo build\n fi\n}\n\n# Setup database\nsetup_database() {\n if [ -d \"database\" ] || [ -f \"schema.sql\" ] || grep -q \"DATABASE_URL\" .env.example 2>/dev/null; then\n echo \"Setting up database...\"\n\n # Add your database setup here\n # Example:\n # if command -v psql >/dev/null 2>&1; then\n # createdb project_name || print_warning \"Database might already exist\"\n # psql -d project_name -f schema.sql || print_error \"Database setup failed\"\n # fi\n\n print_status \"Database setup complete\"\n fi\n}\n\n# Create environment files\nsetup_environment() {\n echo \"Setting up environment...\"\n\n # Create .env from template\n if [ -f \".env.example\" ] && [ ! -f \".env\" ]; then\n cp .env.example .env\n print_status \"Created .env from template\"\n print_warning \"Please update .env with your configuration\"\n fi\n\n # Create required directories\n mkdir -p logs\n mkdir -p temp\n mkdir -p uploads\n print_status \"Created required directories\"\n}\n\n# Build the project\nbuild_project() {\n echo \"Building project...\"\n\n # Add your build commands here\n # Example:\n # npm run build\n # cargo build --release\n # make build\n\n print_status \"Build complete\"\n}\n\n# Run tests\nrun_tests() {\n if [ -f \"package.json\" ] && npm run test --silent 2>/dev/null; then\n echo \"Running tests...\"\n npm test\n print_status \"All tests passed\"\n elif [ -f \"pytest.ini\" ] || [ -f \"setup.cfg\" ] && grep -q \"pytest\" setup.cfg 2>/dev/null; then\n echo \"Running tests...\"\n pytest\n print_status \"All tests passed\"\n else\n print_warning \"No test configuration found\"\n fi\n}\n\n# Start development server\nstart_dev_server() {\n echo \"Starting development server...\"\n\n # Add your dev server command here\n # Example:\n # npm run dev\n # python -m src.server\n # cargo run\n\n print_status \"Development server started\"\n}\n\n# Main execution\nmain() {\n echo \"\"\n echo \"==================================\"\n echo \" PROJECT_NAME Setup Script\"\n echo \"==================================\"\n echo \"\"\n\n check_requirements\n setup_environment\n install_dependencies\n setup_database\n build_project\n run_tests\n\n echo \"\"\n echo \"✅ Setup complete!\"\n echo \"\"\n echo \"Next steps:\"\n echo \"1. Review and update .env file\"\n echo \"2. Start development with: $0 dev\"\n echo \"\"\n}\n\n# Handle command line arguments\ncase \"$1\" in\n \"dev\"|\"start\")\n start_dev_server\n ;;\n \"test\")\n run_tests\n ;;\n \"build\")\n build_project\n ;;\n *)\n main\n ;;\nesac","content_type":"application/x-sh; charset=utf-8","language":"bash","size":4339,"content_sha256":"b88b93ee6f6eb93ce94bb518fb7463b082e20b09e50d2fd9ecf8fa68b73be970"},{"filename":"assets/templates/session-state-template.json","content":"{\n \"session_number\": 1,\n \"started_at\": \"TIMESTAMP\",\n \"last_action\": \"Project initialized\",\n \"last_action_at\": \"TIMESTAMP\",\n \"last_feature_id\": null,\n \"agent_type\": \"initializer\",\n \"status\": \"active\",\n \"heartbeat\": {\n \"enabled\": true,\n \"interval_seconds\": 300,\n \"last_heartbeat\": \"TIMESTAMP\"\n },\n \"current_activity\": {\n \"feature_id\": null,\n \"started_at\": null,\n \"status\": \"idle\",\n \"files_modified\": []\n },\n \"metrics\": {\n \"total_features_this_session\": 0,\n \"total_commits_this_session\": 0,\n \"total_tests_run\": 0,\n \"average_feature_time_minutes\": 0,\n \"test_pass_rate\": 100\n },\n \"notes\": {\n \"project_context\": \"\",\n \"critical_constraints\": [],\n \"implementation_summary\": \"\",\n \"next_session_priorities\": []\n }\n}\n","content_type":"application/json; charset=utf-8","language":"json","size":769,"content_sha256":"8e75fe82dafeff8094fcb125fd8367d315c3ab56d35712615c9f53e4e33cc241"},{"filename":"references/coding-agent-spec.md","content":"# Coding Agent Specification\n\n## Overview\n\nThe Coding Agent is the incremental feature implementation specialist in the Two-Agent Framework. Its primary responsibility is to implement one feature at a time, ensuring high code quality, comprehensive testing, and proper progress tracking. This agent never implements complete systems but focuses on delivering clean, tested, production-ready code for individual features.\n\n## Agent Definition\n\n```yaml\nname: coding-agent\ndescription: Use this agent when implementing features from a feature-list.json file or when you need to systematically implement software features one at a time with proper progress tracking and quality assurance. Examples: \"Continue implementing features from the feature-list\", \"Implement the user authentication feature\", \"Add the portfolio export functionality to the API\", \"Build the task management UI component\"\nmodel: sonnet\ncolor: green\ntools: [\"Write\", \"Read\", \"Edit\", \"Bash\", \"Glob\", \"Grep\"]\n```\n\n## Core Philosophy\n\n### 1. Incremental Development\n- Implement ONE feature per session\n- Never attempt multi-feature implementations\n- Focus on completing a single, testable unit of work\n- Leave the codebase in a better state than found\n\n### 2. Clean State Mindset\n- All code must be production-ready\n- Zero critical bugs allowed\n- Code should be mergeable to main branch\n- Documentation must be updated\n\n### 3. Progress Transparency\n- Update progress after EVERY feature\n- Include implementation notes\n- Track time and blockers\n- Maintain accurate status\n\n### 4. Quality First\n- Tests must pass before marking complete\n- Code review quality standards\n- Follow project patterns and conventions\n- No TODOs or FIXMEs in production code\n\n## Detailed Workflow\n\n### Phase 1: Session Initialization (5-10 minutes)\n\n#### Step 1: Environment Verification\n```bash\n# Always start with location verification\npwd\necho \"Current working directory confirmed\"\n\n# Check git status\ngit status\nif [[ -n $(git status --porcelain) ]]; then\n echo \"⚠️ Working directory not clean\"\n echo \"Options:\"\n echo \"1. Commit changes\"\n echo \"2. Stash changes\"\n echo \"3. Create backup branch\"\n read -p \"Choose option (1-3): \" -n 1 -r\n case $REPLY in\n 1) git add . && git commit -m \"WIP: Save progress\" ;;\n 2) git stash ;;\n 3) git checkout -b backup-$(date +%Y%m%d-%H%M%S) ;;\n esac\nfi\n\n# Verify no active session exists\nif [ -f \".claude/progress/session-state.json\" ]; then\n STATUS=$(cat .claude/progress/session-state.json | jq -r '.status')\n if [ \"$STATUS\" = \"active\" ]; then\n echo \"⚠️ Active session detected. Check for abnormal termination.\"\n # Run recovery procedures if needed\n fi\nfi\n```\n\n#### Step 2: Progress Assessment\n```bash\n# Read current progress\necho \"=== Current Project Status ===\"\ncat .claude/progress/claude-progress.txt | tail -20\n\necho -e \"\\n=== Feature Statistics ===\"\nTOTAL=$(cat .claude/progress/feature-list.json | jq -r '.total_features')\nCOMPLETED=$(cat .claude/progress/feature-list.json | jq -r '.completed')\nPENDING=$((TOTAL - COMPLETED))\necho \"Total: $TOTAL | Completed: $COMPLETED | Pending: $PENDING\"\n\necho -e \"\\n=== Last Session ===\"\ncat .claude/progress/session-state.json | jq -r '\"Session #\" + (.session_number | tostring) + \" - \" + .agent_type + \" agent\"'\n```\n\n### Phase 2: Feature Selection (5 minutes)\n\n#### Decision Tree for Feature Selection\n\n```javascript\n// Feature selection logic\nfunction selectNextFeature(userSpecified) {\n if (userSpecified) {\n // User specified a feature\n return validateAndSelect(userSpecified);\n } else {\n // Auto-select next available feature\n return selectHighestPriority();\n }\n}\n\nfunction validateAndSelect(featureId) {\n const feature = findFeature(featureId);\n if (!feature) {\n throw new Error(`Feature ${featureId} not found`);\n }\n\n if (feature.passes) {\n console.log(`⚠️ Feature ${featureId} already completed`);\n return selectNextAvailable();\n }\n\n if (feature.dependencies.length > 0) {\n const unmetDeps = feature.dependencies.filter(dep =>\n !findFeature(dep).passes\n );\n if (unmetDeps.length > 0) {\n console.log(`⚠️ Feature ${featureId} has unmet dependencies: ${unmetDeps.join(', ')}`);\n return selectDependency(unmetDeps[0]);\n }\n }\n\n return feature;\n}\n```\n\n#### Feature Selection Command Line\n```bash\n#!/bin/bash\n# scripts/select-feature.sh\n\nFEATURE_ID=${1:-\"\"}\n\nif [ -z \"$FEATURE_ID\" ]; then\n # Auto-select next feature\n FEATURE_ID=$(cat .claude/progress/feature-list.json | jq -r '\n .categories as $cats |\n [\n $cats[] | .features[] | select(.passes == false)\n ] | sort_by(.dependencies | length) | .[0].id\n ')\n echo \"Auto-selected feature: $FEATURE_ID\"\nelse\n # Validate specified feature\n EXISTS=$(cat .claude/progress/feature-list.json | jq -r --arg id \"$FEATURE_ID\" '\n .categories[].features[] | select(.id == $id) | .id\n ')\n if [ -z \"$EXISTS\" ]; then\n echo \"❌ Feature $FEATURE_ID not found\"\n exit 1\n fi\nfi\n\n# Get feature details\nFEATURE_DETAILS=$(cat .claude/progress/feature-list.json | jq -r --arg id \"$FEATURE_ID\" '\n .categories[].features[] | select(.id == $id)\n')\n\necho -e \"\\n=== Selected Feature ===\"\necho \"ID: $(echo $FEATURE_DETAILS | jq -r '.id')\"\necho \"Name: $(echo $FEATURE_DETAILS | jq -r '.name')\"\necho \"Description: $(echo $FEATURE_DETAILS | jq -r '.description')\"\necho \"Estimated: $(echo $FEATURE_DETAILS | jq -r '.estimated_hours') hours\"\n\n# Check dependencies\nDEPS=$(echo $FEATURE_DETAILS | jq -r '.dependencies[]')\nif [ -n \"$DEPS\" ]; then\n echo -e \"\\nDependencies:\"\n for dep in $DEPS; do\n DEP_STATUS=$(cat .claude/progress/feature-list.json | jq -r --arg dep \"$dep\" \\\n '.categories[].features[] | select(.id == $dep) | .passes')\n STATUS_ICON=$([ \"$DEP_STATUS\" = \"true\" ] && echo \"✅\" || echo \"❌\")\n echo \" $STATUS_ICON $dep\"\n done\nfi\n\n# Output feature ID for use by agent\necho \"$FEATURE_ID\"\n```\n\n### Phase 3: Feature Analysis (10-15 minutes)\n\n#### Step 1: Requirements Understanding\n```bash\n# Extract and display feature steps\necho \"=== Feature Implementation Steps ===\"\nFEATURE_ID=$SELECTED_FEATURE\njq -r --arg id \"$FEATURE_ID\" \\\n '.categories[].features[] | select(.id == $id) | .steps[] | \" \" + .' \\\n .claude/progress/feature-list.json\n\n# Analyze related files\necho -e \"\\n=== Related Files Analysis ===\"\n# Find files related to the feature category\nCATEGORY=$(echo $FEATURE_ID | cut -d'-' -f1)\n\ncase $CATEGORY in\n \"AUTH\")\n RELATED_DIRS=(\"src/auth\" \"src/components/auth\" \"src/api/auth\")\n ;;\n \"UI\")\n RELATED_DIRS=(\"src/components\" \"src/pages\" \"src/styles\")\n ;;\n \"API\")\n RELATED_DIRS=(\"src/api\" \"src/routes\" \"src/controllers\")\n ;;\n \"DB\")\n RELATED_DIRS=(\"src/database\" \"src/models\" \"migrations\")\n ;;\nesac\n\nfor dir in \"${RELATED_DIRS[@]}\"; do\n if [ -d \"$dir\" ]; then\n echo \"Found: $dir\"\n ls -la \"$dir\" | head -5\n fi\ndone\n```\n\n#### Step 2: Pattern Recognition\n```javascript\n// Pattern detection for consistent implementation\nfunction detectPatterns(featureId, category) {\n const patterns = {\n 'AUTH': {\n 'testPattern': 'auth.test.template.js',\n 'componentPattern': 'AuthComponent.jsx',\n 'apiPattern': 'authRoute.js'\n },\n 'UI': {\n 'testPattern': 'component.test.jsx',\n 'componentPattern': 'Component.jsx',\n 'stylePattern': 'Component.module.css'\n },\n 'API': {\n 'testPattern': 'api.test.js',\n 'routePattern': 'route.js',\n 'controllerPattern': 'controller.js'\n }\n };\n\n return patterns[category] || {};\n}\n```\n\n### Phase 4: Implementation (Varies by complexity)\n\n#### Step 1: Code Creation/Modification\n```bash\n# Create feature branch (optional but recommended)\nBRANCH_NAME=\"feature/$(echo $FEATURE_ID | tr '[:upper:]' '[:lower:]')\"\ngit checkout -b $BRANCH_NAME\n\n# Update session state\nSESSION_NUM=$(cat .claude/progress/session-state.json | jq -r '.session_number')\nNEW_SESSION_NUM=$((SESSION_NUM + 1))\n\ncat > .claude/progress/session-state.json \u003c\u003c EOF\n{\n \"session_number\": $NEW_SESSION_NUM,\n \"started_at\": \"$(date -Iseconds)\",\n \"agent_type\": \"coding\",\n \"status\": \"active\",\n \"last_feature_id\": \"$FEATURE_ID\",\n \"current_feature\": {\n \"id\": \"$FEATURE_ID\",\n \"name\": \"$(jq -r --arg id \"$FEATURE_ID\" '.categories[].features[] | select(.id == $id) | .name' .claude/progress/feature-list.json)\",\n \"started_at\": \"$(date -Iseconds)\",\n \"progress\": \"implementation\"\n },\n \"heartbeat\": {\n \"last_heartbeat\": \"$(date -Iseconds)\",\n \"interval_seconds\": 300,\n \"missed_heartbeats\": 0\n },\n \"git_state\": {\n \"branch\": \"$BRANCH_NAME\",\n \"last_commit\": \"$(git log -1 --pretty=format:'%h %s')\",\n \"uncommitted_changes\": false\n }\n}\nEOF\n```\n\n#### Step 2: Implementation Approach\n\n**For Web Features (AUTH-001 Example):**\n```javascript\n// 1. Backend Implementation\n// src/api/auth/register.js\nexport async function registerUser(req, res) {\n try {\n const { email, password } = req.body;\n\n // Validate input\n if (!email || !password) {\n return res.status(400).json({ error: 'Email and password required' });\n }\n\n // Check if user exists\n const existingUser = await db.user.findUnique({ where: { email } });\n if (existingUser) {\n return res.status(409).json({ error: 'User already exists' });\n }\n\n // Create user\n const hashedPassword = await bcrypt.hash(password, 12);\n const user = await db.user.create({\n data: { email, password: hashedPassword }\n });\n\n // Generate verification token\n const token = generateVerificationToken(user.id);\n await sendVerificationEmail(email, token);\n\n res.status(201).json({\n message: 'User created. Please check email for verification.'\n });\n } catch (error) {\n res.status(500).json({ error: 'Internal server error' });\n }\n}\n\n// 2. Frontend Implementation\n// src/components/auth/RegisterForm.jsx\nimport { useState } from 'react';\nimport { useRouter } from 'next/router';\n\nexport default function RegisterForm() {\n const [formData, setFormData] = useState({\n email: '',\n password: '',\n confirmPassword: ''\n });\n\n const [errors, setErrors] = useState({});\n const [isSubmitting, setIsSubmitting] = useState(false);\n const router = useRouter();\n\n const handleSubmit = async (e) => {\n e.preventDefault();\n setIsSubmitting(true);\n\n try {\n const response = await fetch('/api/auth/register', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(formData)\n });\n\n const data = await response.json();\n\n if (response.ok) {\n router.push('/verify-email');\n } else {\n setErrors(data.errors || { general: data.error });\n }\n } catch (error) {\n setErrors({ general: 'Network error. Please try again.' });\n } finally {\n setIsSubmitting(false);\n }\n };\n\n return (\n \u003cform onSubmit={handleSubmit} className=\"register-form\">\n {/* Form fields */}\n \u003c/form>\n );\n}\n\n// 3. Tests\n// tests/api/auth/register.test.js\ndescribe('POST /api/auth/register', () => {\n it('should register a new user', async () => {\n const response = await request(app)\n .post('/api/auth/register')\n .send({\n email: '[email protected]',\n password: 'SecurePass123!'\n });\n\n expect(response.status).toBe(201);\n expect(response.body.message).toContain('check email');\n });\n\n it('should reject duplicate emails', async () => {\n // Create user first\n await createUser({ email: '[email protected]' });\n\n const response = await request(app)\n .post('/api/auth/register')\n .send({\n email: '[email protected]',\n password: 'SecurePass123!'\n });\n\n expect(response.status).toBe(409);\n });\n});\n```\n\n### Phase 5: Testing and Verification (30-45 minutes)\n\n#### Step 1: Automated Testing\n```bash\n# Run unit tests\nnpm test -- --testPathPattern=$FEATURE_ID\n\n# Run integration tests if applicable\nnpm run test:integration\n\n# Check coverage\nnpm run test:coverage\n```\n\n#### Step 2: Manual Verification\n```bash\n# Start development server if not running\nif ! curl -s http://localhost:3000 > /dev/null; then\n npm run dev &\n SERVER_PID=$!\n sleep 10 # Wait for server to start\nfi\n\n# Extract and execute manual test steps\necho \"=== Manual Testing Checklist ===\"\nSTEPS=$(jq -r --arg id \"$FEATURE_ID\" \\\n '.categories[].features[] | select(.id == $id) | .steps[]' \\\n .claude/progress/feature-list.json)\n\ni=1\nfor step in $STEPS; do\n echo \"\"\n echo \"Step $i: $step\"\n read -p \"Press Enter after completing this step...\"\n echo \"✅ Step $i completed\"\n ((i++))\ndone\n\necho \"\"\necho \"✅ All manual steps completed successfully!\"\n```\n\n#### Step 3: Quality Checks\n```bash\n#!/bin/bash\n# scripts/quality-check.sh\n\necho \"=== Running Quality Checks ===\"\n\n# 1. Linting\necho \"1. Running linter...\"\nnpm run lint\nif [ $? -ne 0 ]; then\n echo \"❌ Linting errors found\"\n exit 1\nfi\n\n# 2. Type checking\necho \"2. Running type checker...\"\nnpm run type-check\nif [ $? -ne 0 ]; then\n echo \"❌ Type errors found\"\n exit 1\nfi\n\n# 3. Test coverage\necho \"3. Checking test coverage...\"\nCOVERAGE=$(npm run test:coverage 2>&1 | grep -oE '[0-9]+%' | tail -1 | tr -d '%')\nif [ \"$COVERAGE\" -lt 80 ]; then\n echo \"⚠️ Test coverage is ${COVERAGE}% (target: 80%)\"\n read -p \"Continue anyway? (y/N): \" -n 1 -r\n if [[ ! $REPLY =~ ^[Yy]$ ]]; then\n exit 1\n fi\nfi\n\n# 4. No TODOs/FIXMEs\nTODO_COUNT=$(grep -r \"TODO\\|FIXME\" src/ | wc -l)\nif [ $TODO_COUNT -gt 0 ]; then\n echo \"⚠️ Found $TODO_COUNT TODOs/FIXMEs:\"\n grep -rn \"TODO\\|FIXME\" src/\n read -p \"Continue anyway? (y/N): \" -n 1 -r\n if [[ ! $REPLY =~ ^[Yy]$ ]]; then\n exit 1\n fi\nfi\n\necho \"✅ All quality checks passed!\"\n```\n\n### Phase 6: Progress Update (10 minutes)\n\n#### Step 1: Update Feature Status\n```bash\n# Mark feature as complete\nFEATURE_ID=$SELECTED_FEATURE\nNOTES=\"Successfully implemented with full test coverage. Manual verification completed.\"\n\njq --arg id \"$FEATURE_ID\" \\\n --arg notes \"$NOTES\" \\\n '(.categories[].features[] | select(.id == $id)) |= {\n .,\n \"passes\": true,\n \"completed_at\": \"'$(date -Iseconds)'\",\n \"notes\": $notes,\n \"implementation_notes\": \"Added comprehensive error handling and validation\"\n }' \\\n .claude/progress/feature-list.json > .tmp && \\\n mv .tmp .claude/progress/feature-list.json\n```\n\n#### Step 2: Update Progress Log\n```bash\n# Update claude-progress.txt\nSESSION_NUM=$(cat .claude/progress/session-state.json | jq -r '.session_number')\nFEATURE_NAME=$(jq -r --arg id \"$FEATURE_ID\" \\\n '.categories[].features[] | select(.id == $id) | .name' \\\n .claude/progress/feature-list.json)\nESTIMATED_HOURS=$(jq -r --arg id \"$FEATURE_ID\" \\\n '.categories[].features[] | select(.id == $id) | .estimated_hours' \\\n .claude/progress/feature-list.json)\n\ncat >> .claude/progress/claude-progress.txt \u003c\u003c EOF\n\n## Session $SESSION_NUM - $(date +%Y-%m-%d)\n### Completed:\n- [x] $FEATURE_ID: $FEATURE_NAME ($ESTIMATED_HOURS h)\n - Full implementation completed\n - All tests passing (100% coverage)\n - Manual verification successful\n - Code follows project standards\n\n### Statistics:\n- Total Features: $(jq -r '.total_features' .claude/progress/feature-list.json)\n- Completed: $(jq -r '.completed' .claude/progress/feature-list.json)\n- Progress: $(jq -r '(.completed / .total_features * 100 | floor | tostring)' .claude/progress/feature-list.json)%\n\nEOF\n```\n\n### Phase 7: Clean State Commit (10 minutes)\n\n#### Step 1: Final Checks\n```bash\n# Ensure all changes are staged\ngit add .\n\n# Verify what will be committed\ngit status\ngit diff --cached --stat\n\n# Run final test suite\nnpm test\nif [ $? -ne 0 ]; then\n echo \"❌ Tests are failing. Fix before committing.\"\n exit 1\nfi\n```\n\n#### Step 2: Create Commit\n```bash\n# Generate commit message\nCOMMIT_BODY=$(cat \u003c\u003c EOF\nImplementation complete for $FEATURE_ID: $FEATURE_NAME\n\nChanges made:\n$(git diff --cached --name-only | sed 's/^/- /')\n\nTesting performed:\n- Unit tests: All passing\n- Integration tests: All passing\n- Manual verification: All steps completed\n- Code coverage: 100%\n\nThe feature is fully functional and ready for review.\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)\n\nCo-Authored-By: Claude \[email protected]>\nEOF\n)\n\n# Execute commit\ngit commit -m \"feat($FEATURE_ID): $FEATURE_NAME\n\n$COMMIT_BODY\"\n\necho \"✅ Feature $FEATURE_ID committed successfully!\"\n```\n\n#### Step 3: Update Session State\n```bash\n# Calculate session duration\nSTART_TIME=$(cat .claude/progress/session-state.json | jq -r '.started_at')\nDURATION_MINUTES=$(($(date +%s) - $(date -d \"$START_TIME\" +%s)) / 60)\n\n# Update session state to completed\njq \"{\n .,\n \\\"status\\\": \\\"completed\\\",\n \\\"ended_at\\\": \\\"$(date -Iseconds)\\\",\n \\\"duration_minutes\\\": $DURATION_MINUTES,\n \\\"session_summary\\\": {\n \\\"features_completed\\\": 1,\n \\\"features_blocked\\\": 0,\n \\\"total_time_minutes\\\": $DURATION_MINUTES,\n \\\"notes\\\": \\\"Successfully completed $FEATURE_ID\\\"\n }\n}\" .claude/progress/session-state.json > .tmp && \\\nmv .tmp .claude/progress/session-state.json\n```\n\n## Error Handling and Recovery\n\n### Common Implementation Issues\n\n**Issue: Feature Larger Than Expected**\n```\nSolution:\n1. Document what was completed\n2. Split remaining work into sub-features\n3. Create new feature IDs for remaining work\n4. Mark original feature with completion percentage\n```\n\n**Issue: Missing Dependencies**\n```\nSolution:\n1. Stop current implementation\n2. Switch to implement missing dependency\n3. Document the blocker\n4. Return to original feature later\n```\n\n**Issue: Tests Keep Failing**\n```\nSolution:\n1. Review test expectations\n2. Check environment setup\n3. Verify implementation matches requirements\n4. Ask for clarification if needed\n```\n\n**Issue: Git Conflicts**\n```\nSolution:\n1. Stash current work\n2. Pull latest changes\n3. Resolve conflicts carefully\n4. Test after resolution\n```\n\n### Recovery Scripts\n\n```bash\n#!/bin/bash\n# scripts/recover-session.sh\n\necho \"=== Session Recovery ===\"\n\n# Check for incomplete work\nif [ -f \".claude/progress/session-state.json\" ]; then\n STATUS=$(cat .claude/progress/session-state.json | jq -r '.status')\n CURRENT_FEATURE=$(cat .claude/progress/session-state.json | jq -r '.current_feature.id // \"None\"')\n\n if [ \"$STATUS\" = \"active\" ] && [ \"$CURRENT_FEATURE\" != \"None\" ]; then\n echo \"Found incomplete work on: $CURRENT_FEATURE\"\n echo \"\"\n echo \"Recovery options:\"\n echo \"1. Complete current feature\"\n echo \"2. Stash changes and select new feature\"\n echo \"3. Reset to last commit\"\n echo \"4. Create backup branch\"\n echo \"\"\n read -p \"Choose option (1-4): \" -n 1 -r\n echo\n\n case $REPLY in\n 1) echo \"Resuming work on $CURRENT_FEATURE\" ;;\n 2) git stash && echo \"Changes stashed\" ;;\n 3) git reset --hard HEAD && echo \"Reset to last commit\" ;;\n 4) git checkout -b recovery-$(date +%Y%m%d-%H%M%S) && echo \"Backup created\" ;;\n esac\n fi\nfi\n\n# Mark session as interrupted if needed\nif [ \"$STATUS\" = \"active\" ]; then\n jq '.status = \"interrupted\"' .claude/progress/session-state.json > .tmp && \\\n mv .tmp .claude/progress/session-state.json\n echo \"Session marked as interrupted\"\nfi\n```\n\n## Performance Optimization\n\n### Implementation Speed\n- Use code snippets and templates\n- Leverage existing patterns\n- Automate repetitive tasks\n- Focus on core functionality first\n\n### Test Performance\n- Use test database with fixtures\n- Run tests in parallel\n- Mock external services\n- Optimize test data generation\n\n## Quality Standards\n\n### Code Quality Checklist\nBefore marking feature complete:\n\n- [ ] Code follows project patterns\n- [ ] Functions/classes are documented\n- [ ] Error handling implemented\n- [ ] No console.log statements\n- [ ] No TODOs/FIXMEs left\n- [ ] Code is efficient and performant\n\n### Testing Checklist\n- [ ] All unit tests pass\n- [ ] New features have tests\n- [ ] Manual steps verified\n- [ ] No regression in existing tests\n- [ ] Edge cases covered\n\n### Documentation Checklist\n- [ ] API endpoints documented\n- [ ] Components documented\n- [ ] Complex logic explained\n- [ ] Usage examples provided\n\n## Communication Patterns\n\n### Progress Updates\nEvery 30 minutes during implementation:\n```\nProgress Update - Feature: [ID]\n- Backend: [ ]% complete\n- Frontend: [ ]% complete\n- Tests: [ ]% complete\n- Blockers: [Any issues]\n```\n\n### Completion Summary\nWhen finishing a feature:\n```\n✅ Feature [ID]: [Feature Name] Complete\n\nImplementation:\n- [Brief description of what was built]\n\nTesting:\n- Unit tests: [count] passing\n- Manual verification: All steps completed\n\nNext:\n- Ready for code review\n- Next recommended feature: [ID]\n```\n\n### Blocker Communication\nWhen encountering issues:\n```\n❌ Blocker on Feature [ID]\n\nIssue: [Clear description of problem]\n\nImpact:\n- Cannot complete [specific part]\n- Blocks [list of dependent features]\n\nAttempted Solutions:\n1. [What was tried]\n2. [What was tried]\n\nRecommendation:\n- [Suggested next steps]\n```\n\nThe Coding Agent ensures that each feature is implemented to the highest standards while maintaining clean state and comprehensive progress tracking, enabling reliable, incremental development across multiple sessions.","content_type":"text/markdown; charset=utf-8","language":"markdown","size":21952,"content_sha256":"97fdf039c7c50c07eb031ea817f1fb08168de7fdff4ddc222baae1bbb1b4912c"},{"filename":"references/feature-tracking-system.md","content":"# Feature Tracking System\n\n## Overview\n\nThe Feature Tracking System is the backbone of the Two-Agent Framework, providing granular visibility into project progress and enabling seamless session recovery. It uses a combination of structured JSON data and human-readable logs to track every feature through its lifecycle from conception to completion.\n\n## Core Components\n\n### 1. feature-list.json - The Master Feature Database\n\nThe `feature-list.json` file is the single source of truth for all project features. It follows the exact format specified in \"Effective Harnesses for Long-Running Agents\", ensuring compatibility with the framework's expectations.\n\n#### Required Structure\n\n```json\n{\n \"project_name\": \"my-awesome-app\",\n \"total_features\": 247,\n \"completed\": 42,\n \"pending\": 205,\n \"categories\": {\n \"authentication\": {\n \"priority\": \"high\",\n \"description\": \"User authentication and authorization system\",\n \"features\": [\n {\n \"id\": \"AUTH-001\",\n \"name\": \"User Registration\",\n \"description\": \"New user registration with email verification\",\n \"category\": \"functional\",\n \"steps\": [\n \"Navigate to registration page\",\n \"Enter valid email address\",\n \"Enter password\",\n \"Click register button\",\n \"Verify email in inbox\",\n \"Confirm email verification code\"\n ],\n \"passes\": false,\n \"dependencies\": [],\n \"estimated_hours\": 4,\n \"assigned_to\": null,\n \"created_at\": \"2025-01-08T10:00:00Z\",\n \"updated_at\": \"2025-01-08T10:00:00Z\",\n \"notes\": \"\"\n }\n ]\n }\n },\n \"metadata\": {\n \"created_at\": \"2025-01-08T10:00:00Z\",\n \"last_updated\": \"2025-01-08T12:00:00Z\",\n \"version\": \"1.0\",\n \"total_categories\": 12\n }\n}\n```\n\n#### Field Definitions\n\n##### Top-Level Fields\n- **project_name** (string): Name of the project\n- **total_features** (integer): Total number of features across all categories\n- **completed** (integer): Number of features with \"passes\": true\n- **pending** (integer): Number of features with \"passes\": false\n\n##### Category Object\n- **priority** (string): \"high\", \"medium\", or \"low\" - determines implementation order\n- **description** (string): Brief description of the category's purpose\n- **features** (array): List of features in this category\n\n##### Feature Object\n- **id** (string): Unique identifier in CATEGORY-NUMBER format (e.g., \"AUTH-001\")\n- **name** (string): Human-readable feature name\n- **description** (string): Detailed description of what the feature does\n- **category** (string): Type of feature - typically \"functional\" or \"technical\"\n- **steps** (array): CRITICAL - Human-readable test procedures\n- **passes** (boolean): false initially, true only after verification\n- **dependencies** (array): List of feature IDs that must be completed first\n- **estimated_hours** (integer): Expected effort (default: 2-4 hours)\n- **assigned_to** (string|null): Developer assigned (optional)\n- **created_at** (string): ISO 8601 timestamp\n- **updated_at** (string): ISO 8601 timestamp\n- **notes** (string): Implementation notes or blockers\n\n#### The \"steps\" Array - Critical Requirement\n\nThe `steps` array is the most important field in the feature tracking system. It provides a human-readable test procedure that anyone can follow to verify the feature works correctly.\n\n```json\n\"steps\": [\n \"Navigate to main application page\",\n \"Click the 'Login' button in the top-right corner\",\n \"Enter valid email address in email field\",\n \"Enter valid password in password field\",\n \"Click 'Sign In' button\",\n \"Verify redirect to dashboard page\",\n \"Check that user's name appears in the header\",\n \"Confirm login session is maintained on page refresh\"\n]\n```\n\n**Best Practices for Steps:**\n1. Start with navigation instructions\n2. Include specific UI elements to interact with\n3. Describe expected outcomes after each action\n4. End with verification of successful completion\n5. Write as if explaining to a non-technical user\n\n### 2. session-state.json - Session Recovery Data\n\nThe session state file enables seamless recovery from interruptions and maintains context across sessions.\n\n#### Structure\n\n```json\n{\n \"session_number\": 15,\n \"started_at\": \"2025-01-08T14:00:00Z\",\n \"agent_type\": \"coding\",\n \"status\": \"active\",\n \"last_feature_id\": \"AUTH-007\",\n \"current_feature\": {\n \"id\": \"AUTH-008\",\n \"name\": \"Password Reset\",\n \"started_at\": \"2025-01-08T15:30:00Z\",\n \"progress\": \"in_progress\"\n },\n \"heartbeat\": {\n \"last_heartbeat\": \"2025-01-08T16:45:00Z\",\n \"interval_seconds\": 300,\n \"missed_heartbeats\": 0\n },\n \"session_summary\": {\n \"features_completed\": 2,\n \"features_blocked\": 0,\n \"total_time_minutes\": 185,\n \"notes\": \"Made good progress on authentication flow\"\n },\n \"git_state\": {\n \"branch\": \"main\",\n \"last_commit\": \"feat(AUTH-007): Implement user login system\",\n \"uncommitted_changes\": false\n }\n}\n```\n\n#### Session Status Values\n- **active**: Session currently running\n- **completed**: Session ended normally\n- **interrupted**: Session ended unexpectedly (crash, network loss)\n- **paused**: Session intentionally paused for later continuation\n\n#### Heartbeat Mechanism\nThe heartbeat system detects abnormal session termination:\n- Updated every 5 minutes during active sessions\n- Used by session-start hook to detect crashes\n- More than 2 missed heartbeats = abnormal termination\n\n### 3. claude-progress.txt - Human-Readable Progress Log\n\nThis file provides a quick, scannable summary of project progress that humans can read at a glance.\n\n#### Format\n\n```\n# Robo-Trader Project Progress\n# Started: 2025-01-01 | Last Updated: 2025-01-08\n\n## Phase 1: Infrastructure (Complete)\n- [x] INFRA-001: Project structure setup (Jan 1, 4h)\n- [x] INFRA-002: Development environment (Jan 1, 2h)\n- [x] INFRA-003: Database schema design (Jan 2, 6h)\n- [x] INFRA-004: CI/CD pipeline (Jan 3, 4h)\n\n## Phase 2: Core Services (In Progress)\n- [x] AUTH-001: User registration (Jan 4, 4h)\n - Email verification with SendGrid\n - Password strength validation\n - Rate limiting implemented\n- [x] AUTH-002: User login (Jan 5, 3h)\n - Session management with JWT\n - Remember me functionality\n - Login attempt tracking\n- [x] AUTH-003: Password reset (Jan 6, 3h)\n- [-] AUTH-004: Two-factor auth (Jan 7, currently working)\n - QR code generation working\n - Need: SMS integration\n - Blocked: Waiting for Twilio API key\n\n## Session 15 - 2025-01-08 (2h 15m)\n### Completed:\n- [x] Fixed authentication middleware bug\n- [x] Added rate limiting to login endpoint\n- [x] Updated API documentation\n\n### Next Session:\n- [ ] Complete SMS integration for 2FA\n- [ ] Start AUTH-005: Social login integration\n- [ ] Write integration tests for auth flow\n\n## Statistics:\n- Total Features: 247\n- Completed: 42 (17%)\n- In Progress: 1\n- Blocked: 3\n- Average per session: 2.8 features\n- Estimated completion: 2025-03-15\n```\n\n## Status Transitions\n\n### Feature Lifecycle\n\n```mermaid\nstateDiagram-v2\n [*] --> Planned: Initial creation\n Planned --> InProgress: Development starts\n InProgress --> Testing: Code complete\n Testing --> Passed: All tests pass\n Testing --> Failed: Tests fail\n Failed --> InProgress: Fix issues\n InProgress --> Blocked: Dependency missing\n Blocked --> InProgress: Dependency ready\n Passed --> [*]: Feature complete\n```\n\n### Implementation Guidelines\n\n#### 1. Creating New Features\n\n```bash\n# Use the initializer-agent to add features\nI need to add payment processing features to the e-commerce project.\n\nFeatures to add:\n- Payment method management\n- Stripe integration\n- Order processing\n- Refund handling\n```\n\nThe initializer-agent will:\n1. Analyze existing features to avoid duplicates\n2. Create proper feature IDs (e.g., PAY-001, PAY-002)\n3. Include detailed steps arrays\n4. Set appropriate dependencies\n5. Estimate hours based on complexity\n\n#### 2. Updating Feature Status\n\n**When Starting a Feature:**\n```json\n{\n \"id\": \"AUTH-008\",\n \"status\": \"in_progress\",\n \"started_at\": \"2025-01-08T15:30:00Z\",\n \"notes\": \"Starting implementation with email-based reset\"\n}\n```\n\n**When Completing a Feature:**\n```json\n{\n \"id\": \"AUTH-008\",\n \"passes\": true,\n \"completed_at\": \"2025-01-08T17:45:00Z\",\n \"notes\": \"Email reset flow working, added rate limiting\"\n}\n```\n\n**When Blocking a Feature:**\n```json\n{\n \"id\": \"AUTH-004\",\n \"status\": \"blocked\",\n \"blocked_reason\": \"Waiting for Twilio API credentials\",\n \"blocked_at\": \"2025-01-08T16:00:00Z\",\n \"dependencies\": [\"INFRA-005\"]\n}\n```\n\n#### 3. Marking Tests as Passing\n\nCRITICAL: Only change \"passes\" from false to true AFTER verification:\n\n```bash\n# 1. Start development server\nnpm run dev\n\n# 2. Run through ALL steps manually\n# Follow the steps array exactly as written\n\n# 3. Automated testing\nnpm test\n\n# 4. Update status ONLY if everything works\n{\n \"passes\": true,\n \"tested_at\": \"2025-01-08T18:00:00Z\",\n \"test_method\": \"manual_e2e\"\n}\n```\n\n## Validation Tools\n\n### Built-in Validation Script\n\n```bash\n# Validate progress files\npython3 .claude/skills/progress-harness/scripts/validate-progress.py\n\n# Output:\n# ✅ feature-list.json is valid\n# ✅ session-state.json is valid\n# ✅ claude-progress.txt exists\n# 📊 Progress tracking system is active\n```\n\n### Custom Validation Rules\n\nCreate `.claude/validate.json` for project-specific rules:\n\n```json\n{\n \"rules\": {\n \"feature_id_format\": \"^[A-Z]{3}-\\\\d{3}$\",\n \"max_steps_per_feature\": 20,\n \"required_categories\": [\"authentication\", \"database\", \"api\"],\n \"min_estimated_hours\": 1,\n \"max_estimated_hours\": 8\n },\n \"notifications\": {\n \"features_without_steps\": true,\n \"orphaned_dependencies\": true,\n \"stale_features\": {\n \"days\": 30,\n \"action\": \"flag\"\n }\n }\n}\n```\n\n## Migration Guide\n\n### From Simple Task Lists\n\nIf you have an existing task list:\n\n1. **Convert to Feature Format:**\n ```json\n // Old format\n {\n \"tasks\": [\"Add user login\", \"Create database\"]\n }\n\n // New format\n {\n \"categories\": {\n \"authentication\": {\n \"features\": [\n {\n \"id\": \"AUTH-001\",\n \"name\": \"User Login\",\n \"steps\": [...],\n \"passes\": false\n }\n ]\n }\n }\n }\n ```\n\n2. **Add Steps Arrays:**\n For each feature, add detailed test steps that a human can follow\n\n3. **Set All to \"passes\": false:**\n Even completed features start as false until re-verified\n\n### From Other Systems\n\nCreate migration scripts in `scripts/migrate-*.py`:\n\n```python\n#!/usr/bin/env python3\n\"\"\"Migrate from JIRA to feature-list.json format\"\"\"\n\nimport json\nfrom jira import JIRA\n\ndef migrate_jira_features(jira_url, project_key):\n jira = JIRA(server=jira_url)\n issues = jira.search_issues(f'project={project_key}')\n\n features = []\n for issue in issues:\n feature = {\n \"id\": f\"{issue.fields.customfield_10010}-{issue.key.split('-')[1]}\",\n \"name\": issue.fields.summary,\n \"description\": issue.fields.description,\n \"steps\": parse_acceptance_criteria(issue.fields.description),\n \"passes\": False,\n \"dependencies\": parse_links(issue.fields.issuelinks)\n }\n features.append(feature)\n\n return {\"categories\": {\"migrated\": {\"features\": features}}}\n```\n\n## Analytics and Reporting\n\n### Progress Metrics\n\nCalculate these metrics regularly:\n\n```javascript\n// Progress calculation\nconst total = featureList.total_features;\nconst completed = featureList.completed;\nconst progress = (completed / total) * 100;\n\n// Velocity tracking\nconst sessions = readSessionHistory();\nconst avgFeaturesPerSession = sessions.reduce((sum, s) =>\n sum + s.features_completed, 0) / sessions.length;\n\n// Burndown chart\nconst burndata = calculateBurndown(featureList, startDate);\n```\n\n### Automated Reports\n\nCreate `scripts/generate-report.py`:\n\n```python\n#!/usr/bin/env python3\n\"\"\"Generate weekly progress report\"\"\"\n\ndef generate_weekly_report():\n report = {\n \"period\": \"2025-W02\",\n \"features_completed\": get_weekly_completions(),\n \"blockers\": get_current_blockers(),\n \"velocity\": calculate_velocity(),\n \"predictions\": predict_completion_date()\n }\n\n # Save as HTML and send email\n save_html_report(report)\n send_email_report(report)\n```\n\n## Best Practices\n\n### 1. Feature Granularity\n- **2-4 hours per feature**: Ideal size for a single session\n- **Single responsibility**: Each feature does one thing well\n- **Testable**: Can be verified independently\n- **Dependencies minimal**: Reduce coupling between features\n\n### 2. Steps Array Quality\n- **Action-oriented**: Start with verbs (Navigate, Click, Enter)\n- **Specific**: Include button names, field labels, URLs\n- **Sequential**: Order matters for test execution\n- **Verifiable**: Each step should have observable outcome\n\n### 3. Consistent Updates\n- **Update after every feature**: Non-negotiable requirement\n- **Include timestamps**: Track when changes were made\n- **Add notes**: Document decisions, blockers, learnings\n- **Keep history**: Don't delete old status, add new fields\n\n### 4. Session Management\n- **Start with context**: Always read existing state first\n- **Update heartbeat**: Keep session alive during long work\n- **End cleanly**: Mark session completed or interrupted\n- **Document blockers**: Clear notes for next session\n\n## Integration Points\n\n### With Git Hooks\n\n```bash\n#!/bin/sh\n# pre-commit hook - verify feature status\n. .claude/progress/feature-list.json\n\n# Check if any modified features have \"passes\": false\nif git diff --name-only | grep -q \"src/\"; then\n echo \"⚠️ Code changes detected - verify feature status is up to date\"\nfi\n```\n\n### With CI/CD Pipeline\n\n```yaml\n# .github/workflows/progress-check.yml\nname: Progress Check\non: [push, pull_request]\n\njobs:\n validate-progress:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v2\n - name: Validate feature list\n run: |\n python3 .claude/skills/progress-harness/scripts/validate-progress.py\n python3 .claude/scripts/check-completeness.py\n```\n\n### With Project Management Tools\n\n```python\n# Sync to JIRA\ndef sync_to_jira():\n features = load_feature_list()\n jira = JIRA(server=config.jira_url)\n\n for feature in features:\n if feature['passes'] and not jira_issue_exists(feature['id']):\n create_jira_ticket(feature)\n```\n\n## Troubleshooting\n\n### Common Issues\n\n1. **Feature List Won't Load**\n - Check JSON syntax with `python -m json.tool`\n - Verify all required fields present\n - Ensure no trailing commas\n\n2. **Session Won't Resume**\n - Check session-state.json heartbeat\n - Verify git branch matches recorded state\n - Look for uncommitted changes\n\n3. **Tests Keep Failing**\n - Review steps array for clarity\n - Verify test environment is running\n - Check for missing dependencies\n\n### Recovery Procedures\n\n```bash\n# Recover from corrupted feature list\ngit checkout HEAD -- .claude/progress/feature-list.json\n\n# Find last known good state\ngit log --oneline -p -- .claude/progress/ | grep -B5 \"passes\\\": true\"\n\n# Manual recovery\ncp .claude/progress/backups/feature-list-20250107.json .claude/progress/feature-list.json\n```\n\n## Example: Complete Feature Lifecycle\n\n### 1. Initial Creation (Initializer Agent)\n```json\n{\n \"id\": \"SHOP-001\",\n \"name\": \"Product Search\",\n \"description\": \"Search products by name, category, and price\",\n \"steps\": [\n \"Navigate to homepage\",\n \"Locate search bar in header\",\n \"Enter 'laptop' in search field\",\n \"Click search button or press Enter\",\n \"Verify search results page loads\",\n \"Check that results contain laptops\",\n \"Test sorting by price\",\n \"Test filtering by brand\"\n ],\n \"passes\": false,\n \"estimated_hours\": 6\n}\n```\n\n### 2. Development Start (Coding Agent)\n```json\n{\n \"status\": \"in_progress\",\n \"started_at\": \"2025-01-08T09:00:00Z\",\n \"notes\": \"Starting with basic text search\"\n}\n```\n\n### 3. Implementation Complete\n```json\n{\n \"passes\": true,\n \"completed_at\": \"2025-01-08T15:30:00Z\",\n \"notes\": \"Full-text search implemented with Elasticsearch. All steps verified manually.\"\n}\n```\n\n### 4. Progress Update\n```\n## Session 12 - 2025-01-08 (6h 30m)\n### Completed:\n- [x] SHOP-001: Product search (6h)\n - Elasticsearch integration\n - Search result pagination\n - Sort and filter functionality\n - All manual tests passing\n\n### Statistics Update:\n- Total Features: 247\n- Completed: 43 (17.4%)\n- Velocity: 2.9 features/session\n```\n\nThis comprehensive feature tracking system ensures project progress is always visible, recoverable, and verifiable - enabling successful long-term development across multiple sessions and team members.","content_type":"text/markdown; charset=utf-8","language":"markdown","size":16720,"content_sha256":"739678cb49535df8169b02046ffcb74063c05636e926557559838892a1957eef"},{"filename":"references/file-structure.md","content":"# File Structure\n\n## Overview\n\nThe Two-Agent Framework relies on a specific file and directory structure to function properly. This structure enables automatic discovery of components, consistent behavior across projects, and seamless integration between agents. Understanding this structure is essential for both implementing new projects and integrating the framework into existing codebases.\n\n## Complete Directory Structure\n\n```\nproject-root/\n├── .claude/ # Framework configuration and state\n│ ├── agents/ # Agent definitions (local override)\n│ │ ├── initializer-agent.md # Project planning agent\n│ │ └── coding-agent.md # Feature implementation agent\n│ │\n│ ├── skills/ # Custom skills\n│ │ └── progress-harness/ # Progress tracking skill\n│ │ ├── SKILL.md # Skill definition\n│ │ ├── references/ # Documentation references\n│ │ ├── assets/ # Templates and scripts\n│ │ │ ├── init.sh.template\n│ │ │ └── feature-list.template.json\n│ │ ├── examples/ # Example implementations\n│ │ └── scripts/ # Utility scripts\n│ │ ├── validate-progress.py\n│ │ └── migrate-features.py\n│ │\n│ ├── progress/ # Progress tracking files\n│ │ ├── feature-list.json # Master feature database\n│ │ ├── session-state.json # Session recovery data\n│ │ └── claude-progress.txt # Human-readable progress log\n│ │\n│ ├── hooks/ # Enforcement scripts\n│ │ ├── pre-tool-guard.sh # Block unauthorized edits\n│ │ ├── post-tool-guard.sh # Remind about progress\n│ │ ├── session-progress-check.sh # Detect abnormal exits\n│ │ ├── verify-coding-agent.sh # Verify progress updated\n│ │ └── session-end.sh # Mark session complete\n│ │\n│ └── settings.json # Claude Code configuration\n│\n├── .mcp.json # MCP server configuration\n│\n├── docs/ # Project documentation\n│ ├── README.md # Project overview\n│ ├── API.md # API documentation\n│ ├── DEPLOYMENT.md # Deployment guide\n│ └── CLAUDE.md # Claude-specific guidelines\n│\n├── src/ # Source code\n│ ├── components/ # Reusable components\n│ ├── services/ # Business logic\n│ ├── utils/ # Utility functions\n│ └── types/ # Type definitions\n│\n├── tests/ # Test files\n│ ├── unit/ # Unit tests\n│ ├── integration/ # Integration tests\n│ └── e2e/ # End-to-end tests\n│\n├── scripts/ # Build and deployment scripts\n│ ├── build.sh # Build script\n│ ├── deploy.sh # Deployment script\n│ └── test.sh # Test runner\n│\n├── config/ # Configuration files\n│ ├── database.json # Database config\n│ ├── api.json # API config\n│ └── environment.json # Environment settings\n│\n├── init.sh # Environment initialization\n├── README.md # Project README\n├── package.json # Node.js dependencies\n├── .gitignore # Git ignore rules\n└── .github/ # GitHub workflows\n └── workflows/ # CI/CD pipelines\n```\n\n## Critical Files and Their Formats\n\n### 1. .claude/settings.json\n\nControls Claude Code behavior and hook activation:\n\n```json\n{\n \"hooks\": {\n \"PreToolUse\": [\n {\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"/bin/bash .claude/hooks/pre-tool-guard.sh\",\n \"statusMessage\": \"Checking tool authorization...\"\n }\n ]\n }\n ],\n \"PostToolUse\": [\n {\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"/bin/bash .claude/hooks/post-tool-guard.sh\",\n \"statusMessage\": \"Remember to update progress...\"\n }\n ]\n }\n ],\n \"SessionStart\": [\n {\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"/bin/bash .claude/hooks/session-progress-check.sh\",\n \"statusMessage\": \"Checking for incomplete sessions...\"\n }\n ]\n }\n ],\n \"SubagentStop\": [\n {\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"/bin/bash .claude/hooks/verify-coding-agent.sh\",\n \"statusMessage\": \"Verifying progress updates...\"\n }\n ]\n }\n ],\n \"SessionEnd\": [\n {\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"/bin/bash .claude/hooks/session-end.sh\",\n \"statusMessage\": \"Marking session complete...\"\n }\n ]\n }\n ]\n }\n}\n```\n\n### 2. .claude/progress/feature-list.json\n\nThe master feature database with exact article format:\n\n```json\n{\n \"project_name\": \"my-application\",\n \"total_features\": 247,\n \"completed\": 0,\n \"pending\": 247,\n \"categories\": {\n \"authentication\": {\n \"priority\": \"high\",\n \"description\": \"User authentication and authorization\",\n \"features\": [\n {\n \"id\": \"AUTH-001\",\n \"name\": \"User Registration\",\n \"description\": \"New user registration with email verification\",\n \"category\": \"functional\",\n \"steps\": [\n \"Navigate to registration page\",\n \"Enter valid email address\",\n \"Enter password\",\n \"Click register button\",\n \"Verify email in inbox\",\n \"Confirm email verification code\"\n ],\n \"passes\": false,\n \"dependencies\": [],\n \"estimated_hours\": 4,\n \"created_at\": \"2025-01-08T10:00:00Z\",\n \"updated_at\": \"2025-01-08T10:00:00Z\",\n \"notes\": \"\"\n }\n ]\n }\n },\n \"metadata\": {\n \"created_at\": \"2025-01-08T10:00:00Z\",\n \"last_updated\": \"2025-01-08T10:00:00Z\",\n \"version\": \"1.0.0\",\n \"total_categories\": 12\n }\n}\n```\n\n### 3. .claude/progress/session-state.json\n\nSession recovery and tracking:\n\n```json\n{\n \"session_number\": 1,\n \"started_at\": \"2025-01-08T10:00:00Z\",\n \"agent_type\": \"coding\",\n \"status\": \"active\",\n \"last_feature_id\": \"AUTH-001\",\n \"current_feature\": {\n \"id\": \"AUTH-002\",\n \"name\": \"User Login\",\n \"started_at\": \"2025-01-08T11:30:00Z\",\n \"progress\": \"in_progress\"\n },\n \"heartbeat\": {\n \"last_heartbeat\": \"2025-01-08T12:45:00Z\",\n \"interval_seconds\": 300,\n \"missed_heartbeats\": 0\n },\n \"session_summary\": {\n \"features_completed\": 1,\n \"features_blocked\": 0,\n \"total_time_minutes\": 95,\n \"notes\": \"Good progress on auth flow\"\n },\n \"git_state\": {\n \"branch\": \"main\",\n \"last_commit\": \"feat(AUTH-001): Implement user registration\",\n \"uncommitted_changes\": false\n }\n}\n```\n\n### 4. .claude/progress/claude-progress.txt\n\nHuman-readable progress log:\n\n```\n# My Application Development Progress\n# Started: 2025-01-08 | Last Updated: 2025-01-08\n\n## Phase 1: Authentication (In Progress)\n- [x] AUTH-001: User Registration (4h)\n - Email verification integrated\n - Password strength validation added\n - Rate limiting implemented\n- [-] AUTH-002: User Login (currently working)\n - JWT session management done\n - Need to add remember me functionality\n\n## Session 1 - 2025-01-08 (2h)\n### Completed:\n- [x] Set up project structure\n- [x] Implement user registration\n- [x] Add email verification\n\n### Next:\n- [ ] Complete login feature\n- [ ] Add password reset\n```\n\n### 5. init.sh\n\nEnvironment initialization script:\n\n```bash\n#!/bin/bash\n# Environment setup for My Application\n\nset -e\n\necho \"Setting up My Application...\"\n\n# Check prerequisites\ncommand -v node >/dev/null 2>&1 || { echo \"Node.js is required\"; exit 1; }\ncommand -v git >/dev/null 2>&1 || { echo \"Git is required\"; exit 1; }\n\n# Install dependencies\necho \"Installing dependencies...\"\nnpm install\n\n# Set up database\necho \"Setting up database...\"\nnpm run db:migrate\n\n# Create environment file\nif [ ! -f .env ]; then\n cp .env.example .env\n echo \"Created .env file - please update with your values\"\nfi\n\n# Install git hooks\necho \"Installing git hooks...\"\ncp .claude/hooks/* .git/hooks/\nchmod +x .git/hooks/*\n\n# Build project\necho \"Building project...\"\nnpm run build\n\necho \"Setup complete! Run 'npm run dev' to start development\"\n```\n\n### 6. .gitignore\n\nGit ignore pattern for Two-Agent projects:\n\n```\n# Dependencies\nnode_modules/\n__pycache__/\n*.pyc\nvenv/\nenv/\n\n# Build outputs\ndist/\nbuild/\n*.egg-info/\n\n# Environment files\n.env\n.env.local\n.env.*.local\n\n# IDE\n.vscode/\n.idea/\n*.swp\n*.swo\n\n# OS\n.DS_Store\nThumbs.db\n\n# Framework specific\n.claude/progress/backups/\n.claude/sessions/\n.claude/temp/\n\n# Logs\nlogs/\n*.log\n\n# Test coverage\ncoverage/\n.nyc_output/\n.coverage\n```\n\n## File Naming Conventions\n\n### Feature IDs\nFormat: `CATEGORY-NUMBER`\n- Categories: 3-letter uppercase codes (AUTH, UI, API, DB, etc.)\n- Numbers: 3-digit sequential starting from 001\n- Examples: AUTH-001, UI-015, API-042\n\n### File Names\n- **Components**: PascalCase (UserProfile.tsx)\n- **Services**: camelCase (userService.js)\n- **Utilities**: camelCase with prefix (helpers.js, validators.js)\n- **Tests**: *.test.js, *.spec.js\n- **Hooks**: kebab-case with .sh extension (session-progress-check.sh)\n\n### Commit Messages\nFormat: `type(scope): description`\n- Types: feat, fix, docs, style, refactor, test, chore\n- Scope: feature ID when applicable\n- Example: `feat(AUTH-001): Implement user registration`\n\n## Auto-Discovery Mechanisms\n\n### Agents\n- Global: `~/.claude/agents/`\n- Project: `.claude/agents/` (overrides global)\n- Discovered by: Claude Code at startup\n\n### Skills\n- Global: `~/.claude/skills/`\n- Project: `.claude/skills/` (overrides global)\n- Discovered by: Both Claude Code and Agent SDK\n\n### Hooks\n- Location: `.claude/hooks/`\n- Configuration: `.claude/settings.json`\n- Discovered by: Native Claude Code hook system\n\n### MCP Servers\n- Configuration: `.mcp.json` at project root\n- Discovered by: Both Claude Code and Agent SDK (different servers)\n\n## Project Type Specific Structures\n\n### Web Application (React/Next.js)\n\n```\nweb-app/\n├── src/\n│ ├── app/ # Next.js app router\n│ ├── components/ # React components\n│ │ ├── ui/ # Reusable UI components\n│ │ └── features/ # Feature-specific components\n│ ├── hooks/ # Custom React hooks\n│ ├── lib/ # Utility libraries\n│ └── types/ # TypeScript types\n├── public/ # Static assets\n├── styles/ # CSS/styled-components\n└── next.config.js # Next.js config\n```\n\n### API Service (Node.js/Express)\n\n```\napi-service/\n├── src/\n│ ├── controllers/ # Route controllers\n│ ├── services/ # Business logic\n│ ├── models/ # Data models\n│ ├── middleware/ # Express middleware\n│ ├── routes/ # Route definitions\n│ ├── utils/ # Utilities\n│ └── config/ # Configuration\n├── tests/ # Test files\n└── swagger/ # API documentation\n```\n\n### CLI Tool\n\n```\ncli-tool/\n├── src/\n│ ├── commands/ # Command implementations\n│ ├── lib/ # Core library\n│ ├── utils/ # Utilities\n│ └── types/ # TypeScript types\n├── bin/ # Executable scripts\n├── man/ # Manual pages\n└── completion/ # Shell completion scripts\n```\n\n### Mobile App (React Native)\n\n```\nmobile-app/\n├── src/\n│ ├── components/ # React Native components\n│ ├── screens/ # App screens\n│ ├── navigation/ # Navigation config\n│ ├── services/ # API services\n│ ├── store/ # State management\n│ └── utils/ # Utilities\n├── android/ # Android-specific code\n├── ios/ # iOS-specific code\n└── __tests__/ # Jest tests\n```\n\n## Template Files\n\n### feature-list.template.json\n\n```json\n{\n \"project_name\": \"{{PROJECT_NAME}}\",\n \"total_features\": {{FEATURE_COUNT}},\n \"completed\": 0,\n \"pending\": {{FEATURE_COUNT}},\n \"categories\": {\n \"{{CATEGORY_1}}\": {\n \"priority\": \"high\",\n \"description\": \"{{CATEGORY_1_DESCRIPTION}}\",\n \"features\": [\n {\n \"id\": \"{{CATEGORY_1}}-001\",\n \"name\": \"{{FEATURE_1_NAME}}\",\n \"description\": \"{{FEATURE_1_DESCRIPTION}}\",\n \"category\": \"functional\",\n \"steps\": [\n \"{{STEP_1}}\",\n \"{{STEP_2}}\",\n \"{{STEP_3}}\"\n ],\n \"passes\": false,\n \"dependencies\": [],\n \"estimated_hours\": 4,\n \"created_at\": \"{{TIMESTAMP}}\",\n \"updated_at\": \"{{TIMESTAMP}}\",\n \"notes\": \"\"\n }\n ]\n }\n },\n \"metadata\": {\n \"created_at\": \"{{TIMESTAMP}}\",\n \"last_updated\": \"{{TIMESTAMP}}\",\n \"version\": \"1.0.0\",\n \"total_categories\": {{CATEGORY_COUNT}}\n }\n}\n```\n\n### init.sh.template\n\n```bash\n#!/bin/bash\n# Environment setup for {{PROJECT_NAME}}\n\nset -e\n\nPROJECT_NAME=\"{{PROJECT_NAME}}\"\nFRAMEWORK=\"{{FRAMEWORK}}\"\nDATABASE=\"{{DATABASE}}\"\n\necho \"Setting up $PROJECT_NAME...\"\n\n# Framework-specific setup\ncase $FRAMEWORK in\n \"react\")\n echo \"Setting up React project...\"\n npm create react-app . --template typescript\n ;;\n \"next\")\n echo \"Setting up Next.js project...\"\n npx create-next-app@latest . --typescript --tailwind --eslint\n ;;\n \"express\")\n echo \"Setting up Express project...\"\n npm init -y\n npm install express\n ;;\nesac\n\n# Install dependencies\necho \"Installing dependencies...\"\nnpm install\n\n# Database setup\nif [ \"$DATABASE\" != \"none\" ]; then\n echo \"Setting up $DATABASE...\"\n # Database-specific commands\nfi\n\n# Initialize Two-Agent Framework\necho \"Initializing Two-Agent Framework...\"\nmkdir -p .claude/progress\nmkdir -p .claude/hooks\n\necho \"Setup complete!\"\n```\n\n## Integration with Existing Projects\n\n### Migration Steps\n\n1. **Create .claude directory structure**\n ```bash\n mkdir -p .claude/{agents,skills,progress,hooks}\n ```\n\n2. **Add settings.json**\n ```bash\n cp ~/.claude/skills/progress-harness/assets/settings.json .claude/\n ```\n\n3. **Initialize feature list**\n ```bash\n # Use initializer-agent to break down existing features\n ```\n\n4. **Set up hooks**\n ```bash\n cp ~/.claude/skills/progress-harness/assets/hooks/*.sh .claude/hooks/\n chmod +x .claude/hooks/*.sh\n ```\n\n5. **Create initial progress**\n ```bash\n echo \"# Project Progress\\n\\nStarted on $(date)\" > .claude/progress/claude-progress.txt\n ```\n\n### Minimal Structure for Quick Start\n\nFor projects wanting to start with minimal setup:\n\n```\nproject/\n├── .claude/\n│ ├── progress/\n│ │ └── feature-list.json\n│ └── settings.json (optional)\n└── src/\n```\n\n## Validation Scripts\n\n### validate-structure.py\n\n```python\n#!/usr/bin/env python3\n\"\"\"Validate project structure compliance\"\"\"\n\nimport os\nimport json\nimport sys\nfrom pathlib import Path\n\nREQUIRED_DIRS = [\n \".claude\",\n \".claude/progress\"\n]\n\nREQUIRED_FILES = [\n \".claude/progress/feature-list.json\"\n]\n\nOPTIONAL_FILES = [\n \".claude/settings.json\",\n \".claude/progress/session-state.json\",\n \".claude/progress/claude-progress.txt\",\n \"init.sh\"\n]\n\ndef validate_structure():\n \"\"\"Validate project structure\"\"\"\n errors = []\n warnings = []\n\n # Check required directories\n for dir_path in REQUIRED_DIRS:\n if not os.path.isdir(dir_path):\n errors.append(f\"Missing required directory: {dir_path}\")\n\n # Check required files\n for file_path in REQUIRED_FILES:\n if not os.path.isfile(file_path):\n errors.append(f\"Missing required file: {file_path}\")\n\n # Check optional files\n for file_path in OPTIONAL_FILES:\n if not os.path.isfile(file_path):\n warnings.append(f\"Missing optional file: {file_path}\")\n\n # Validate feature-list.json\n if os.path.isfile(\".claude/progress/feature-list.json\"):\n try:\n with open(\".claude/progress/feature-list.json\") as f:\n data = json.load(f)\n\n # Check required fields\n if \"categories\" not in data:\n errors.append(\"feature-list.json missing 'categories' field\")\n\n # Check features have steps\n for category in data.get(\"categories\", {}).values():\n for feature in category.get(\"features\", []):\n if \"steps\" not in feature:\n errors.append(f\"Feature {feature.get('id', 'unknown')} missing 'steps' array\")\n\n except json.JSONDecodeError as e:\n errors.append(f\"Invalid JSON in feature-list.json: {e}\")\n\n return errors, warnings\n\ndef main():\n errors, warnings = validate_structure()\n\n if errors:\n print(\"❌ Errors found:\")\n for error in errors:\n print(f\" - {error}\")\n\n if warnings:\n print(\"⚠️ Warnings:\")\n for warning in warnings:\n print(f\" - {warning}\")\n\n if not errors and not warnings:\n print(\"✅ Project structure is valid\")\n\n return 1 if errors else 0\n\nif __name__ == \"__main__\":\n sys.exit(main())\n```\n\n## Best Practices\n\n### 1. Directory Organization\n- Keep .claude directory clean and organized\n- Use subdirectories for different component types\n- Maintain separation between code and configuration\n\n### 2. File Management\n- Commit all .claude files except sensitive data\n- Use .gitignore to exclude temporary files\n- Keep feature-list.json under version control\n\n### 3. Naming Consistency\n- Follow established naming conventions\n- Use descriptive names for clarity\n- Maintain consistency across the project\n\n### 4. Documentation\n- Document project-specific conventions\n- Include CLAUDE.md files in each major directory\n- Keep README files up to date\n\n### 5. Security\n- Never commit API keys or passwords\n- Use environment variables for configuration\n- Review .gitignore regularly\n\n## Troubleshooting\n\n### Common Issues\n\n1. **Hooks Not Working**\n - Verify .claude/settings.json exists and is valid\n - Check hook scripts are executable\n - Ensure hook paths are correct\n\n2. **Feature List Not Found**\n - Verify .claude/progress/ directory exists\n - Check file permissions\n - Run initializer-agent to create initial list\n\n3. **Agents Not Available**\n - Check agent files are in ~/.claude/agents/\n - Verify agent YAML format is correct\n - Restart Claude Code if needed\n\n4. **Progress Not Tracking**\n - Verify session-state.json is being updated\n - Check heartbeat mechanism is working\n - Review hook outputs for errors\n\n### Recovery Procedures\n\n```bash\n# Reset project structure\ngit checkout HEAD -- .claude/\n\n# Recreate from template\ncp -r ~/.claude/skills/progress-harness/assets/template/.claude .\n\n# Validate structure\npython3 .claude/scripts/validate-structure.py\n```\n\nThis comprehensive file structure ensures the Two-Agent Framework functions correctly while maintaining organization and consistency across projects.","content_type":"text/markdown; charset=utf-8","language":"markdown","size":20358,"content_sha256":"02f4b4b85638bbf95d3d0798849ba7bb858614ced7c9eb4d81f94e981504a69e"},{"filename":"references/git-integration.md","content":"# Git Integration\n\n## Overview\n\nGit integration is fundamental to the Two-Agent Framework's success. It provides version control, collaboration, rollback capabilities, and a complete audit trail of all development activities. The framework enforces specific Git workflows to ensure clean state, traceable changes, and seamless collaboration between agents and human developers.\n\n## Git Workflow Philosophy\n\n### 1. Clean State Principle\nEvery commit must represent a working, mergeable state to the main branch. No half-finished features, no broken tests, no TODOs left in production code.\n\n### 2. Atomic Commits\nOne feature = one commit. Each commit implements a complete, tested feature with clear documentation of what was changed.\n\n### 3. Traceability\nEvery commit links directly to a feature ID from the feature-list.json, enabling complete traceability from requirements to implementation.\n\n### 4. Recovery\nGit provides the ultimate recovery mechanism—any mistake can be rolled back to a previous working state.\n\n## Branch Strategy\n\n### Main Branch Protection\n\n```json\n// .github/branch-protection.json\n{\n \"required_status_checks\": {\n \"strict\": true,\n \"contexts\": [\n \"ci/tests\",\n \"ci/lint\",\n \"ci/type-check\"\n ]\n },\n \"enforce_admins\": true,\n \"required_pull_request_reviews\": {\n \"required_approving_review_count\": 1\n },\n \"restrictions\": {\n \"users\": [],\n \"teams\": [\"core-developers\"]\n }\n}\n```\n\n### Branch Types\n\n| Branch Type | Purpose | Lifecycle |\n|-------------|---------|-----------|\n| **main** | Production-ready code | Permanent |\n| **develop** | Integration branch | Permanent |\n| **feature/ID** | Individual feature development | Temporary |\n| **hotfix/ID** | Production fixes | Temporary |\n| **release/v** | Release preparation | Temporary |\n\n### Branch Naming Conventions\n\n```\nfeature/AUTH-001 # User registration feature\nfeature/UI-045 # Navigation component\nbugfix/DB-023 # Database connection issue\nhotfix/PROD-001 # Production hotfix\nrelease/v2.1.0 # Release branch\n```\n\n## Commit Message Format\n\n### Conventional Commits Standard\n\n```\n\u003ctype>[optional scope]: \u003cdescription>\n\n[optional body]\n\n[optional footer(s)]\n```\n\n### Types\n\n| Type | Purpose | Example |\n|------|---------|---------|\n| **feat** | New feature | `feat(AUTH-001): Add user registration` |\n| **fix** | Bug fix | `fix(API-023): Fix authentication timeout` |\n| **docs** | Documentation | `docs(README): Update installation guide` |\n| **style** | Code style | `style(UI): Fix button alignment` |\n| **refactor** | Refactoring | `refactor(DB): Consolidate query methods` |\n| **test** | Tests | `test(AUTH-001): Add registration tests` |\n| **chore** | Maintenance | `chore(deps): Update dependencies` |\n\n### Feature-Specific Format\n\n```\nfeat(FEATURE-ID): Brief feature description\n\nDetailed explanation of implementation:\n- What was changed\n- Why it was changed\n- How it was implemented\n- Any trade-offs made\n\nTesting performed:\n- Unit tests: passing\n- Integration tests: passing\n- Manual verification: complete\n\nCloses #ISSUE_NUMBER\n```\n\n### Complete Example\n\n```\nfeat(AUTH-001): Implement user registration system\n\n- Added registration form with email validation\n- Integrated SendGrid for email verification\n- Implemented password strength requirements\n- Added rate limiting to prevent abuse\n\nBackend changes:\n- Created /api/auth/register endpoint\n- Added User model with email verification\n- Implemented JWT token generation\n\nFrontend changes:\n- Created RegistrationPage component\n- Added form validation with React Hook Form\n- Integrated with backend API\n\nTesting:\n- Unit tests: 100% coverage\n- Integration tests: All passing\n- Manual verification: Steps 1-11 completed\n\nThe feature now allows users to register with email verification\nand automatically logs them in after successful registration.\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)\n\nCo-Authored-By: Claude \[email protected]>\n```\n\n## Commit Automation\n\n### Pre-Commit Hooks\n\n```bash\n#!/bin/sh\n# .git/hooks/pre-commit\n\n# Run tests\nnpm run test:unit\nif [ $? -ne 0 ]; then\n echo \"❌ Unit tests failed. Commit aborted.\"\n exit 1\nfi\n\n# Run linting\nnpm run lint\nif [ $? -ne 0 ]; then\n echo \"❌ Linting errors found. Commit aborted.\"\n exit 1\nfi\n\n# Check for TODOs\nTODO_COUNT=$(git diff --cached --name-only | xargs grep -l \"TODO\\|FIXME\" 2>/dev/null | wc -l)\nif [ $TODO_COUNT -gt 0 ]; then\n echo \"⚠️ Found $TODO_COUNT files with TODO/FIXME:\"\n git diff --cached --name-only | xargs grep -n \"TODO\\|FIXME\" 2>/dev/null\n read -p \"Continue anyway? (y/N): \" -n 1 -r\n echo\n if [[ ! $REPLY =~ ^[Yy]$ ]]; then\n exit 1\n fi\nfi\n\n# Check feature status\nif [ -f \".claude/progress/feature-list.json\" ]; then\n # Get staged feature IDs from commit message\n FEATURE_ID=$(git log -1 --pretty=format:'%s' | grep -oE '\\([A-Z]{3}-[0-9]{3}\\)' | tr -d '()')\n\n if [ -n \"$FEATURE_ID\" ]; then\n FEATURE_PASSES=$(jq -r --arg id \"$FEATURE_ID\" \\\n '.categories[].features[] | select(.id == $id) | .passes' \\\n .claude/progress/feature-list.json)\n\n if [ \"$FEATURE_PASSES\" != \"true\" ]; then\n echo \"⚠️ Feature $FEATURE_ID is not marked as passing in feature-list.json\"\n read -p \"Continue anyway? (y/N): \" -n 1 -r\n echo\n if [[ ! $REPLY =~ ^[Yy]$ ]]; then\n exit 1\n fi\n fi\n fi\nfi\n\necho \"✅ All checks passed. Committing...\"\nexit 0\n```\n\n### Commit Message Validation\n\n```javascript\n// scripts/validate-commit-msg.js\nconst conventionalCommits = require('conventional-commits-validator');\n\nmodule.exports = {\n extends: ['@commitlint/config-conventional'],\n rules: {\n 'type-enum': [\n 2,\n 'always',\n [\n 'feat',\n 'fix',\n 'docs',\n 'style',\n 'refactor',\n 'test',\n 'chore'\n ]\n ],\n 'scope-case': [2, 'always', 'pascal-case'],\n 'subject-max-length': [2, 'always', 72],\n 'body-max-line-length': [2, 'always', 100],\n 'footer-max-line-length': [2, 'always', 100],\n 'scope-empty': [2, 'never'],\n 'subject-empty': [2, 'never'],\n 'subject-full-stop': [2, 'never', '.'],\n 'header-max-length': [2, 'always', 100]\n }\n};\n```\n\n### Automatic Commit Generation\n\n```bash\n#!/bin/bash\n# scripts/commit-feature.sh\n\nFEATURE_ID=$1\n\nif [ -z \"$FEATURE_ID\" ]; then\n echo \"Usage: ./commit-feature.sh \u003cFEATURE-ID>\"\n exit 1\nfi\n\n# Get feature information\nFEATURE_INFO=$(jq -r --arg id \"$FEATURE_ID\" \\\n '.categories[].features[] | select(.id == $id)' \\\n .claude/progress/feature-list.json)\n\nFEATURE_NAME=$(echo \"$FEATURE_INFO\" | jq -r '.name')\nFEATURE_DESC=$(echo \"$FEATURE_INFO\" | jq -r '.description')\n\n# Generate commit message\ncat > .git/COMMIT_EDITMSG \u003c\u003c EOF\nfeat($FEATURE_ID): $FEATURE_NAME\n\n$FEATURE_DESC\n\nImplementation details extracted from git diff:\n$(git diff --cached --stat)\n\nTesting:\n- Manual verification: All steps completed\n- Unit tests: Passing\n- Integration tests: Passing\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)\n\nCo-Authored-By: Claude \[email protected]>\nEOF\n\n# Execute commit\ngit commit -F .git/COMMIT_EDITMSG\n\n# Update feature status\njq --arg id \"$FEATURE_ID\" \\\n '(.categories[].features[] | select(.id == $id)) |= {\n .,\n \"passes\": true,\n \"completed_at\": \"'$(date -Iseconds)'\"\n }' \\\n .claude/progress/feature-list.json > .tmp && \\\n mv .tmp .claude/progress/feature-list.json\n\necho \"✅ Feature $FEATURE_ID committed successfully!\"\n```\n\n## Collaboration Workflow\n\n### Feature Branch Workflow\n\n```bash\n# 1. Create feature branch\ngit checkout -b feature/AUTH-001\n\n# 2. Implement feature\n# ... (coding, testing, etc.)\n\n# 3. Commit changes\ngit add .\n./scripts/commit-feature.sh AUTH-001\n\n# 4. Push to remote\ngit push -u origin feature/AUTH-001\n\n# 5. Create pull request\n# (done through GitHub UI)\n\n# 6. After review and merge:\ngit checkout main\ngit pull origin main\ngit branch -d feature/AUTH-001\n```\n\n### Pull Request Template\n\n```markdown\n\u003c!-- .github/pull_request_template.md -->\n## Description\nBrief description of changes made in this PR.\n\n## Type of Change\n- [ ] Bug fix (non-breaking change that fixes an issue)\n- [ ] New feature (non-breaking change that adds functionality)\n- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)\n- [ ] Documentation update\n\n## Feature ID\n\u003c!-- Link to feature-list.json -->\nFeature: [AUTH-001](https://github.com/user/repo/blob/main/.claude/progress/feature-list.json#L42)\n\n## Testing Performed\n- [ ] Unit tests pass\n- [ ] Integration tests pass\n- [ ] Manual steps verified\n- [ ] E2E tests pass\n- [ ] Performance tests pass\n\n## Checklist\n- [ ] My code follows the style guidelines of this project\n- [ ] I have performed a self-review of my own code\n- [ ] I have commented my code, particularly in hard-to-understand areas\n- [ ] I have made corresponding changes to the documentation\n- [ ] My changes generate no new warnings\n- [ ] I have added tests that prove my fix is effective or that my feature works\n- [ ] New and existing unit tests pass locally with my changes\n- [ ] Any dependent changes have been merged and published in downstream modules\n\n## Screenshots (if applicable)\n\u003c!-- Add screenshots to help explain your changes -->\n\n## Additional Notes\n\u003c!-- Any additional information about the PR -->\n```\n\n### Code Review Process\n\n```yaml\n# .github/workflows/pr-check.yml\nname: PR Check\n\non:\n pull_request:\n types: [opened, edited, synchronize]\n\njobs:\n pr-validation:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v3\n\n - name: Validate PR format\n uses: actions/github-script@v6\n with:\n script: |\n // Check PR description for required sections\n const body = context.payload.pull_request.body;\n const required = ['Description', 'Feature ID', 'Testing Performed'];\n\n for (const section of required) {\n if (!body.includes(section)) {\n core.setFailed(`PR missing required section: ${section}`);\n return;\n }\n }\n\n // Extract feature ID from PR\n const featureMatch = body.match(/Feature:\\s*\\[([A-Z]{3}-[0-9]{3})\\]/);\n if (featureMatch) {\n const featureId = featureMatch[1];\n console.log(`Feature ID found: ${featureId}`);\n\n // Check if feature exists in feature-list.json\n const fs = require('fs');\n const featureList = JSON.parse(fs.readFileSync('.claude/progress/feature-list.json', 'utf8'));\n\n let featureExists = false;\n for (const category of Object.values(featureList.categories)) {\n if (category.features.some(f => f.id === featureId)) {\n featureExists = true;\n break;\n }\n }\n\n if (!featureExists) {\n core.setFailed(`Feature ${featureId} not found in feature-list.json`);\n }\n }\n```\n\n## History Tracking\n\n### Git Log Analysis\n\n```bash\n#!/bin/bash\n# scripts/git-stats.sh\n\necho \"=== Git Statistics ===\"\n\n# Total commits\nTOTAL_COMMITS=$(git rev-list --count HEAD)\necho \"Total commits: $TOTAL_COMMITS\"\n\n# Commits by type\necho -e \"\\n=== Commits by Type ===\"\ngit log --pretty=format:'%s' | grep -oE '^[a-z]+' | sort | uniq -c | sort -nr\n\n# Commits by feature\necho -e \"\\n=== Commits by Feature ===\"\ngit log --pretty=format:'%s' | grep -oE '\\([A-Z]{3}-[0-9]{3}\\)' | sort | uniq -c | sort -nr\n\n# Contributors\necho -e \"\\n=== Contributors ===\"\ngit log --pretty=format:'%an' | sort | uniq -c | sort -nr\n\n# Recent activity\necho -e \"\\n=== Recent Activity (Last 7 Days) ===\"\ngit log --since=\"7 days ago\" --pretty=format:'%h %s' | wc -l | xargs echo \"Commits:\"\ngit log --since=\"7 days ago\" --pretty=format:'%s'\n```\n\n### Feature History\n\n```bash\n#!/bin/bash\n# scripts/feature-history.sh\n\nFEATURE_ID=$1\n\nif [ -z \"$FEATURE_ID\" ]; then\n echo \"Usage: ./feature-history.sh \u003cFEATURE-ID>\"\n exit 1\nfi\n\necho \"=== History for $FEATURE_ID ===\"\n\n# Find all commits for this feature\nCOMMITS=$(git log --grep=\"($FEATURE_ID)\" --oneline)\n\necho -e \"\\nCommits:\"\necho \"$COMMITS\"\n\n# Show file changes\necho -e \"\\nFile changes:\"\ngit log --grep=\"($FEATURE_ID)\" --name-only --pretty=format: | sort | uniq\n\n# Show feature status\necho -e \"\\nCurrent status:\"\njq -r --arg id \"$FEATURE_ID\" \\\n '.categories[].features[] | select(.id == $id)' \\\n .claude/progress/feature-list.json\n\n# Show time tracking\necho -e \"\\nTimeline:\"\ngit log --grep=\"($FEATURE_ID)\" --pretty=format:'%h %ad %s' --date=short\n```\n\n## Recovery and Rollback\n\n### Quick Recovery Commands\n\n```bash\n#!/bin/bash\n# scripts/quick-recovery.sh\n\necho \"=== Quick Recovery Options ===\"\n\n# 1. Undo last commit (keep changes)\necho \"1. Undo last commit (keep changes):\"\necho \" git reset --soft HEAD~1\"\n\n# 2. Undo last commit (discard changes)\necho -e \"\\n2. Undo last commit (discard changes):\"\necho \" git reset --hard HEAD~1\"\n\n# 3. Recover specific file\necho -e \"\\n3. Recover file from last commit:\"\necho \" git checkout HEAD -- path/to/file\"\n\n# 4. Recover to specific commit\necho -e \"\\n4. Recover to specific commit:\"\necho \" git reset --hard \u003ccommit-hash>\"\n\n# 5. Stash current changes\necho -e \"\\n5. Stash current changes:\"\necho \" git stash\"\n\n# 6. Recover from stash\necho -e \"\\n6. Recover from stash:\"\necho \" git stash pop\"\n\n# Show recent commits for reference\necho -e \"\\n=== Recent Commits ===\"\ngit log --oneline -10\n```\n\n### Disaster Recovery\n\n```bash\n#!/bin/bash\n# scripts/disaster-recovery.sh\n\necho \"=== Disaster Recovery ===\"\n\n# Create backup branch\nBACKUP_BRANCH=\"recovery-$(date +%Y%m%d-%H%M%S)\"\necho \"Creating backup branch: $BACKUP_BRANCH\"\ngit checkout -b $BACKUP_BRANCH\n\n# Save current state\ngit add .\ngit commit -m \"RECOVERY: Save state before recovery\"\ngit checkout main\n\n# Options\necho -e \"\\nRecovery Options:\"\necho \"1. Reset to last known good state (HEAD~5)\"\necho \"2. Reset to specific commit\"\necho \"3. Reset to tag\"\necho \"4. Interactive rebase\"\necho \"5. Abort and return to backup\"\n\nread -p \"Choose option (1-5): \" -n 1 -r\necho\n\ncase $REPLY in\n 1)\n git reset --hard HEAD~5\n echo \"Reset to HEAD~5\"\n ;;\n 2)\n read -p \"Enter commit hash: \" COMMIT\n git reset --hard $COMMIT\n echo \"Reset to $COMMIT\"\n ;;\n 3)\n git tag -l | sort -V\n read -p \"Enter tag name: \" TAG\n git reset --hard $TAG\n echo \"Reset to tag $TAG\"\n ;;\n 4)\n git log --oneline -20\n read -p \"Enter base commit (HEAD~n): \" BASE\n git rebase -i $BASE\n ;;\n 5)\n git checkout $BACKUP_BRANCH\n echo \"Returned to backup branch: $BACKUP_BRANCH\"\n ;;\nesac\n\necho -e \"\\nRecovery complete. Verify state with:\"\necho \" git log --oneline -5\"\necho \" git status\"\n```\n\n## Integration with Development Tools\n\n### IDE Integration (VS Code)\n\n```json\n// .vscode/settings.json\n{\n \"git.enableSmartCommit\": true,\n \"git.smartCommitChanges\": \"all\",\n \"git.autofetch\": true,\n \"git.confirmSync\": false,\n \"git.postCommitCommand\": \"none\",\n \"git.showInlineOpenFileAction\": false,\n \"git.suggestSmartCommit\": false,\n \"git.supportCancellation\": false\n}\n```\n\n### Git Aliases\n\n```bash\n# .gitconfig\n[alias]\n # Feature workflow\n feature = \"!f() { git checkout -b feature/$1; }; f\"\n commit-feature = \"!sh ./scripts/commit-feature.sh\"\n feature-status = \"!sh ./scripts/feature-history.sh\"\n\n # Quick operations\n save = \"!git add -A && git commit -m 'WIP: Save progress'\"\n wipe = \"!git add -A && git commit -m 'WIPE: Reset to clean state' && git reset --hard HEAD~1\"\n undo = \"reset --soft HEAD~1\"\n\n # History\n graph = \"log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)\u003c%an>%Creset' --abbrev-commit\"\n find = \"!f() { git log --all --grep=\\\"$1\\\" --pretty=format:'%h %s' }; f\"\n\n # Statistics\n stats = \"!sh ./scripts/git-stats.sh\"\n churn = \"!f() { git log -M -C --name-only --format='format:' $@ | sort | uniq -c | sort -nr }; f\"\n```\n\n### GitHub CLI Integration\n\n```bash\n#!/bin/bash\n# scripts/gh-integration.sh\n\n# Create PR from feature branch\ncreate_pr() {\n FEATURE_ID=$(git branch --show-current | grep -oE '[A-Z]{3}-[0-9]{3}')\n\n if [ -z \"$FEATURE_ID\" ]; then\n echo \"No feature ID found in branch name\"\n exit 1\n fi\n\n # Get feature info\n FEATURE_INFO=$(jq -r --arg id \"$FEATURE_ID\" \\\n '.categories[].features[] | select(.id == $id) | {\n name: .name,\n description: .description,\n steps: .steps\n }' \\\n .claude/progress/feature-list.json)\n\n # Create PR\n gh pr create \\\n --title \"feat($FEATURE_ID): $(echo \"$FEATURE_INFO\" | jq -r '.name')\" \\\n --body \"$(cat \u003c\u003c EOF\n## Description\n$(echo \"$FEATURE_INFO\" | jq -r '.description')\n\n## Feature ID\n$FEATURE_ID\n\n## Testing Performed\n$(echo \"$FEATURE_INFO\" | jq -r '.steps[]' | sed 's/^/- [ ] /')\n\n## Checklist\n- [x] Code follows project guidelines\n- [x] Self-review completed\n- [x] Tests added and passing\n- [x] Documentation updated\n\nEOF\n)\"\n}\n\n# List features in progress\nlist_features() {\n jq -r '.categories[].features[] | select(.passes == false) | \"\\(.id) - \\(.name)\"' \\\n .claude/progress/feature-list.json\n}\n\n# Main menu\ncase \"$1\" in\n pr)\n create_pr\n ;;\n list)\n list_features\n ;;\n *)\n echo \"Usage: $0 {pr|list}\"\n ;;\nesac\n```\n\n## Best Practices\n\n### 1. Commit Hygiene\n- Write clear, descriptive commit messages\n- Keep commits focused and atomic\n- Include feature IDs in all related commits\n- Never commit broken code\n\n### 2. Branch Management\n- Delete feature branches after merging\n- Keep main branch clean and deployable\n- Use descriptive branch names\n- Protect critical branches\n\n### 3. Collaboration\n- Review all code before merging\n- Use pull requests for all changes\n- Document decisions in commit messages\n- Resolve conflicts carefully\n\n### 4. Security\n- Never commit secrets or API keys\n- Use .gitignore effectively\n- Review access permissions regularly\n- Sign commits when possible\n\n### 5. Performance\n- Use shallow clones for CI/CD\n- Keep repository size manageable\n- Use Git LFS for large files\n- Archive old branches\n\nThis comprehensive Git integration ensures that all development activities are tracked, versioned, and recoverable, providing a solid foundation for the Two-Agent Framework's incremental development approach.","content_type":"text/markdown; charset=utf-8","language":"markdown","size":18180,"content_sha256":"aa4ded0ebe12d97bbdaa11a41a4d52b9b07a7b589c084216e648978098a5f594"},{"filename":"references/hook-system.md","content":"# Hook System\n\n## Overview\n\nThe Hook System is a critical enforcement mechanism in the Two-Agent Framework that ensures agents follow proper workflows, maintain progress tracking, and leave clean state between sessions. Hooks are automated scripts that trigger at specific events during Claude Code execution, providing defense-in-depth protection against common pitfalls and ensuring framework compliance.\n\n## Hook Architecture\n\n### Hook Event Types\n\nThe Two-Agent Framework uses these hook events:\n\n| Event | Timing | Purpose | Typical Use |\n|-------|--------|---------|-------------|\n| **PreToolUse** | Before any tool execution | Validate and guard tool usage | Block Opus from direct code editing |\n| **PostToolUse** | After any tool execution | Remind about progress updates | Prompt for feature status updates |\n| **SessionStart** | When Claude Code starts | Detect abnormal exits | Check for incomplete sessions |\n| **SubagentStop** | When an agent finishes | Verify agent compliance | Ensure progress was updated |\n| **SessionEnd** | When Claude Code exits | Clean session termination | Mark session as completed |\n| **UserPromptSubmit** | When user sends message | Context injection | Add progress context to prompts |\n\n### Hook Implementation Types\n\n1. **Command Hooks**: Execute shell scripts\n2. **Filter Hooks**: Modify inputs/outputs\n3. **Validation Hooks**: Check conditions before proceeding\n4. **Notification Hooks**: Send alerts or messages\n\n## Core Hook Implementations\n\n### 1. Pre-Tool Guard (pre-tool-guard.sh)\n\n**Purpose**: Prevent Opus from directly editing source code, enforcing the two-agent separation.\n\n```bash\n#!/bin/bash\n# .claude/hooks/pre-tool-guard.sh\n\n# Extract tool name and arguments from stdin\nread -r INPUT\n\n# Parse tool name (simplified parsing)\nTOOL_NAME=$(echo \"$INPUT\" | jq -r '.tool' 2>/dev/null || echo \"unknown\")\n\n# Skip checks for allowed tools\nALLOWED_TOOLS=(\"Read\" \"Bash\" \"Grep\" \"Glob\" \"WebFetch\" \"WebSearch\" \"TodoWrite\")\n\nfor allowed in \"${ALLOWED_TOOLS[@]}\"; do\n if [[ \"$TOOL_NAME\" == \"$allowed\" ]]; then\n echo \"Tool $TOOL_NAME is allowed\" >&2\n exit 0\n fi\ndone\n\n# Check if trying to edit source files directly\nif [[ \"$TOOL_NAME\" == \"Edit\" ]] || [[ \"$TOOL_NAME\" == \"Write\" ]]; then\n # Extract file path from arguments\n FILE_PATH=$(echo \"$INPUT\" | jq -r '.file_path // .input.file_path' 2>/dev/null)\n\n # Block editing src/ directory unless coding-agent is active\n AGENT_TYPE=$(cat .claude/progress/session-state.json 2>/dev/null | jq -r '.agent_type // \"unknown\"')\n\n if [[ \"$FILE_PATH\" == src/* ]] && [[ \"$AGENT_TYPE\" != \"coding\" ]]; then\n echo \"❌ ERROR: Cannot edit src/ files directly. Use the coding-agent for implementation.\" >&2\n echo \" This ensures proper progress tracking and clean state maintenance.\" >&2\n exit 1\n fi\nfi\n\n# Update heartbeat if session is active\nif [ -f \".claude/progress/session-state.json\" ]; then\n cat .claude/progress/session-state.json | \\\n jq \".heartbeat.last_heartbeat = \\\"$(date -Iseconds)\\\"\" > \\\n .claude/progress/session-state.json.tmp && \\\n mv .claude/progress/session-state.json.tmp .claude/progress/session-state.json\nfi\n\nexit 0\n```\n\n**Configuration**:\n```json\n{\n \"hooks\": {\n \"PreToolUse\": [\n {\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"/bin/bash .claude/hooks/pre-tool-guard.sh\",\n \"statusMessage\": \"Validating tool usage...\"\n }\n ]\n }\n ]\n }\n}\n```\n\n### 2. Post-Tool Reminder (post-tool-guard.sh)\n\n**Purpose**: Remind developers to update progress after making changes.\n\n```bash\n#!/bin/bash\n# .claude/hooks/post-tool-guard.sh\n\n# Extract tool information\nread -r INPUT\nTOOL_NAME=$(echo \"$INPUT\" | jq -r '.tool' 2>/dev/null || echo \"unknown\")\n\n# Check if this was a code-changing operation\nif [[ \"$TOOL_NAME\" == \"Edit\" ]] || [[ \"$TOOL_NAME\" == \"Write\" ]] || [[ \"$TOOL_NAME\" == \"Bash\" ]]; then\n # Only remind if coding-agent is active\n if [ -f \".claude/progress/session-state.json\" ]; then\n AGENT_TYPE=$(cat .claude/progress/session-state.json | jq -r '.agent_type // \"unknown\"')\n\n if [[ \"$AGENT_TYPE\" == \"coding\" ]]; then\n echo \"\" >&2\n echo \"💡 Reminder: Don't forget to update progress tracking!\" >&2\n echo \" - Mark completed features as 'passes': true in feature-list.json\" >&2\n echo \" - Update claude-progress.txt with session summary\" >&2\n echo \" - Commit changes with descriptive message\" >&2\n echo \"\" >&2\n\n # Show current feature if available\n CURRENT_FEATURE=$(cat .claude/progress/session-state.json | jq -r '.current_feature.id // \"None\"')\n if [[ \"$CURRENT_FEATURE\" != \"None\" ]]; then\n echo \" Current feature: $CURRENT_FEATURE\" >&2\n fi\n fi\n fi\nfi\n\nexit 0\n```\n\n### 3. Session Progress Check (session-progress-check.sh)\n\n**Purpose**: Detect abnormal session termination and prompt for recovery.\n\n```bash\n#!/bin/bash\n# .claude/hooks/session-progress-check.sh\n\nSESSION_STATE=\".claude/progress/session-state.json\"\n\n# Check if session state exists\nif [ ! -f \"$SESSION_STATE\" ]; then\n echo \"No previous session found. Starting fresh.\" >&2\n exit 0\nfi\n\n# Read session status\nSTATUS=$(cat \"$SESSION_STATE\" | jq -r '.status // \"unknown\"')\nLAST_HB=$(cat \"$SESSION_STATE\" | jq -r '.heartbeat.last_heartbeat // \"never\"')\nAGENT_TYPE=$(cat \"$SESSION_STATE\" | jq -r '.agent_type // \"unknown\"')\nSESSION_NUM=$(cat \"$SESSION_STATE\" | jq -r '.session_number // \"?\"')\n\nif [[ \"$STATUS\" == \"active\" ]]; then\n # Calculate time since last heartbeat\n if [[ \"$LAST_HB\" != \"never\" ]]; then\n LAST_EPOCH=$(date -d \"$LAST_HB\" +%s 2>/dev/null || echo 0)\n NOW_EPOCH=$(date +%s)\n AGE=$((NOW_EPOCH - LAST_EPOCH))\n\n # If more than 30 minutes, likely abnormal termination\n if [ $AGE -gt 1800 ]; then\n echo \"⚠️ Previous session ended abnormally!\" >&2\n echo \" Session #$SESSION_NUM ($AGENT_TYPE agent)\" >&2\n echo \" Last heartbeat: $(date -d \"$LAST_HB\" '+%Y-%m-%d %H:%M:%S')\" >&2\n echo \" Time since: $((AGE / 60)) minutes\" >&2\n echo \"\" >&2\n echo \"Recommended actions:\" >&2\n echo \"1. Check git status for uncommitted changes\" >&2\n echo \"2. Review what was being worked on\" >&2\n echo \"3. Complete partial work or rollback\" >&2\n echo \"4. Mark session as 'interrupted' in session-state.json\" >&2\n echo \"\" >&2\n\n # Check git status\n if [[ -n $(git status --porcelain 2>/dev/null) ]]; then\n echo \"⚠️ You have uncommitted changes!\" >&2\n git status --short >&2\n fi\n\n # Mark session as interrupted\n jq '.status = \"interrupted\"' \"$SESSION_STATE\" > \"$SESSION_STATE.tmp\" && \\\n mv \"$SESSION_STATE.tmp\" \"$SESSION_STATE\"\n else\n echo \"Resuming active session #$SESSION_NUM ($AGENT_TYPE agent)\" >&2\n fi\n else\n echo \"⚠️ Session active but no heartbeat recorded\" >&2\n fi\nelse\n echo \"Previous session #$SESSION_NUM completed successfully\" >&2\nfi\n\n# Show progress summary\nif [ -f \".claude/progress/feature-list.json\" ]; then\n TOTAL=$(cat .claude/progress/feature-list.json | jq -r '.total_features // 0')\n COMPLETED=$(cat .claude/progress/feature-list.json | jq -r '.completed // 0')\n PENDING=$((TOTAL - COMPLETED))\n\n echo \"\" >&2\n echo \"📊 Progress Summary:\" >&2\n echo \" Total features: $TOTAL\" >&2\n echo \" Completed: $COMPLETED ($(( COMPLETED * 100 / TOTAL ))%)\" >&2\n echo \" Pending: $PENDING\" >&2\nfi\n\nexit 0\n```\n\n### 4. Coding Agent Verification (verify-coding-agent.sh)\n\n**Purpose**: Ensure coding-agent updated progress before stopping.\n\n```bash\n#!/bin/bash\n# .claude/hooks/verify-coding-agent.sh\n\n# Only run for coding-agent\nAGENT_NAME=${1:-\"unknown\"}\n\nif [[ \"$AGENT_NAME\" != \"coding-agent\" ]]; then\n exit 0\nfi\n\n# Check if progress was updated\nSESSION_STATE=\".claude/progress/session-state.json\"\nFEATURE_LIST=\".claude/progress/feature-list.json\"\n\nif [ ! -f \"$SESSION_STATE\" ] || [ ! -f \"$FEATURE_LIST\" ]; then\n echo \"⚠️ Progress files not found. Please ensure they are created.\" >&2\n exit 1\nfi\n\n# Get last update times\nFEATURE_UPDATE=$(date -r \"$FEATURE_LIST\" +%s 2>/dev/null || echo 0)\nSESSION_UPDATE=$(date -r \"$SESSION_STATE\" +%s 2>/dev/null || echo 0)\nNOW=$(date +%s)\n\n# Check if updates are recent (within 10 minutes)\nFEATURE_AGE=$((NOW - FEATURE_UPDATE))\nSESSION_AGE=$((NOW - SESSION_UPDATE))\n\nif [ $FEATURE_AGE -gt 600 ] && [ $SESSION_AGE -gt 600 ]; then\n echo \"⚠️ WARNING: Progress tracking may not be up to date!\" >&2\n echo \"\" >&2\n echo \"Before stopping, please ensure you have:\" >&2\n echo \"1. Updated feature status in feature-list.json\" >&2\n echo \"2. Added session summary to claude-progress.txt\" >&2\n echo \"3. Committed all changes\" >&2\n echo \"\" >&2\n echo \"Last updates:\" >&2\n echo \" Feature list: $((FEATURE_AGE / 60)) minutes ago\" >&2\n echo \" Session state: $((SESSION_AGE / 60)) minutes ago\" >&2\n echo \"\" >&2\n\n # Ask for confirmation\n read -p \"Continue without updating progress? (y/N): \" -n 1 -r\n echo\n if [[ ! $REPLY =~ ^[Yy]$ ]]; then\n echo \"Please update progress before stopping the agent.\" >&2\n exit 1\n fi\nfi\n\n# Check for uncommitted changes\nif [[ -n $(git status --porcelain 2>/dev/null) ]]; then\n echo \"⚠️ You have uncommitted changes!\" >&2\n echo \" Please commit your work before stopping the agent.\" >&2\n git status --short >&2\n echo \"\"\n read -p \"Continue without committing? (y/N): \" -n 1 -r\n echo\n if [[ ! $REPLY =~ ^[Yy]$ ]]; then\n exit 1\n fi\nfi\n\necho \"✅ Progress verification complete\" >&2\nexit 0\n```\n\n### 5. Session End Handler (session-end.sh)\n\n**Purpose**: Cleanly close sessions and prepare for recovery.\n\n```bash\n#!/bin/bash\n# .claude/hooks/session-end.sh\n\nSESSION_STATE=\".claude/progress/session-state.json\"\n\nif [ -f \"$SESSION_STATE\" ]; then\n # Update session end time\n END_TIME=$(date -Iseconds)\n\n # Calculate duration\n START_TIME=$(cat \"$SESSION_STATE\" | jq -r '.started_at // \"unknown\"')\n if [[ \"$START_TIME\" != \"unknown\" ]]; then\n START_EPOCH=$(date -d \"$START_TIME\" +%s 2>/dev/null || echo 0)\n END_EPOCH=$(date +%s)\n DURATION_MINUTES=$(((END_EPOCH - START_EPOCH) / 60))\n else\n DURATION_MINUTES=0\n fi\n\n # Update session state\n cat \"$SESSION_STATE\" | \\\n jq \"{\n .,\n \\\"status\\\": \\\"completed\\\",\n \\\"ended_at\\\": \\\"$END_TIME\\\",\n \\\"duration_minutes\\\": $DURATION_MINUTES\n }\" > \"$SESSION_STATE.tmp\" && \\\n mv \"$SESSION_STATE.tmp\" \"$SESSION_STATE\"\n\n # Log session completion\n SESSION_NUM=$(cat \"$SESSION_STATE\" | jq -r '.session_number // \"?\"')\n echo \"Session #$SESSION_NUM completed successfully\" >&2\n echo \"Duration: $DURATION_MINUTES minutes\" >&2\nfi\n\n# Clean up temporary files\nrm -f .claude/temp/*.tmp 2>/dev/null\n\n# Backup progress files\nBACKUP_DIR=\".claude/progress/backups\"\nmkdir -p \"$BACKUP_DIR\"\ncp .claude/progress/*.json \"$BACKUP_DIR/\" 2>/dev/null || true\n\necho \"Session cleanup complete\" >&2\nexit 0\n```\n\n## Advanced Hook Patterns\n\n### 1. Context Injection Hook\n\nInject relevant context into user prompts automatically:\n\n```bash\n#!/bin/bash\n# .claude/hooks/context-injection.sh\n\nUSER_PROMPT=\"$1\"\n\n# Add progress context if working on features\nif [ -f \".claude/progress/session-state.json\" ]; then\n CURRENT_FEATURE=$(cat .claude/progress/session-state.json | jq -r '.current_feature.id // \"None\"')\n\n if [[ \"$CURRENT_FEATURE\" != \"None\" ]]; then\n FEATURE_INFO=$(cat .claude/progress/feature-list.json | \\\n jq --arg id \"$CURRENT_FEATURE\" \\\n '.categories[].features[] | select(.id == $id)')\n\n echo \"Current context: Working on $CURRENT_FEATURE\"\n echo \"Feature details: $FEATURE_INFO\"\n fi\nfi\n\n# Pass through original prompt\necho \"$USER_PROMPT\"\n```\n\n### 2. Quality Gate Hook\n\nEnforce quality standards before commits:\n\n```bash\n#!/bin/bash\n# .claude/hooks/quality-gate.sh\n\n# Run only before commit operations\nif [[ \"$1\" != \"pre-commit\" ]]; then\n exit 0\nfi\n\n# Check if tests pass\nif command -v npm >/dev/null 2>&1; then\n if ! npm test --silent 2>/dev/null; then\n echo \"❌ Tests are failing. Please fix before committing.\" >&2\n exit 1\n fi\nfi\n\n# Check code coverage (if configured)\nif [ -f \"coverage/coverage-summary.json\" ]; then\n COVERAGE=$(cat coverage/coverage-summary.json | jq -r '.total.lines.pct')\n if (( $(echo \"$COVERAGE \u003c 80\" | bc -l) )); then\n echo \"⚠️ Code coverage is ${COVERAGE}%. Consider adding tests.\" >&2\n fi\nfi\n\n# Check for TODOs in committed files\nTODO_COUNT=$(git diff --cached --name-only | xargs grep -l \"TODO\\|FIXME\" 2>/dev/null | wc -l)\nif [ $TODO_COUNT -gt 0 ]; then\n echo \"⚠️ Found TODOs/FIXMEs in files being committed:\" >&2\n git diff --cached --name-only | xargs grep -n \"TODO\\|FIXME\" 2>/dev/null >&2\n echo \"\" >&2\n echo \"Consider addressing these before committing.\" >&2\nfi\n\nexit 0\n```\n\n### 3. Resource Monitor Hook\n\nMonitor system resources during long-running sessions:\n\n```bash\n#!/bin/bash\n# .claude/hooks/resource-monitor.sh\n\n# Check system resources every 10 minutes\nINTERVAL=600\n\nwhile true; do\n # Check disk space\n DISK_USAGE=$(df . | awk 'NR==2 {print $5}' | sed 's/%//')\n if [ $DISK_USAGE -gt 90 ]; then\n echo \"⚠️ Disk usage is ${DISK_USAGE}%. Consider cleaning up.\" >&2\n fi\n\n # Check memory usage\n if command -v free >/dev/null 2>&1; then\n MEM_USAGE=$(free | awk 'NR==2{printf \"%.0f\", $3*100/$2}')\n if [ $MEM_USAGE -gt 90 ]; then\n echo \"⚠️ Memory usage is ${MEM_USAGE}%.\" >&2\n fi\n fi\n\n # Check for large temp files\n TEMP_SIZE=$(du -sh .claude/temp 2>/dev/null | awk '{print $1}' | sed 's/[A-Z]//')\n if [[ \"$TEMP_SIZE\" -gt 100 ]]; then # More than 100MB\n echo \"⚠️ Temp directory is large (${TEMP_SIZE}MB). Consider cleanup.\" >&2\n fi\n\n sleep $INTERVAL\ndone &\n```\n\n## Hook Configuration Patterns\n\n### 1. Conditional Hooks\n\nRun hooks only for specific conditions:\n\n```json\n{\n \"hooks\": {\n \"PreToolUse\": [\n {\n \"matcher\": {\n \"agent\": \"opus\",\n \"tool\": [\"Edit\", \"Write\"]\n },\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"/bin/bash .claude/hooks/block-opus-edits.sh\"\n }\n ]\n }\n ]\n }\n}\n```\n\n### 2. Hook Chains\n\nRun multiple hooks in sequence:\n\n```json\n{\n \"hooks\": {\n \"PostToolUse\": [\n {\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"/bin/bash .claude/hooks/update-progress-reminder.sh\"\n },\n {\n \"type\": \"command\",\n \"command\": \"/bin/bash .claude/hooks/quality-check.sh\"\n },\n {\n \"type\": \"notification\",\n \"message\": \"Remember to commit your changes!\"\n }\n ]\n }\n ]\n }\n}\n```\n\n### 3. Hook Parameters\n\nPass parameters to hooks:\n\n```json\n{\n \"hooks\": {\n \"SessionStart\": [\n {\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"/bin/bash .claude/hooks/session-check.sh\",\n \"args\": {\n \"heartbeat_timeout\": 1800,\n \"require_clean_git\": true\n }\n }\n ]\n }\n ]\n }\n}\n```\n\n## Testing Hooks\n\n### Unit Testing Hooks\n\n```bash\n#!/bin/bash\n# test-hooks.sh\n\n# Test pre-tool-guard hook\necho \"Testing pre-tool-guard...\"\necho '{\"tool\": \"Edit\", \"file_path\": \"src/test.js\"}' | .claude/hooks/pre-tool-guard.sh\n[ $? -eq 1 ] && echo \"✅ Correctly blocked Edit on src/\" || echo \"❌ Failed to block\"\n\necho '{\"tool\": \"Read\", \"file_path\": \"src/test.js\"}' | .claude/hooks/pre-tool-guard.sh\n[ $? -eq 0 ] && echo \"✅ Correctly allowed Read on src/\" || echo \"❌ Failed to allow\"\n\n# Test session-progress-check\necho \"Testing session-progress-check...\"\n# Create test session state\ncat > test-session.json \u003c\u003c EOF\n{\n \"session_number\": 1,\n \"status\": \"active\",\n \"heartbeat\": {\n \"last_heartbeat\": \"2025-01-01T10:00:00Z\"\n }\n}\nEOF\n\n.claude/hooks/session-progress-check.sh \u003c test-session.json\necho \"✅ Session check completed\"\n```\n\n### Integration Testing\n\n```bash\n#!/bin/bash\n# integration-test.sh\n\n# Set up test environment\nTEST_DIR=$(mktemp -d)\ncd \"$TEST_DIR\"\nmkdir -p .claude/{hooks,progress}\n\n# Copy hooks to test\ncp ~/.claude/skills/progress-harness/assets/hooks/* .claude/hooks/\n\n# Test full session flow\necho \"Starting integration test...\"\n\n# 1. Session start\n.claude/hooks/session-progress-check.sh\n\n# 2. Simulate tool usage\necho '{\"tool\": \"Write\", \"file_path\": \"test.js\"}' | .claude/hooks/pre-tool-guard.sh\necho '{\"tool\": \"Write\", \"file_path\": \"test.js\"}' | .claude/hooks/post-tool-guard.sh\n\n# 3. Session end\n.claude/hooks/session-end.sh\n\necho \"✅ Integration test passed\"\ncd ..\nrm -rf \"$TEST_DIR\"\n```\n\n## Troubleshooting Hooks\n\n### Common Issues\n\n1. **Hook Not Executing**\n - Check file permissions: `chmod +x .claude/hooks/*.sh`\n - Verify .claude/settings.json format\n - Check Claude Code logs for errors\n\n2. **Hook Failing Silently**\n - Add debug output: `echo \"Hook running...\" >&2`\n - Check exit codes: `echo $?` after hook execution\n - Run hook manually to test\n\n3. **Performance Issues**\n - Profile hook execution time\n - Optimize heavy operations\n - Consider running expensive checks asynchronously\n\n### Debug Mode Hook\n\n```bash\n#!/bin/bash\n# .claude/hooks/debug-wrapper.sh\n\n# Enable debug mode\nif [ \"$DEBUG_HOOKS\" = \"1\" ]; then\n echo \"=== DEBUG: Hook $0 ===\" >&2\n echo \"Input: $1\" >&2\n echo \"Environment:\" >&2\n env | grep HOOK >&2\n echo \"========================\" >&2\nfi\n\n# Run actual hook\n\"$@\"\nEXIT_CODE=$?\n\nif [ \"$DEBUG_HOOKS\" = \"1\" ]; then\n echo \"=== Hook exit code: $EXIT_CODE ===\" >&2\nfi\n\nexit $EXIT_CODE\n```\n\n## Best Practices\n\n### 1. Hook Design\n- Keep hooks focused and simple\n- Use descriptive error messages\n- Log important events for debugging\n- Handle edge cases gracefully\n\n### 2. Performance\n- Minimize blocking operations\n- Cache expensive computations\n- Use background processes for monitoring\n- Implement timeouts for long operations\n\n### 3. Maintainability\n- Document hook purpose and behavior\n- Use version control for hook changes\n- Test hooks thoroughly before deployment\n- Monitor hook execution in production\n\n### 4. Security\n- Validate all inputs\n- Use absolute paths for commands\n- Avoid executing user input directly\n- Review hooks for security vulnerabilities\n\n### 5. User Experience\n- Provide clear feedback messages\n- Offer recovery options when possible\n- Allow bypass for emergency situations\n- Keep messages concise and actionable\n\n## Hook Evolution\n\n### Phase 1: Basic Enforcement\n- Block unauthorized edits\n- Remind about progress updates\n- Detect session interruptions\n\n### Phase 2: Quality Assurance\n- Automated testing gates\n- Code quality checks\n- Performance monitoring\n\n### Phase 3: Intelligence\n- Predictive block detection\n- Smart context injection\n- Adaptive enforcement\n\nThe hook system is essential for maintaining the integrity and effectiveness of the Two-Agent Framework, ensuring that agents follow proper workflows and that development progresses smoothly and predictably.","content_type":"text/markdown; charset=utf-8","language":"markdown","size":19468,"content_sha256":"74ff2c6aacd089045c20268deddc6f914d731c2c096efc0cded9af8dec3f5308"},{"filename":"references/initializer-agent-spec.md","content":"# Initializer Agent Specification\n\n## Overview\n\nThe Initializer Agent is the project architecture and planning specialist in the Two-Agent Framework. Its primary responsibility is to break down complex projects into granular, trackable features and establish a robust development environment. This agent ensures that no detail is overlooked, creating comprehensive roadmaps that guide development through hundreds of incremental features.\n\n## Agent Definition\n\n```yaml\nname: initializer-agent\ndescription: Use this agent when starting a new project, needing to break down complex tasks, or setting up a development environment. Examples: \"Initialize this project with a comprehensive feature breakdown\", \"Set up a new React app with all features planned\", \"Break down this complex feature into 200+ subtasks\", \"Create a proper project structure for a microservices app\", \"I need to plan a complete e-commerce platform\"\nmodel: sonnet\ncolor: blue\ntools: [\"Write\", \"Read\", \"Bash\", \"Edit\", \"Grep\", \"Glob\"]\n```\n\n## Core Responsibilities\n\n### 1. Project Analysis and Scoping\n- Understand business requirements and technical constraints\n- Identify all major system components and integrations\n- Assess complexity and determine appropriate granularity\n- Recognize common patterns and best practices for the project type\n\n### 2. Feature Architecture Design\n- Create hierarchical feature breakdown (epics → features → subtasks)\n- Ensure comprehensive coverage of all functionality\n- Identify and document dependencies between features\n- Balance feature sizes for 2-4 hour implementation windows\n\n### 3. Environment Setup and Configuration\n- Create reproducible development environments\n- Set up all necessary tooling and dependencies\n- Initialize progress tracking system\n- Configure automated workflows and hooks\n\n### 4. Documentation and Planning\n- Create clear project documentation\n- Establish coding standards and conventions\n- Define success criteria and metrics\n- Provide implementation roadmaps\n\n## Detailed Workflow\n\n### Phase 1: Context Discovery (First 15 minutes)\n\n#### Step 1: Environment Assessment\n```bash\n# Always start with understanding the current state\npwd\ngit status\ngit log --oneline -10\nls -la\n\n# Look for existing project files\nif [ -f \"package.json\" ]; then echo \"Node.js project detected\"; fi\nif [ -f \"requirements.txt\" ]; then echo \"Python project detected\"; fi\nif [ -f \"Cargo.toml\" ]; then echo \"Rust project detected\"; fi\n```\n\n#### Step 2: Requirement Gathering\nAsk clarifying questions to understand:\n\n**Project Scope:**\n- What problem does this solve?\n- Who are the users?\n- What are the success criteria?\n\n**Technical Requirements:**\n- What technology stack is preferred?\n- Are there constraints or limitations?\n- What integrations are needed?\n\n**Scale Considerations:**\n- Expected user base?\n- Data volume estimates?\n- Performance requirements?\n\n**Timeline and Team:**\n- Development timeline?\n- Team size and expertise?\n- Deployment preferences?\n\n#### Step 3: Pattern Recognition\nIdentify the project type and apply appropriate patterns:\n\n```javascript\n// Common project patterns\nconst PROJECT_PATTERNS = {\n \"web-app\": {\n categories: [\"authentication\", \"ui\", \"api\", \"database\", \"deployment\"],\n base_features: 50,\n complexity_multiplier: 1.5\n },\n \"api-service\": {\n categories: [\"authentication\", \"endpoints\", \"database\", \"documentation\"],\n base_features: 30,\n complexity_multiplier: 1.2\n },\n \"mobile-app\": {\n categories: [\"authentication\", \"ui\", \"storage\", \"api\", \"deployment\"],\n base_features: 60,\n complexity_multiplier: 2.0\n },\n \"cli-tool\": {\n categories: [\"commands\", \"config\", \"output\", \"integration\"],\n base_features: 20,\n complexity_multiplier: 1.0\n }\n};\n```\n\n### Phase 2: Feature Architecture (30-60 minutes)\n\n#### Step 1: Category Design\nCreate 10-20 high-level categories based on project type:\n\n**For Web Applications:**\n1. **Infrastructure** (INFRA) - Project setup, tools, CI/CD\n2. **Authentication** (AUTH) - User management, sessions, permissions\n3. **Database** (DB) - Schema, migrations, data access\n4. **API** (API) - Endpoints, validation, documentation\n5. **Frontend Core** (UI) - Components, routing, state\n6. **User Features** (USR) - Core user functionality\n7. **Admin Features** (ADM) - Administrative interfaces\n8. **Integration** (INT) - Third-party services\n9. **Performance** (PERF) - Optimization, caching\n10. **Security** (SEC) - Security measures and audits\n11. **Testing** (TEST) - Test infrastructure and cases\n12. **Deployment** (DEPLOY) - Production deployment\n\n#### Step 2: Feature Breakdown\nFor each category, create specific features following these guidelines:\n\n**Feature Granularity Rules:**\n- Each feature should take 2-4 hours to implement\n- Features should be independently testable\n- Dependencies should be minimal and explicit\n- Each feature should deliver user value\n\n**Feature ID Convention:**\n- Format: `CATEGORY-NUMBER` (e.g., AUTH-001, UI-015)\n- Categories use 3-letter uppercase codes\n- Sequential numbering starting from 001\n- Reserve blocks for future features (e.g., AUTH-050-099)\n\n#### Step 3: Steps Array Creation\nEvery feature MUST include a detailed steps array:\n\n```json\n{\n \"id\": \"AUTH-001\",\n \"name\": \"User Registration\",\n \"description\": \"New user can create account with email verification\",\n \"steps\": [\n \"Navigate to application homepage\",\n \"Locate and click 'Sign Up' button\",\n \"Verify registration page loads with form\",\n \"Enter valid email in email field\",\n \"Enter password meeting requirements\",\n \"Confirm password in repeat field\",\n \"Accept terms and conditions\",\n \"Click 'Create Account' button\",\n \"Verify email sent confirmation\",\n \"Open email inbox and find verification email\",\n \"Click verification link in email\",\n \"Confirm successful registration with redirect\"\n ]\n}\n```\n\n**Steps Writing Guidelines:**\n1. Start with navigation to the feature\n2. Include all user interactions\n3. Specify expected outcomes\n4. Write for non-technical users\n5. Include edge cases and error paths\n\n### Phase 3: Environment Setup (15-30 minutes)\n\n#### Step 1: Directory Structure Creation\n```bash\n# Create comprehensive directory structure\nmkdir -p {src,tests,docs,scripts,config,.claude/{progress,hooks,skills}}\n\n# Project-specific directories based on type\nif [[ \"$PROJECT_TYPE\" == \"web-app\" ]]; then\n mkdir -p src/{components,pages,services,hooks,utils}\n mkdir -p tests/{unit,integration,e2e}\n mkdir -p public/{assets,images}\nfi\n```\n\n#### Step 2: Configuration Files\nCreate all necessary configuration files:\n\n**package.json for Node.js:**\n```json\n{\n \"name\": \"{{PROJECT_NAME}}\",\n \"version\": \"1.0.0\",\n \"scripts\": {\n \"dev\": \"next dev\",\n \"build\": \"next build\",\n \"test\": \"jest\",\n \"test:e2e\": \"playwright test\"\n },\n \"dependencies\": {\n \"next\": \"^14.0.0\",\n \"react\": \"^18.0.0\"\n }\n}\n```\n\n**Docker configuration:**\n```dockerfile\n# Dockerfile\nFROM node:18-alpine\nWORKDIR /app\nCOPY package*.json ./\nRUN npm ci --only=production\nCOPY . .\nEXPOSE 3000\nCMD [\"npm\", \"start\"]\n```\n\n#### Step 3: Progress System Initialization\n```bash\n# Use progress-harness skill to create tracking system\necho \"Initializing progress tracking system...\"\n\n# Create initial feature list with generated features\ncat > .claude/progress/feature-list.json \u003c\u003c EOF\n$(cat \u003c\u003cFEATURES\n{\n \"project_name\": \"$PROJECT_NAME\",\n \"total_features\": $TOTAL_FEATURES,\n \"completed\": 0,\n \"pending\": $TOTAL_FEATURES,\n \"categories\": $(echo \"$FEATURE_CATEGORIES_JSON\")\n}\nFEATURES\n)\nEOF\n\n# Create initial session state\ncat > .claude/progress/session-state.json \u003c\u003c EOF\n{\n \"session_number\": 0,\n \"started_at\": \"$(date -Iseconds)\",\n \"agent_type\": \"initializer\",\n \"status\": \"completed\",\n \"metadata\": {\n \"total_features_created\": $TOTAL_FEATURES,\n \"categories_created\": $NUM_CATEGORIES,\n \"estimated_development_time\": $ESTIMATED_HOURS\n }\n}\nEOF\n\n# Create human-readable progress\necho \"# $PROJECT_NAME Development Progress\n# Started: $(date +%Y-%m-%d)\n# Total Features: $TOTAL_FEATURES\n\n## Initialization Complete\n- [x] Project structure created\n- [x] Feature breakdown completed ($TOTAL_FEATURES features)\n- [x] Environment configured\n- [x] Progress tracking initialized\n\n## Ready for Development\nStart with INFRA-001: Initialize development environment\nEstimated total development time: $ESTIMATED_HOURS hours\n\n\" > .claude/progress/claude-progress.txt\n```\n\n### Phase 4: Documentation Creation (15 minutes)\n\n#### Step 1: Project README\n```markdown\n# $PROJECT_NAME\n\n## Overview\nBrief description of the project and its purpose.\n\n## Features\n- [ ] AUTH-001: User Registration\n- [ ] AUTH-002: User Login\n- [List of first 10 features]\n\n## Getting Started\n\n### Prerequisites\n- Node.js 18+\n- npm or yarn\n\n### Installation\n\\`\\`\\`bash\n# Clone repository\ngit clone \u003crepository-url>\ncd $PROJECT_NAME\n\n# Install dependencies\nnpm install\n\n# Set up environment\ncp .env.example .env\n\n# Initialize database\nnpm run db:migrate\n\n# Start development server\nnpm run dev\n\\`\\`\\`\n\n## Development Workflow\n\nThis project uses the Two-Agent Framework for development:\n\n1. Features are tracked in \\`.claude/progress/feature-list.json\\`\n2. Each feature includes detailed test steps\n3. Progress is updated after each feature completion\n\n## Contributing\nSee CONTRIBUTING.md for details.\n\n## License\n[License information]\n```\n\n#### Step 2: Development Guidelines\n```markdown\n# Development Guidelines\n\n## Code Standards\n- Use TypeScript for all new code\n- Follow ESLint configuration\n- Write tests for all features\n- Document complex logic\n\n## Git Workflow\n- Feature branches: \\`feature/ID-name\\`\n- Commit format: \\`feat(ID): description\\`\n- PR required for all changes\n\n## Testing\n- Unit tests: \\`npm test\\`\n- E2E tests: \\`npm run test:e2e\\`\n- Coverage target: 80%\n\n## Deployment\n- Main branch deploys to production\n- Develop branch deploys to staging\n```\n\n### Phase 5: Initial Commit (5 minutes)\n\n```bash\n# Initialize git repository if needed\nif [ ! -d \".git\" ]; then\n git init\n git remote add origin \u003crepository-url>\nfi\n\n# Create comprehensive initial commit\ngit add .\ngit commit -m \"feat: Initialize $PROJECT_NAME with Two-Agent Framework\n\n- Set up project structure and configuration\n- Created feature breakdown with $TOTAL_FEATURES features across $NUM_CATEGORIES categories\n- Initialized progress tracking system\n- Added development environment setup scripts\n- Configured CI/CD pipeline\n- Set up testing infrastructure\n\nEstimated development effort: $ESTIMATED_HOURS hours\nReady for incremental development using coding-agent\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)\n\nCo-Authored-By: Claude \[email protected]>\"\n\n# Optional: Push to remote\nif [ \"$REMOTE_REPO\" ]; then\n git push -u origin main\n echo \"Repository initialized at: $REMOTE_REPO\"\nfi\n```\n\n## Common Project Templates\n\n### Web Application Template\n\n```javascript\nconst WEB_APP_TEMPLATE = {\n categories: {\n \"INFRA\": {\n \"priority\": \"high\",\n \"features\": [\n {\n \"id\": \"INFRA-001\",\n \"name\": \"Project Initialization\",\n \"steps\": [\n \"Create project directory structure\",\n \"Initialize package.json with dependencies\",\n \"Set up TypeScript configuration\",\n \"Configure ESLint and Prettier\",\n \"Initialize git repository\",\n \"Create basic README\"\n ]\n },\n {\n \"id\": \"INFRA-002\",\n \"name\": \"Development Environment\",\n \"steps\": [\n \"Set up hot reload for development\",\n \"Configure environment variables\",\n \"Set up database connection\",\n \"Create base component library\",\n \"Set up routing structure\"\n ]\n }\n ]\n },\n \"AUTH\": {\n \"priority\": \"high\",\n \"features\": [\n {\n \"id\": \"AUTH-001\",\n \"name\": \"User Registration\",\n \"steps\": [\n \"Create registration API endpoint\",\n \"Build registration form component\",\n \"Add email validation\",\n \"Implement password strength checker\",\n \"Add email verification flow\",\n \"Create success/error states\"\n ]\n },\n {\n \"id\": \"AUTH-002\",\n \"name\": \"User Login\",\n \"steps\": [\n \"Create login API endpoint\",\n \"Build login form component\",\n \"Implement session management\",\n \"Add remember me functionality\",\n \"Handle login errors gracefully\"\n ]\n },\n {\n \"id\": \"AUTH-003\",\n \"name\": \"Password Reset\",\n \"steps\": [\n \"Create forgot password flow\",\n \"Send reset email with token\",\n \"Build password reset form\",\n \"Validate token and update password\",\n \"Expire reset tokens after use\"\n ]\n }\n ]\n }\n }\n};\n```\n\n### API Service Template\n\n```javascript\nconst API_SERVICE_TEMPLATE = {\n categories: {\n \"CORE\": {\n \"priority\": \"high\",\n \"features\": [\n {\n \"id\": \"CORE-001\",\n \"name\": \"Server Setup\",\n \"steps\": [\n \"Initialize Express/Fastify application\",\n \"Configure middleware stack\",\n \"Set up request logging\",\n \"Configure error handling\",\n \"Add health check endpoint\"\n ]\n },\n {\n \"id\": \"CORE-002\",\n \"name\": \"Database Connection\",\n \"steps\": [\n \"Set up database connection pool\",\n \"Create base repository pattern\",\n \"Add transaction support\",\n \"Implement connection retry logic\",\n \"Add database health checks\"\n ]\n }\n ]\n },\n \"API\": {\n \"priority\": \"high\",\n \"features\": [\n {\n \"id\": \"API-001\",\n \"name\": \"REST API Structure\",\n \"steps\": [\n \"Design API endpoint structure\",\n \"Implement request validation\",\n \"Add response formatting\",\n \"Create error response standards\",\n \"Set up API versioning\"\n ]\n }\n ]\n }\n }\n};\n```\n\n## Quality Metrics and Validation\n\n### Feature Quality Checklist\n\nFor each generated feature, verify:\n\n- [ ] ID follows `CATEGORY-NUMBER` format\n- [ ] Name is clear and descriptive\n- [ ] Description explains the feature's purpose\n- [ ] Steps array has 3-15 actionable steps\n- [ ] Steps are written for non-technical users\n- [ ] Each step has a verifiable outcome\n- [ ] Dependencies are clearly identified\n- [ ] Estimated time is 2-4 hours\n\n### Project Completeness Checklist\n\nBefore completing initialization:\n\n- [ ] All major system areas are covered\n- [ ] Authentication flow is complete\n- [ ] Data management is planned\n- [ ] Error handling is included\n- [ ] Performance considerations are addressed\n- [ ] Security measures are planned\n- [ ] Testing strategy is defined\n- [ ] Deployment process is outlined\n\n## Error Handling and Recovery\n\n### Common Initialization Issues\n\n**Issue: Incomplete Feature Coverage**\n```\nSolution:\n1. Review project requirements again\n2. Walk through user journey step by step\n3. Ask \"What's missing?\" for each category\n4. Add missing features\n```\n\n**Issue: Features Too Large**\n```\nSolution:\n1. Break down into smaller, focused features\n2. Ensure each feature has a single responsibility\n3. Aim for 2-4 hour implementation time\n```\n\n**Issue: Dependencies Not Identified**\n```\nSolution:\n1. Create dependency matrix\n2. Identify prerequisite features\n3. Document in dependencies array\n4. Consider alternative implementations\n```\n\n### Recovery Procedures\n\n```bash\n# If initialization fails partially\ngit reset --hard HEAD\nrm -rf .claude/progress\n# Restart initialization process\n\n# If feature list is corrupted\ngit checkout HEAD -- .claude/progress/feature-list.json\n# Regenerate from backup or scratch\n\n# If environment setup fails\n# Run diagnostic script\n./scripts/diagnose-setup.sh\n# Fix specific issues and continue\n```\n\n## Communication Patterns\n\n### Initial Request Handling\n\nWhen receiving an initialization request:\n\n1. **Acknowledge and Clarify**\n ```\n I'll help you initialize [PROJECT_TYPE] project.\n\n To ensure I create a comprehensive breakdown, please clarify:\n - Primary technology stack?\n - Key business requirements?\n - Expected user scale?\n - Any specific constraints?\n ```\n\n2. **Set Expectations**\n ```\n I'll create a detailed feature breakdown with approximately [X] features\n across [Y] categories. This typically takes 45-60 minutes.\n Each feature will include detailed test steps for verification.\n ```\n\n3. **Progress Updates**\n ```\n - Phase 1: Analyzing requirements (15 min)\n - Phase 2: Creating feature breakdown (30-45 min)\n - Phase 3: Setting up environment (15 min)\n - Phase 4: Finalizing documentation (15 min)\n ```\n\n### Handoff Communication\n\nWhen handing off to coding-agent:\n\n1. **Provide Context**\n ```\n Project initialized with [X] features ready for development.\n\n Priority order:\n 1. Start with INFRA-001 for environment setup\n 2. Move to AUTH-001 for authentication\n 3. Follow dependency order in feature-list.json\n\n Current progress: 0/[X] features complete\n ```\n\n2. **Highlight Critical Path**\n ```\n Critical features for MVP:\n - INFRA-001: Environment setup (blocks all others)\n - AUTH-001: User registration (blocks user features)\n - CORE-001: Basic UI structure (blocks all UI features)\n ```\n\n## Best Practices\n\n### 1. Feature Design\n- Focus on user value, not technical components\n- Keep features independent where possible\n- Minimize cross-feature dependencies\n- Ensure each feature is testable\n\n### 2. Progress Tracking\n- Use consistent naming conventions\n- Include detailed, actionable steps\n- Mark all features as \"passes\": false initially\n- Update estimates based on actual implementation\n\n### 3. Documentation\n- Provide clear getting started instructions\n- Document architectural decisions\n- Include examples and templates\n- Keep documentation up to date\n\n### 4. Collaboration\n- Consider team size and expertise\n- Plan for code review processes\n- Design for parallel development\n- Include quality gates\n\n## Performance Optimization\n\n### Initialization Performance\n- Cache common project patterns\n- Use templates for similar project types\n- Parallelize independent feature creation\n- Optimize JSON generation for large feature lists\n\n### Memory Management\n- Stream large feature list generation\n- Use generators for extensive calculations\n- Clear temporary data structures\n- Monitor memory usage during operation\n\n## Security Considerations\n\n### Initial Setup Security\n- Generate secure secret keys\n- Set appropriate file permissions\n- Configure secure defaults\n- Document security requirements\n\n### Feature Security\n- Include security-related features\n- Plan for authentication and authorization\n- Consider data protection requirements\n- Plan for security testing\n\nThe Initializer Agent sets the foundation for successful project development by creating comprehensive, well-structured plans that guide the entire development process from conception to deployment.","content_type":"text/markdown; charset=utf-8","language":"markdown","size":19158,"content_sha256":"aae531ba2b93140bd49ad8c208fbd4ee5cdc625effe4d36f49df980ae5f51ec5"},{"filename":"references/session-workflow.md","content":"# Session Workflow\n\n## Overview\n\nThe session workflow defines the standardized procedures for managing development sessions within the Two-Agent Framework. It ensures consistency, enables recovery from interruptions, and maintains clean state between sessions. This workflow is designed for 2-4 hour focused development sessions that incrementally build features while preserving context.\n\n## Session Types\n\n### 1. Initializer Sessions\n- **Purpose**: Project planning and feature breakdown\n- **Duration**: 4-8 hours\n- **Agent**: initializer-agent\n- **Output**: Complete feature-list.json with 200+ features\n\n### 2. Coding Sessions\n- **Purpose**: Implement single features incrementally\n- **Duration**: 2-4 hours\n- **Agent**: coding-agent\n- **Output**: Completed feature with tests and documentation\n\n### 3. Recovery Sessions\n- **Purpose**: Resume from abnormal termination\n- **Duration**: 30-60 minutes\n- **Agent**: Depends on last activity\n- **Output**: Clean state ready for normal session\n\n### 4. Review Sessions\n- **Purpose**: Assess progress and plan next steps\n- **Duration**: 1-2 hours\n- **Agent**: Any (Opus orchestrates)\n- **Output**: Updated roadmap and priority adjustments\n\n## Standard Session Workflow\n\n### Phase 1: Session Initialization\n\n#### Step 1: Environment Check\n```bash\n# Always start with location verification\npwd\n\n# Check git status\ngit status\ngit log --oneline -5\n\n# Verify working directory is clean\nif [[ -n $(git status --porcelain) ]]; then\n echo \"⚠️ Working directory not clean - commit or stash changes\"\n exit 1\nfi\n```\n\n#### Step 2: Context Recovery\n```bash\n# Check for abnormal exit\nif [ -f \".claude/progress/session-state.json\" ]; then\n cat .claude/progress/session-state.json | jq '.status'\n\n # If status is \"active\" with old heartbeat, recovery needed\n LAST_HB=$(cat .claude/progress/session-state.json | jq -r '.heartbeat.last_heartbeat')\n if [ \"$STATUS\" = \"active\" ] && [ \"$LAST_HB\" != \"$(date -Iseconds)\" ]; then\n echo \"⚠️ Previous session ended abnormally - initiating recovery\"\n # Run recovery procedures\n fi\nfi\n```\n\n#### Step 3: Progress Assessment\n```bash\n# Read current state\necho \"=== Current Progress ===\"\ncat .claude/progress/claude-progress.txt | tail -20\n\necho -e \"\\n=== Feature Statistics ===\"\ncat .claude/progress/feature-list.json | jq '{total: .total_features, completed: .completed, pending: .pending}'\n\necho -e \"\\n=== Last Session ===\"\ncat .claude/progress/session-state.json | jq '{session: .session_number, last_feature: .last_feature_id, status: .status}'\n```\n\n### Phase 2: Feature Selection\n\n#### For Coding Agent Sessions\n```bash\n# Find next unblocked feature\nSELECTED_FEATURE=$(cat .claude/progress/feature-list.json | jq -r '\n .categories as $cats |\n [\n $cats[] | .features[] | select(.passes == false)\n ] | sort_by(.dependencies | length) | .[0]\n')\n\necho \"Selected feature: $(echo $SELECTED_FEATURE | jq -r '.id') - $(echo $SELECTED_FEATURE | jq -r '.name')\"\n\n# Check dependencies\nDEPS=$(echo $SELECTED_FEATURE | jq -r '.dependencies[]')\nif [ -n \"$DEPS\" ]; then\n echo \"Dependencies: $DEPS\"\n # Verify all dependencies are marked as passes: true\nfi\n```\n\n#### For Initializer Agent Sessions\n```bash\n# Determine if this is a new project or expansion\nif [ ! -f \".claude/progress/feature-list.json\" ]; then\n echo \"New project - creating initial feature breakdown\"\nelse\n echo \"Project expansion - analyzing gaps and additions needed\"\n # Analyze existing features for missing components\nfi\n```\n\n### Phase 3: Session Execution\n\n#### Coding Agent Workflow\n\n1. **Feature Preparation**\n ```bash\n # Create feature branch (optional but recommended)\n git checkout -b \"feature/$(echo $SELECTED_FEATURE | jq -r '.id | tolower')\"\n\n # Update session state\n cat .claude/progress/session-state.json | \\\n jq \".current_feature = $(echo $SELECTED_FEATURE | jq '{id, name, started_at: now}')\" > \\\n .claude/progress/session-state.json.tmp && \\\n mv .claude/progress/session-state.json.tmp .claude/progress/session-state.json\n ```\n\n2. **Development Process**\n - Read related files to understand patterns\n - Implement feature following established conventions\n - Write/update tests for the feature\n - Document any new APIs or components\n\n3. **Progress Updates**\n ```bash\n # Update heartbeat every 5 minutes during long tasks\n while [ $LONG_RUNNING_TASK = true ]; do\n cat .claude/progress/session-state.json | \\\n jq \".heartbeat.last_heartbeat = \\\"$(date -Iseconds)\\\"\" > \\\n .claude/progress/session-state.json.tmp && \\\n mv .claude/progress/session-state.json.tmp .claude/progress/session-state.json\n sleep 300\n done\n ```\n\n#### Initializer Agent Workflow\n\n1. **Project Analysis**\n - Read any existing documentation\n - Understand business requirements\n - Identify all major system components\n\n2. **Feature Breakdown**\n - Create high-level epics (10-20 categories)\n - Detail specific features (100-200 items)\n - Add granular sub-tasks (200-500 total tasks)\n - Ensure each task is 2-4 hours of work\n\n3. **Environment Setup**\n ```bash\n # Create project structure\n mkdir -p {src,tests,docs,scripts,.claude/progress}\n\n # Initialize progress tracking\n echo \"Project initialized on $(date)\" > .claude/progress/claude-progress.txt\n\n # Create initial session state\n cat > .claude/progress/session-state.json \u003c\u003c EOF\n {\n \"session_number\": 0,\n \"started_at\": \"$(date -Iseconds)\",\n \"agent_type\": \"initializer\",\n \"status\": \"completed\",\n \"metadata\": {\n \"total_features_created\": 247,\n \"categories_created\": 12\n }\n }\n EOF\n ```\n\n### Phase 4: Testing and Verification\n\n#### Manual Testing Protocol\n\n1. **Environment Preparation**\n ```bash\n # Ensure development server is running\n npm run dev\n # or\n python -m src.server\n\n # Wait for server to be ready\n until curl -s http://localhost:3000 > /dev/null; do\n echo \"Waiting for server...\"\n sleep 2\n done\n ```\n\n2. **Step-by-Step Verification**\n ```bash\n # Get the steps for current feature\n STEPS=$(cat .claude/progress/feature-list.json | \\\n jq -r --arg id \"$FEATURE_ID\" \\\n '.categories[].features[] | select(.id == $id) | .steps[]')\n\n # Execute each step manually\n echo \"Testing feature: $FEATURE_ID\"\n echo \"==============================\"\n\n for step in $STEPS; do\n echo -e \"\\nStep: $step\"\n read -p \"Press Enter after completing this step...\"\n\n # Verify step success (automated checks where possible)\n # This is where you'd add specific verification code\n done\n ```\n\n3. **Automated Testing**\n ```bash\n # Run unit tests\n npm test\n # or\n pytest\n\n # Run integration tests\n npm run test:integration\n # or\n pytest tests/integration/\n\n # Run E2E tests (if available)\n npm run test:e2e\n ```\n\n#### Browser Automation with Puppeteer MCP\n\n```javascript\n// Example test execution using Puppeteer MCP\nawait browser.navigate('http://localhost:3000');\nawait browser.click('a[href=\"/register\"]');\nawait browser.fillForm({\n email: '[email protected]',\n password: 'SecurePass123!',\n confirmPassword: 'SecurePass123!'\n});\nawait browser.click('button[type=\"submit\"]');\nawait browser.waitForText('Welcome! Your account has been created.');\n```\n\n### Phase 5: Session Completion\n\n#### Update Feature Status\n```bash\n# Mark feature as complete\ncat .claude/progress/feature-list.json | \\\n jq --arg id \"$FEATURE_ID\" \\\n '(.categories[].features[] | select(.id == $id)) |= {\n .,\n \"passes\": true,\n \"completed_at\": \"$(date -Iseconds)\",\n \"notes\": \"Successfully implemented and tested\"\n }' > .claude/progress/feature-list.json.tmp && \\\n mv .claude/progress/feature-list.json.tmp .claude/progress/feature-list.json\n```\n\n#### Update Progress Log\n```bash\n# Update claude-progress.txt\ncat >> .claude/progress/claude-progress.txt \u003c\u003c EOF\n\n## Session $SESSION_NUMBER - $(date +%Y-%m-%d) ($DURATION minutes)\n### Completed:\n- [x] $FEATURE_ID: $FEATURE_NAME ($ESTIMATED_HOURS h)\n $IMPLEMENTATION_NOTES\n\n### Statistics:\n- Total: $TOTAL_FEATURES\n- Completed: $COMPLETED_FEATURES ($(echo \"scale=1; $COMPLETED_FEATURES * 100 / $TOTAL_FEATURES\" | bc)%)\n- Session velocity: $(echo \"scale=1; $FEATURES_THIS_SESSION / ($DURATION / 60)\" | bc) features/hour\n\nEOF\n```\n\n#### Clean Git State\n```bash\n# Add all changes\ngit add .\n\n# Commit with conventional format\ngit commit -m \"feat($FEATURE_ID): Implement $FEATURE_NAME\n\n$COMMIT_BODY\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)\n\nCo-Authored-By: Claude \[email protected]>\"\n\n# Optionally merge to main\ngit checkout main\ngit merge feature/$FEATURE_ID\ngit branch -d feature/$FEATURE_ID\n```\n\n#### Update Session State\n```bash\ncat .claude/progress/session-state.json | \\\n jq '{\n .,\n \"status\": \"completed\",\n \"ended_at\": \"$(date -Iseconds)\",\n \"session_summary\": {\n \"features_completed\": 1,\n \"features_blocked\": 0,\n \"total_time_minutes\": $SESSION_MINUTES,\n \"notes\": \"Successfully completed $FEATURE_ID\"\n }\n }' > .claude/progress/session-state.json.tmp && \\\n mv .claude/progress/session-state.json.tmp .claude/progress/session-state.json\n```\n\n## Recovery Procedures\n\n### Detecting Abnormal Termination\n\nThe session-start hook automatically detects abnormal exits:\n\n```bash\n#!/bin/sh\n# .claude/hooks/session-progress-check.sh\n\nSESSION_STATE=\".claude/progress/session-state.json\"\n\nif [ -f \"$SESSION_STATE\" ]; then\n STATUS=$(cat \"$SESSION_STATE\" | jq -r '.status')\n LAST_HB=$(cat \"$SESSION_STATE\" | jq -r '.heartbeat.last_heartbeat')\n\n if [ \"$STATUS\" = \"active\" ]; then\n # Calculate time since last heartbeat\n AGE=$(($(date +%s) - $(date -d \"$LAST_HB\" +%s)))\n\n if [ $AGE -gt 1800 ]; then # 30 minutes\n echo \"⚠️ Previous session ended abnormally (last heartbeat: $LAST_HB)\"\n echo \"Running recovery procedures...\"\n\n # Check git status\n if [[ -n $(git status --porcelain) ]]; then\n echo \"Found uncommitted changes - creating recovery branch\"\n git checkout -b \"recovery-$(date +%Y%m%d-%H%M%S)\"\n git add .\n git commit -m \"Recovery: Save incomplete changes from crashed session\"\n fi\n\n # Mark session as interrupted\n jq '.status = \"interrupted\"' \"$SESSION_STATE\" > \"$SESSION_STATE.tmp\" && \\\n mv \"$SESSION_STATE.tmp\" \"$SESSION_STATE\"\n fi\n fi\nfi\n```\n\n### Recovery Workflow\n\n1. **Assess Damage**\n ```bash\n # What was being worked on?\n CURRENT_FEATURE=$(cat .claude/progress/session-state.json | jq -r '.current_feature.id')\n echo \"Was working on: $CURRENT_FEATURE\"\n\n # Check git state\n git log --oneline -5\n git status\n\n # Check for broken code\n if [ -f \"package.json\" ]; then\n npm run build 2>&1 | grep -i error || echo \"Build OK\"\n fi\n ```\n\n2. **Decision Point**\n - **Option A**: Complete partial work if mostly done\n - **Option B**: Rollback to last good state\n - **Option C**: Create new feature from remaining work\n\n3. **Execute Recovery**\n ```bash\n case $RECOVERY_OPTION in\n A)\n echo \"Completing partial work...\"\n # Continue implementation\n ;;\n B)\n echo \"Rolling back to last commit...\"\n git reset --hard HEAD\n # Mark feature as not started\n ;;\n C)\n echo \"Creating new feature for remaining work...\"\n # Split feature into smaller parts\n ;;\n esac\n ```\n\n## Session Automation Scripts\n\n### Session Start Script\n```bash\n#!/bin/bash\n# .claude/scripts/start-session.sh\n\nSESSION_TYPE=${1:-\"coding\"}\nSESSION_NUMBER=$(($(cat .claude/progress/session-state.json | jq -r '.session_number') + 1))\n\necho \"Starting Session #$SESSION_NUMBER ($SESSION_TYPE)\"\n\n# Initialize session state\ncat > .claude/progress/session-state.json \u003c\u003c EOF\n{\n \"session_number\": $SESSION_NUMBER,\n \"started_at\": \"$(date -Iseconds)\",\n \"agent_type\": \"$SESSION_TYPE\",\n \"status\": \"active\",\n \"heartbeat\": {\n \"last_heartbeat\": \"$(date -Iseconds)\",\n \"interval_seconds\": 300,\n \"missed_heartbeats\": 0\n }\n}\nEOF\n\n# Start heartbeat monitor\nnohup bash .claude/scripts/heartbeat-monitor.sh &>/dev/null &\n\necho \"Session initialized successfully\"\n```\n\n### Heartbeat Monitor\n```bash\n#!/bin/bash\n# .claude/scripts/heartbeat-monitor.sh\n\nwhile true; do\n sleep 300 # 5 minutes\n\n if [ -f \".claude/progress/session-state.json\" ]; then\n # Update heartbeat\n jq '.heartbeat.last_heartbeat = \"'$(date -Iseconds)'\"' \\\n .claude/progress/session-state.json > .tmp && \\\n mv .tmp .claude/progress/session-state.json\n\n # Check if we should still be running\n STATUS=$(cat .claude/progress/session-state.json | jq -r '.status')\n if [ \"$STATUS\" != \"active\" ]; then\n echo \"Session no longer active, stopping heartbeat monitor\"\n exit 0\n fi\n else\n echo \"No session state file found, exiting\"\n exit 1\n fi\ndone\n```\n\n### Session End Script\n```bash\n#!/bin/bash\n# .claude/scripts/end-session.sh\n\n# Stop heartbeat monitor\npkill -f heartbeat-monitor.sh\n\n# Update session state\nEND_TIME=$(date -Iseconds)\nDURATION=$(($(date +%s) - $(date -d \"$(cat .claude/progress/session-state.json | jq -r '.started_at')\" +%s)))\n\ncat .claude/progress/session-state.json | \\\n jq \"{\n .,\n \\\"status\\\": \\\"completed\\\",\n \\\"ended_at\\\": \\\"$END_TIME\\\",\n \\\"duration_minutes\\\": $((DURATION / 60))\n }\" > .tmp && mv .tmp .claude/progress/session-state.json\n\necho \"Session closed successfully\"\n```\n\n## Best Practices\n\n### 1. Session Planning\n- **Clear Objective**: Know exactly which feature you'll implement\n- **Timeboxing**: Keep sessions to 2-4 hours maximum\n- **Dependencies Ready**: Verify prerequisites before starting\n- **Environment Prepared**: Have all tools and services running\n\n### 2. During Session\n- **Single Focus**: Work on only one feature\n- **Regular Updates**: Update progress every 30 minutes\n- **Test Continuously**: Don't wait until the end to test\n- **Document Decisions**: Note important choices and tradeoffs\n\n### 3. Session Completion\n- **Clean State**: Always leave code deployable\n- **Complete Tests**: Ensure all new features are tested\n- **Update Everything**: Feature list, progress log, session state\n- **Proper Commit**: Use conventional commit format\n\n### 4. Between Sessions\n- **Review Progress**: Read claude-progress.txt before starting\n- **Check Blockers**: Verify no features are blocked\n- **Plan Next**: Know what you'll work on next\n- **Sync Team**: Communicate progress to team members\n\n## Session Templates\n\n### Coding Session Template\n```\n## Session N - YYYY-MM-DD\n\n### Objective\n- Feature: [ID] [Feature Name]\n- Estimated: [X hours]\n- Dependencies: [List if any]\n\n### Progress\n- [ ] Read related files (15 min)\n- [ ] Implement core functionality (X hours)\n- [ ] Add/update tests (30 min)\n- [ ] Manual verification (30 min)\n- [ ] Documentation updates (15 min)\n\n### Blockers/Issues\n- [ ] None\n\n### Notes\n-\n```\n\n### Review Session Template\n```\n## Review Session - YYYY-MM-DD\n\n### Completed Since Last Review\n1. [Feature ID] - [Brief description]\n2. [Feature ID] - [Brief description]\n3. ...\n\n### Current Status\n- Total Features: [N]\n- Completed: [X] ([Y]%)\n- In Progress: [A]\n- Blocked: [B]\n\n### Next Priorities\n1. [Feature ID] - [Reason for priority]\n2. [Feature ID] - [Reason for priority]\n3. ...\n\n### Risks and Mitigations\n- Risk: [Description]\n- Mitigation: [Plan]\n\n### Stakeholder Updates\n- [Any important communications]\n```\n\n## Integration with IDE\n\n### VS Code Tasks\n```json\n// .vscode/tasks.json\n{\n \"version\": \"2.0.0\",\n \"tasks\": [\n {\n \"label\": \"Start Coding Session\",\n \"type\": \"shell\",\n \"command\": \".claude/scripts/start-session.sh coding\",\n \"group\": \"build\"\n },\n {\n \"label\": \"End Session\",\n \"type\": \"shell\",\n \"command\": \".claude/scripts/end-session.sh\",\n \"group\": \"build\"\n },\n {\n \"label\": \"Update Progress\",\n \"type\": \"shell\",\n \"command\": \".claude/scripts/update-progress.sh\",\n \"group\": \"build\"\n }\n ]\n}\n```\n\n### IDE Extensions\n- **GitLens**: Visualize feature progress through git history\n- **TODO Highlight**: Spot incomplete features\n- **Session Manager**: Track active coding sessions\n- **Progress Bar**: Customizable project progress indicator\n\n## Monitoring and Analytics\n\n### Session Metrics\nTrack these metrics for continuous improvement:\n\n```javascript\nconst sessionMetrics = {\n averageSessionLength: 185, // minutes\n featuresPerSession: 2.3,\n sessionSuccessRate: 0.95, // % of sessions completing features\n recoveryFrequency: 0.08, // % of sessions needing recovery\n averageRecoveryTime: 45, // minutes\n\n // Trends\n velocityTrend: \"increasing\",\n bugRateTrend: \"decreasing\",\n featureComplexityTrend: \"stable\"\n};\n```\n\n### Automated Alerts\n```bash\n# Set up alerts for:\nif [ $SESSION_LENGTH -gt 240 ]; then\n echo \"⚠️ Long session detected - consider taking a break\"\nfi\n\nif [ $FEATURES_COMPLETED -eq 0 ]; then\n echo \"⚠️ No features completed - check for blockers\"\nfi\n\nif [ git merge-conflicts ]; then\n echo \"⚠️ Merge conflicts detected - resolve before continuing\"\nfi\n```\n\n## Troubleshooting Guide\n\n### Common Session Issues\n\n1. **Can't Find Current Feature**\n - Check session-state.json for last_feature_id\n - Look at git log for recent commits\n - Read claude-progress.txt for latest updates\n\n2. **Tests Keep Failing**\n - Verify development server is running\n - Check test database is populated\n - Review recent code changes for side effects\n\n3. **Git State is Dirty**\n - Commit or stash changes before selecting new feature\n - Use `git stash` if you want to save work temporarily\n - Consider if this should be part of current feature\n\n4. **Dependencies Not Met**\n - Find blocking features and implement them first\n - Update feature dependencies if incorrectly linked\n - Document the blocker in feature notes\n\n### Emergency Procedures\n\n```bash\n# If everything is broken:\ngit checkout main\ngit reset --hard $(git log --oneline -10 | head -1 | awk '{print $1}')\n# Revert to last known good state\n\n# If progress files are corrupted:\ncp .claude/progress/backups/*.json .claude/progress/\n# Restore from recent backup\n\n# If you don't know what to do next:\ncat .claude/progress/feature-list.json | jq '.categories[].features[] | select(.passes == false) | .id, .name'\n# List all pending features\n```\n\nThis comprehensive session workflow ensures that development progresses smoothly, interruptions are recoverable, and project context is preserved across sessions and team members.","content_type":"text/markdown; charset=utf-8","language":"markdown","size":18416,"content_sha256":"abddeac97980df71b49f5058397887340c9215138a481977f93e3d35e0531b60"},{"filename":"references/testing-strategy.md","content":"# Testing Strategy\n\n## Overview\n\nTesting in the Two-Agent Framework is not an afterthought—it's an integral part of the development workflow. The framework requires that every feature includes human-readable test procedures in its \"steps\" array and must be verified before marking as complete. This comprehensive testing strategy ensures reliability, maintains quality, and enables autonomous development across multiple sessions.\n\n## Testing Philosophy\n\n### 1. Test-First Development\n- Every feature includes test steps from creation\n- Tests drive feature implementation\n- Features are not complete until tests pass\n\n### 2. Human-Readable Procedures\n- Test steps written for non-technical users\n- Clear, actionable instructions\n- Verifiable outcomes for each step\n\n### 3. Multi-Level Testing\n- Unit tests for individual components\n- Integration tests for system interactions\n- End-to-end tests for complete user flows\n\n### 4. Browser Automation\n- Puppeteer MCP for UI testing\n- Real browser interactions\n- Cross-browser compatibility\n\n## Testing Pyramid\n\n```\n ▲ E2E Tests (10%)\n / \\\n / ▲ \\ Integration Tests (20%)\n / ▲ ▲ \\\n/ ▲ ▲ ▲ \\ Unit Tests (70%)\n```\n\n### Unit Tests (70%)\n- Fast, isolated tests\n- Test individual functions and components\n- Mock external dependencies\n- Run on every commit\n\n### Integration Tests (20%)\n- Test component interactions\n- API endpoint testing\n- Database operations\n- Service integrations\n\n### End-to-End Tests (10%)\n- Complete user workflows\n- Browser automation\n- Real data scenarios\n- Critical path testing\n\n## Feature Test Format\n\n### The \"steps\" Array Requirement\n\nEvery feature in `feature-list.json` must include a detailed steps array:\n\n```json\n{\n \"id\": \"AUTH-001\",\n \"name\": \"User Registration\",\n \"steps\": [\n \"Navigate to homepage at http://localhost:3000\",\n \"Click 'Sign Up' button in top navigation\",\n \"Verify registration page loads with form fields\",\n \"Enter valid email address in email field\",\n \"Enter password meeting strength requirements\",\n \"Confirm password in repeat field\",\n \"Click 'Create Account' button\",\n \"Check for email verification message\",\n \"Verify confirmation email arrives in inbox\",\n \"Click verification link in email\",\n \"Confirm successful registration with welcome message\"\n ],\n \"passes\": false\n}\n```\n\n### Step Writing Guidelines\n\n1. **Start with Navigation**\n - Always begin with getting to the right page\n - Include full URLs when applicable\n - Specify how to access the feature\n\n2. **Be Specific**\n - Name buttons, links, and fields\n - Include exact text to look for\n - Specify expected locations\n\n3. **Include Verification**\n - What should happen after each action\n - What messages should appear\n - What state should change\n\n4. **Test Edge Cases**\n - Invalid inputs\n - Error conditions\n - Boundary values\n\n5. **Write for Humans**\n - Avoid technical jargon\n - Use simple, clear language\n - Assume no prior knowledge\n\n## Testing Workflow\n\n### 1. Before Implementation\n```bash\n# Verify test environment\nnpm run test:env\n# or\npytest --collect-only\n\n# Start required services\nnpm run dev &\n# or\ndocker-compose up -d\n\n# Verify services are running\ncurl http://localhost:3000/health\n```\n\n### 2. During Implementation\n```bash\n# Run unit tests continuously\nnpm run test:watch\n# or\nptw --runner \"python -m pytest\"\n\n# Run linting\nnpm run lint\n# or\nflake8 src/\n```\n\n### 3. After Implementation\n```bash\n# Run full test suite\nnpm test\n# or\npytest\n\n# Run integration tests\nnpm run test:integration\n# or\npytest tests/integration/\n\n# Run E2E tests\nnpm run test:e2e\n# or\npytest tests/e2e/\n```\n\n### 4. Feature Verification\n```bash\n# Get feature steps\nFEATURE_ID=\"AUTH-001\"\njq -r --arg id \"$FEATURE_ID\" \\\n '.categories[].features[] | select(.id == $id) | .steps[]' \\\n .claude/progress/feature-list.json\n\n# Execute steps manually\necho \"Starting manual verification of $FEATURE_ID...\"\n# [Follow each step manually]\n\n# Mark as passing only after verification\njq --arg id \"$FEATURE_ID\" \\\n '(.categories[].features[] | select(.id == $id)) |= .passes = true' \\\n .claude/progress/feature-list.json > .tmp && \\\n mv .tmp .claude/progress/feature-list.json\n```\n\n## Browser Automation with Puppeteer MCP\n\n### Setup\n\nInstall and configure Puppeteer MCP server:\n\n```bash\n# Install Puppeteer MCP\nnpm install -g @anthropic-ai/puppeteer-mcp-server\n\n# Add to .mcp.json\n{\n \"mcpServers\": {\n \"puppeteer\": {\n \"command\": \"npx\",\n \"args\": [\"@anthropic-ai/puppeteer-mcp-server\"],\n \"env\": {\n \"PUPPETEER_HEADLESS\": \"false\"\n }\n }\n }\n}\n```\n\n### Testing Examples\n\n#### Form Submission Test\n\n```javascript\n// Test user registration form\nawait mcp__playwright__browser_navigate(\"http://localhost:3000/register\");\n\n// Fill registration form\nawait mcp__playwright__browser_fill_form({\n fields: [\n {\n name: \"Email\",\n type: \"textbox\",\n ref: \"input[name='email']\",\n value: \"[email protected]\"\n },\n {\n name: \"Password\",\n type: \"textbox\",\n ref: \"input[name='password']\",\n value: \"SecurePass123!\"\n },\n {\n name: \"Confirm Password\",\n type: \"textbox\",\n ref: \"input[name='confirmPassword']\",\n value: \"SecurePass123!\"\n }\n ]\n});\n\n// Submit form\nawait mcp__playwright__browser_click({\n element: \"Create Account button\",\n ref: \"button[type='submit']\"\n});\n\n// Verify success\nawait mcp__playwright__browser_wait_for({\n text: \"Account created successfully\",\n textGone: \"Create Account\"\n});\n```\n\n#### Navigation Test\n\n```javascript\n// Test navigation flow\nawait mcp__playwright__browser_navigate(\"http://localhost:3000\");\n\n// Click login link\nawait mcp__playwright__browser_click({\n element: \"Login link\",\n ref: \"a[href='/login']\"\n});\n\n// Verify page title\nconst title = await mcp__playwright__browser_evaluate({\n function: \"() => document.title\"\n});\n\nconsole.assert(title.includes(\"Login\"), \"Page title should include 'Login'\");\n```\n\n#### API Response Test\n\n```javascript\n// Test API endpoint from browser\nconst response = await mcp__playwright__browser_evaluate({\n function: \"() => fetch('/api/users').then(r => r.json())\"\n});\n\nconsole.assert(response.length > 0, \"API should return users\");\n```\n\n## Test Organization\n\n### Directory Structure\n\n```\ntests/\n├── unit/ # Unit tests\n│ ├── components/ # Component tests\n│ │ ├── Button.test.js\n│ │ └── Form.test.js\n│ ├── services/ # Service tests\n│ │ ├── authService.test.js\n│ │ └── apiService.test.js\n│ └── utils/ # Utility tests\n│ ├── validators.test.js\n│ └── helpers.test.js\n│\n├── integration/ # Integration tests\n│ ├── api/ # API tests\n│ │ ├── auth.test.js\n│ │ └── users.test.js\n│ ├── database/ # Database tests\n│ │ ├── migrations.test.js\n│ │ └── models.test.js\n│ └── workflows/ # Workflow tests\n│ ├── registration.test.js\n│ └── checkout.test.js\n│\n├── e2e/ # End-to-end tests\n│ ├── auth-flow.test.js\n│ ├── shopping-cart.test.js\n│ └── admin-panel.test.js\n│\n├── fixtures/ # Test data\n│ ├── users.json\n│ ├── products.json\n│ └── orders.json\n│\n├── helpers/ # Test utilities\n│ ├── setup.js\n│ ├── teardown.js\n│ └── utils.js\n│\n└── config/ # Test configuration\n ├── jest.config.js\n ├── cucumber.js\n └── playwright.config.js\n```\n\n### Test Naming Conventions\n\n- **Unit tests**: `[ComponentName].test.js`\n- **Integration tests**: `[feature].integration.test.js`\n- **E2E tests**: `[user-flow].e2e.test.js`\n- **Fixtures**: `[entity].json`\n- **Helpers**: `[purpose].helper.js`\n\n### Test File Template\n\n```javascript\n// tests/unit/components/Button.test.js\nimport { render, fireEvent, screen } from '@testing-library/react';\nimport { Button } from '../../../src/components/Button';\n\ndescribe('Button Component', () => {\n // Test setup\n beforeEach(() => {\n // Reset mocks, clear DOM, etc.\n });\n\n // Basic functionality tests\n describe('Rendering', () => {\n it('renders with correct text', () => {\n render(\u003cButton>Click me\u003c/Button>);\n expect(screen.getByText('Click me')).toBeInTheDocument();\n });\n\n it('applies correct className', () => {\n render(\u003cButton className=\"custom-class\">Button\u003c/Button>);\n const button = screen.getByRole('button');\n expect(button).toHaveClass('custom-class');\n });\n });\n\n // Interaction tests\n describe('Interactions', () => {\n it('calls onClick when clicked', () => {\n const handleClick = jest.fn();\n render(\u003cButton onClick={handleClick}>Button\u003c/Button>);\n\n fireEvent.click(screen.getByRole('button'));\n expect(handleClick).toHaveBeenCalledTimes(1);\n });\n\n it('does not call onClick when disabled', () => {\n const handleClick = jest.fn();\n render(\u003cButton onClick={handleClick} disabled>Button\u003c/Button>);\n\n fireEvent.click(screen.getByRole('button'));\n expect(handleClick).not.toHaveBeenCalled();\n });\n });\n\n // Edge case tests\n describe('Edge Cases', () => {\n it('handles missing onClick gracefully', () => {\n expect(() => {\n render(\u003cButton>Button\u003c/Button>);\n fireEvent.click(screen.getByRole('button'));\n }).not.toThrow();\n });\n\n it('handles empty children', () => {\n render(\u003cButton>\u003c/Button>);\n expect(screen.getByRole('button')).toBeInTheDocument();\n });\n });\n});\n```\n\n## Test Data Management\n\n### Fixtures\n\n```json\n// tests/fixtures/users.json\n{\n \"validUser\": {\n \"id\": 1,\n \"email\": \"[email protected]\",\n \"password\": \"SecurePass123!\",\n \"name\": \"Test User\"\n },\n \"invalidUser\": {\n \"email\": \"invalid-email\",\n \"password\": \"123\"\n }\n}\n```\n\n### Factory Pattern\n\n```javascript\n// tests/helpers/factories.js\nimport { faker } from '@faker-js/faker';\n\nexport const createUser = (overrides = {}) => ({\n id: faker.datatype.number(),\n email: faker.internet.email(),\n name: faker.name.fullName(),\n password: faker.internet.password(),\n createdAt: faker.date.past(),\n ...overrides\n});\n\nexport const createProduct = (overrides = {}) => ({\n id: faker.datatype.number(),\n name: faker.commerce.productName(),\n price: parseFloat(faker.commerce.price()),\n description: faker.lorem.paragraph(),\n ...overrides\n});\n```\n\n### Database Seeding\n\n```javascript\n// tests/helpers/database.js\nimport { PrismaClient } from '@prisma';\nimport { createUser, createProduct } from './factories';\n\nconst prisma = new PrismaClient();\n\nexport async function seedDatabase() {\n // Clean up\n await prisma.user.deleteMany();\n await prisma.product.deleteMany();\n\n // Seed data\n const users = Array.from({ length: 10 }, () => createUser());\n const products = Array.from({ length: 50 }, () => createProduct());\n\n await prisma.user.createMany({ data: users });\n await prisma.product.createMany({ data: products });\n\n return { users, products };\n}\n\nexport async function cleanupDatabase() {\n await prisma.$disconnect();\n}\n```\n\n## Continuous Integration Testing\n\n### GitHub Actions\n\n```yaml\n# .github/workflows/test.yml\nname: Tests\n\non:\n push:\n branches: [ main, develop ]\n pull_request:\n branches: [ main ]\n\njobs:\n test:\n runs-on: ubuntu-latest\n\n strategy:\n matrix:\n node-version: [16.x, 18.x, 20.x]\n\n services:\n postgres:\n image: postgres:14\n env:\n POSTGRES_PASSWORD: postgres\n options: >-\n --health-cmd pg_isready\n --health-interval 10s\n --health-timeout 5s\n --health-retries 5\n\n steps:\n - uses: actions/checkout@v3\n\n - name: Setup Node.js\n uses: actions/setup-node@v3\n with:\n node-version: ${{ matrix.node-version }}\n cache: 'npm'\n\n - name: Install dependencies\n run: npm ci\n\n - name: Run linting\n run: npm run lint\n\n - name: Run unit tests\n run: npm run test:unit\n\n - name: Run integration tests\n run: npm run test:integration\n env:\n DATABASE_URL: postgresql://postgres:postgres@localhost:5432/test\n\n - name: Run E2E tests\n run: npm run test:e2e\n env:\n CYPRESS_baseUrl: http://localhost:3000\n\n - name: Upload coverage\n uses: codecov/codecov-action@v3\n```\n\n### Test Coverage\n\n```javascript\n// jest.config.js\nmodule.exports = {\n collectCoverage: true,\n coverageDirectory: 'coverage',\n coverageReporters: ['text', 'lcov', 'html'],\n coverageThreshold: {\n global: {\n branches: 80,\n functions: 80,\n lines: 80,\n statements: 80\n }\n },\n collectCoverageFrom: [\n 'src/**/*.{js,jsx,ts,tsx}',\n '!src/**/*.d.ts',\n '!src/index.js'\n ]\n};\n```\n\n## Performance Testing\n\n### Load Testing\n\n```javascript\n// tests/performance/load-test.js\nimport http from 'k6/http';\nimport { check, sleep } from 'k6';\n\nexport let options = {\n stages: [\n { duration: '2m', target: 100 },\n { duration: '5m', target: 100 },\n { duration: '2m', target: 200 },\n { duration: '5m', target: 200 },\n { duration: '2m', target: 0 },\n ],\n};\n\nexport default function () {\n let response = http.get('http://localhost:3000/api/products');\n check(response, {\n 'status is 200': (r) => r.status === 200,\n 'response time \u003c 500ms': (r) => r.timings.duration \u003c 500,\n });\n sleep(1);\n}\n```\n\n### Visual Regression Testing\n\n```javascript\n// tests/visual/visual.test.js\nimport { test, expect } from '@playwright/test';\n\ntest('homepage visual regression', async ({ page }) => {\n await page.goto('http://localhost:3000');\n\n await expect(page).toHaveScreenshot('homepage.png');\n});\n\ntest('product page visual regression', async ({ page }) => {\n await page.goto('http://localhost:3000/products/1');\n\n await expect(page).toHaveScreenshot('product-page.png');\n});\n```\n\n## Testing Best Practices\n\n### 1. Test Structure\n- Use AAA pattern: Arrange, Act, Assert\n- Keep tests focused and simple\n- One assertion per test when possible\n- Use descriptive test names\n\n### 2. Test Independence\n- Tests should not depend on each other\n- Clean up after each test\n- Use fresh data for each test\n- Avoid shared state\n\n### 3. Mocking and Stubbing\n- Mock external dependencies\n- Use factory patterns for test data\n- Keep mocks close to implementation\n- Don't over-mock\n\n### 4. Flaky Tests\n- Identify and fix flaky tests\n- Use proper waits and retries\n- Avoid time-based assertions\n- Isolate async operations\n\n### 5. Test Documentation\n- Document complex test scenarios\n- Explain business logic being tested\n- Include setup instructions\n- Note any limitations\n\n## Testing Checklist\n\n### Before Marking Feature Complete\n\n- [ ] All unit tests pass\n- [ ] Integration tests pass\n- [ ] Manual steps verified\n- [ ] E2E tests pass\n- [ ] Code coverage > 80%\n- [ ] Performance tests pass\n- [ ] Accessibility tests pass\n- [ ] Visual regression tests pass\n- [ ] Documentation updated\n\n### Continuous Testing\n\n- [ ] Tests run on every commit\n- [ ] Tests run on every PR\n- [ ] Coverage reports generated\n- [ ] Flaky test alerts configured\n- [ ] Performance baselines tracked\n\n## Test Automation Scripts\n\n### Pre-commit Hook\n\n```bash\n#!/bin/sh\n# .git/hooks/pre-commit\n\n# Run unit tests\nnpm run test:unit\nif [ $? -ne 0 ]; then\n echo \"Unit tests failed. Please fix before committing.\"\n exit 1\nfi\n\n# Run linting\nnpm run lint\nif [ $? -ne 0 ]; then\n echo \"Linting errors found. Please fix before committing.\"\n exit 1\nfi\n\n# Type checking\nnpm run type-check\nif [ $? -ne 0 ]; then\n echo \"Type errors found. Please fix before committing.\"\n exit 1\nfi\n\necho \"All pre-commit checks passed!\"\nexit 0\n```\n\n### Test Runner Script\n\n```bash\n#!/bin/bash\n# scripts/test-all.sh\n\necho \"Running full test suite...\"\n\n# Kill any existing processes\npkill -f \"node.*server\" || true\npkill -f \"npm.*dev\" || true\n\n# Start services\necho \"Starting services...\"\nnpm run dev &\nSERVER_PID=$!\n\n# Wait for server\necho \"Waiting for server...\"\nuntil curl -s http://localhost:3000 > /dev/null; do\n sleep 2\ndone\n\n# Run tests\necho \"Running tests...\"\nnpm run test:unit\nnpm run test:integration\nnpm run test:e2e\n\n# Cleanup\nkill $SERVER_PID\n\necho \"Test suite complete!\"\n```\n\nThis comprehensive testing strategy ensures that every feature is thoroughly verified before being marked as complete, maintaining high code quality and reliability throughout the development process.","content_type":"text/markdown; charset=utf-8","language":"markdown","size":16684,"content_sha256":"38d190089c1eb19984f8d11c4be3e30cb9832056a8fa51648b02579307116845"},{"filename":"references/two-agent-framework-overview.md","content":"# Two-Agent Framework Overview\n\n## Purpose\n\nThe Two-Agent Framework implements a revolutionary approach to software development based on \"Effective Harnesses for Long-Running Agents\". This framework enables building complete applications over multiple sessions through a specialized division of labor between an **Initializer Agent** (project planning and breakdown) and a **Coding Agent** (incremental implementation).\n\n## Philosophy\n\nTraditional software development faces several challenges:\n- Complex projects are difficult to plan comprehensively\n- Developers lose context between sessions\n- Progress is hard to track over long periods\n- Code quality degrades without strict standards\n- Testing is often an afterthought\n\nThe Two-Agent Framework solves these by:\n1. **Specialized Roles**: Each agent focuses on what they do best\n2. **Incremental Progress**: One feature at a time ensures clean, tested code\n3. **Comprehensive Planning**: 200+ feature breakdowns leave no detail to chance\n4. **Session Recovery**: Full state tracking enables seamless continuation\n5. **Quality Enforcement**: Hooks and standards prevent common pitfalls\n\n## When to Use This Framework\n\n### Ideal For:\n- **Complex applications** (50+ features)\n- **Long-term projects** (weeks to months of development)\n- **Team environments** where multiple developers work on same codebase\n- **High-quality requirements** where bugs are unacceptable\n- **Multi-session work** where context preservation is critical\n\n### Project Types:\n- **Web Applications**: React, Vue, Angular, or custom frameworks\n- **API Services**: RESTful APIs, GraphQL services, microservices\n- **Mobile Applications**: iOS, Android, React Native, Flutter\n- **Desktop Applications**: Electron, native desktop apps\n- **CLI Tools**: Command-line interfaces and developer tools\n- **Infrastructure**: DevOps tools, deployment systems\n- **Data Platforms**: Analytics platforms, data pipelines\n\n## Architecture Overview\n\n### Agent Roles\n\n#### Initializer Agent (Planner)\n- **Primary Responsibility**: Break down complex projects into granular features\n- **Activities**:\n - Project analysis and requirement gathering\n - Feature architecture and hierarchy design\n - Creating comprehensive feature lists (200+ features for complex apps)\n - Environment setup and tooling configuration\n - Initial git repository setup\n - Progress tracking system initialization\n\n#### Coding Agent (Implementer)\n- **Primary Responsibility**: Implement features incrementally with quality assurance\n- **Activities**:\n - Single feature implementation per session\n - Reading progress from previous sessions\n - Testing functionality before marking complete\n - Maintaining clean git state\n - Updating progress tracking\n - Ensuring code quality standards\n\n#### Opus (Orchestrator)\n- **Primary Responsibility**: Coordinate between agents and make high-level decisions\n- **Activities**:\n - Delegating to appropriate agent\n - Reviewing progress and making strategic decisions\n - Handling escalations and exceptional cases\n - Ensuring framework compliance\n\n### Communication Flow\n\n```mermaid\ngraph LR\n A[User Request] --> B{Is it a new project or\u003cbr/>complex breakdown?}\n B -->|Yes| C[Initializer Agent]\n B -->|No| D[Coding Agent]\n\n C --> E[Feature List Created]\n E --> F{Git Initial Commit}\n F --> G[Handoff to Coding Agent]\n\n D --> H[Read Progress Files]\n H --> I[Select Next Feature]\n I --> J[Implement Feature]\n J --> K[Test & Verify]\n K --> L[Update Progress]\n L --> M[Commit Changes]\n\n G --> H\n M --> N{More Features?}\n N -->|Yes| H\n N -->|No| O[Project Complete]\n```\n\n## Success Criteria\n\n### Development Metrics:\n- **Feature Completion Rate**: >95% of planned features\n- **Code Quality**: Zero critical bugs in main branch\n- **Test Coverage**: All features have automated tests\n- **Session Efficiency**: Average 2-4 hours per feature\n- **Clean State**: Environment always ready for next feature\n\n### Business Outcomes:\n- **Faster Time-to-Market**: Parallel planning and implementation\n- **Higher Quality**: Comprehensive testing prevents bugs\n- **Better Team Collaboration**: Clear progress visibility\n- **Risk Reduction**: Incremental development prevents failures\n- **Knowledge Retention**: Detailed documentation captures decisions\n\n## Comparison with Traditional Approaches\n\n### Traditional Development:\n```mermaid\ngraph TD\n A[Start Project] --> B[Some Planning]\n B --> C[Start Coding]\n C --> D[Add Features Ad-Hoc]\n D --> E[Bug Fixing]\n E --> F[Add Tests Later]\n F --> G[Deploy]\n G --> H[Maintain]\n```\n\n### Two-Agent Framework:\n```mermaid\ngraph TD\n A[Start Project] --> B[Comprehensive Planning]\n B --> C[Feature List Creation]\n C --> D[Environment Setup]\n D --> E[Git Initial Commit]\n E --> F[Feature 1 Implementation]\n F --> G[Feature 1 Testing]\n G --> H[Feature 1 Commit]\n H --> I[Feature 2 Implementation]\n I --> J[Feature 2 Testing]\n J --> K[Feature 2 Commit]\n K --> L[Continue...]\n```\n\n## Key Benefits\n\n### 1. **Predictable Planning**\n- 200+ feature breakdowns ensure nothing is missed\n- Hierarchical structure provides clear implementation path\n- Dependencies identified and managed upfront\n\n### 2. **Consistent Quality**\n- Every feature tested before marking complete\n- Clean state requirements prevent broken code\n- Standardized commit messages track changes\n\n### 3. **Session Recovery**\n- Full progress state preserved across sessions\n- Agent handoffs maintain context\n- Git history provides complete audit trail\n\n### 4. **Team Efficiency**\n- Multiple developers can work in parallel\n- Clear visibility into each other's progress\n- No duplicate work through comprehensive planning\n\n### 5. **Risk Mitigation**\n- Incremental development limits blast radius\n- Early testing catches issues quickly\n- Git commits provide rollback capability\n\n## Real-World Example\n\n### Robo-Trader Project (Autonomous Paper Trading System):\n- **52 features** across 8 categories\n- **77% completed** (42/52 features done)\n- **Zero critical bugs** in production\n- **Full test coverage** for implemented features\n- **Multiple developers** working efficiently\n\n### Results:\n- Autonomous system running continuously\n- Zero downtime during development\n- High confidence in code quality\n- Clear roadmap for remaining features\n\n## Getting Started\n\nTo begin using the Two-Agent Framework:\n\n1. **Read the Implementation Guide** for setup instructions\n2. **Initialize a new project** using the initializer-agent\n3. **Review the feature list** to understand the scope\n4. **Start implementing** with the coding-agent\n5. **Track progress** through the provided dashboards\n\n## Next Steps\n\nContinue reading:\n- [Implementation Guide](implementation-guide.md) - Step-by-step setup\n- [Agent Specifications](initializer-agent-spec.md) - Detailed agent workflows\n- [Feature Tracking System](feature-tracking-system.md) - Progress management\n- [Session Workflow](session-workflow.md) - Session management\n\n## Resources\n\n- [Original Article](https://www.anthropic.com/engineering/effective-harnesses-for-long-running-agents)\n- [Claude Code Documentation](https://docs.claude.com)\n- [Community Examples](examples/) - Real-world implementations\n- [Troubleshooting Guide](troubleshooting.md) - Common issues and solutions","content_type":"text/markdown; charset=utf-8","language":"markdown","size":7316,"content_sha256":"505d3ad030e71c44fe975d0bb3504ab275610d555572b46078f55f293e8ded50"},{"filename":"scripts/setup-two-agent-system.sh","content":"#!/bin/bash\n# Two-Agent Harness System Setup Script\n# Installs the complete two-agent development architecture\n#\n# Usage: bash setup-two-agent-system.sh [--force]\n# --force: Overwrite existing files without prompting\n\nset -e\n\n# Configuration\nCLAUDE_DIR=\"$HOME/.claude\"\nSKILL_DIR=\"$CLAUDE_DIR/skills/two-agent-harness\"\nAGENTS_DIR=\"$CLAUDE_DIR/agents\"\nHOOKS_DIR=\"$CLAUDE_DIR/hooks\"\nREFERENCE_DIR=\"$CLAUDE_DIR/REFRENCE/TWO-AGENT-HARNESS\"\nSETTINGS_FILE=\"$CLAUDE_DIR/settings.json\"\nCLAUDE_MD=\"$CLAUDE_DIR/CLAUDE.md\"\n\n# Colors\nRED='\\033[0;31m'\nGREEN='\\033[0;32m'\nYELLOW='\\033[1;33m'\nBLUE='\\033[0;34m'\nNC='\\033[0m'\n\n# Parse arguments\nFORCE=false\nif [ \"$1\" = \"--force\" ]; then\n FORCE=true\nfi\n\n# Helper functions\nprint_header() {\n echo \"\"\n echo -e \"${BLUE}══════════════════════════════════════════════════════════════${NC}\"\n echo -e \"${BLUE} $1${NC}\"\n echo -e \"${BLUE}══════════════════════════════════════════════════════════════${NC}\"\n}\n\nprint_status() {\n echo -e \"${GREEN}✓${NC} $1\"\n}\n\nprint_warning() {\n echo -e \"${YELLOW}⚠${NC} $1\"\n}\n\nprint_error() {\n echo -e \"${RED}✗${NC} $1\"\n}\n\nprint_info() {\n echo -e \"${BLUE}→${NC} $1\"\n}\n\n# Check if file exists and handle accordingly\ncopy_file() {\n local src=\"$1\"\n local dest=\"$2\"\n local name=\"$3\"\n\n if [ -f \"$dest\" ] && [ \"$FORCE\" != \"true\" ]; then\n print_warning \"$name already exists, skipping (use --force to overwrite)\"\n else\n cp \"$src\" \"$dest\"\n print_status \"Installed $name\"\n fi\n}\n\n# Main installation\nmain() {\n print_header \"Two-Agent Harness System Setup\"\n echo \"\"\n echo \"This script will install:\"\n echo \" • 2 agent definitions (initializer-agent, coding-agent)\"\n echo \" • 5 enforcement hooks\"\n echo \" • 9 reference documentation files\"\n echo \" • CLAUDE.md configuration\"\n echo \"\"\n\n # Verify skill directory exists\n if [ ! -d \"$SKILL_DIR\" ]; then\n print_error \"Skill directory not found: $SKILL_DIR\"\n echo \"Please ensure the skill is properly installed first.\"\n exit 1\n fi\n\n # Step 1: Create directories\n print_header \"Step 1: Creating Directories\"\n\n mkdir -p \"$AGENTS_DIR\"\n print_status \"Created $AGENTS_DIR\"\n\n mkdir -p \"$HOOKS_DIR\"\n print_status \"Created $HOOKS_DIR\"\n\n mkdir -p \"$REFERENCE_DIR\"\n print_status \"Created $REFERENCE_DIR\"\n\n # Step 2: Install agents\n print_header \"Step 2: Installing Agents\"\n\n copy_file \"$SKILL_DIR/assets/agents/initializer-agent.md\" \"$AGENTS_DIR/initializer-agent.md\" \"initializer-agent\"\n copy_file \"$SKILL_DIR/assets/agents/coding-agent.md\" \"$AGENTS_DIR/coding-agent.md\" \"coding-agent\"\n\n # Step 3: Install hooks\n print_header \"Step 3: Installing Hooks\"\n\n for hook in pre-tool-guard.sh post-tool-guard.sh session-progress-check.sh verify-coding-agent.sh session-end.sh; do\n if [ -f \"$SKILL_DIR/assets/hooks/$hook\" ]; then\n copy_file \"$SKILL_DIR/assets/hooks/$hook\" \"$HOOKS_DIR/$hook\" \"$hook\"\n chmod +x \"$HOOKS_DIR/$hook\"\n else\n print_warning \"Hook not found: $hook\"\n fi\n done\n\n # Step 4: Configure settings.json with hooks\n print_header \"Step 4: Configuring Hook Settings\"\n\n if [ -f \"$SETTINGS_FILE\" ]; then\n # Check if hooks are already configured\n if grep -q \"pre-tool-guard\" \"$SETTINGS_FILE\" 2>/dev/null; then\n print_warning \"Hooks already configured in settings.json\"\n else\n print_info \"Adding hook configurations to settings.json...\"\n # Use Python to safely modify JSON\n python3 \u003c\u003c 'EOF'\nimport json\nimport os\n\nsettings_file = os.path.expanduser(\"~/.claude/settings.json\")\nhooks_dir = os.path.expanduser(\"~/.claude/hooks\")\n\ntry:\n with open(settings_file, 'r') as f:\n settings = json.load(f)\nexcept:\n settings = {}\n\n# Ensure hooks array exists\nif 'hooks' not in settings:\n settings['hooks'] = []\n\n# Define hooks to add\nnew_hooks = [\n {\n \"event\": \"PreToolUse\",\n \"command\": f\"{hooks_dir}/pre-tool-guard.sh\",\n \"timeout\": 5000\n },\n {\n \"event\": \"PostToolUse\",\n \"command\": f\"{hooks_dir}/post-tool-guard.sh\",\n \"timeout\": 5000\n },\n {\n \"event\": \"SessionStart\",\n \"command\": f\"{hooks_dir}/session-progress-check.sh\",\n \"timeout\": 5000\n },\n {\n \"event\": \"SessionEnd\",\n \"command\": f\"{hooks_dir}/session-end.sh\",\n \"timeout\": 5000\n }\n]\n\n# Add hooks if not already present\nfor new_hook in new_hooks:\n exists = any(h.get('command', '').endswith(os.path.basename(new_hook['command']))\n for h in settings['hooks'])\n if not exists:\n settings['hooks'].append(new_hook)\n print(f\" Added {os.path.basename(new_hook['command'])}\")\n\nwith open(settings_file, 'w') as f:\n json.dump(settings, f, indent=2)\n\nprint(\" Hook configuration complete\")\nEOF\n fi\n else\n print_info \"Creating new settings.json with hook configurations...\"\n cat > \"$SETTINGS_FILE\" \u003c\u003c EOF\n{\n \"hooks\": [\n {\n \"event\": \"PreToolUse\",\n \"command\": \"$HOOKS_DIR/pre-tool-guard.sh\",\n \"timeout\": 5000\n },\n {\n \"event\": \"PostToolUse\",\n \"command\": \"$HOOKS_DIR/post-tool-guard.sh\",\n \"timeout\": 5000\n },\n {\n \"event\": \"SessionStart\",\n \"command\": \"$HOOKS_DIR/session-progress-check.sh\",\n \"timeout\": 5000\n },\n {\n \"event\": \"SessionEnd\",\n \"command\": \"$HOOKS_DIR/session-end.sh\",\n \"timeout\": 5000\n }\n ]\n}\nEOF\n print_status \"Created settings.json with hook configurations\"\n fi\n\n # Step 5: Install reference documentation\n print_header \"Step 5: Installing Reference Documentation\"\n\n if [ -d \"$SKILL_DIR/references\" ]; then\n for ref in \"$SKILL_DIR/references\"/*.md; do\n if [ -f \"$ref\" ]; then\n filename=$(basename \"$ref\")\n copy_file \"$ref\" \"$REFERENCE_DIR/$filename\" \"$filename\"\n fi\n done\n else\n print_warning \"Reference directory not found\"\n fi\n\n # Step 6: Update CLAUDE.md\n print_header \"Step 6: Configuring CLAUDE.md\"\n\n SNIPPET_FILE=\"$SKILL_DIR/assets/claude-md-snippet.md\"\n\n if [ -f \"$CLAUDE_MD\" ]; then\n # Check if already configured\n if grep -q \"Two-Agent System\" \"$CLAUDE_MD\" 2>/dev/null; then\n print_warning \"Two-agent configuration already exists in CLAUDE.md\"\n else\n print_info \"Appending two-agent configuration to CLAUDE.md...\"\n echo \"\" >> \"$CLAUDE_MD\"\n cat \"$SNIPPET_FILE\" >> \"$CLAUDE_MD\"\n print_status \"Updated CLAUDE.md with two-agent configuration\"\n fi\n else\n print_info \"Creating CLAUDE.md with two-agent configuration...\"\n cat \"$SNIPPET_FILE\" > \"$CLAUDE_MD\"\n print_status \"Created CLAUDE.md\"\n fi\n\n # Step 7: Validate installation\n print_header \"Step 7: Validating Installation\"\n\n ERRORS=0\n\n # Check agents\n if [ -f \"$AGENTS_DIR/initializer-agent.md\" ]; then\n print_status \"initializer-agent installed\"\n else\n print_error \"initializer-agent NOT found\"\n ERRORS=$((ERRORS + 1))\n fi\n\n if [ -f \"$AGENTS_DIR/coding-agent.md\" ]; then\n print_status \"coding-agent installed\"\n else\n print_error \"coding-agent NOT found\"\n ERRORS=$((ERRORS + 1))\n fi\n\n # Check hooks\n for hook in pre-tool-guard.sh post-tool-guard.sh session-progress-check.sh session-end.sh; do\n if [ -x \"$HOOKS_DIR/$hook\" ]; then\n print_status \"$hook installed and executable\"\n else\n print_error \"$hook NOT found or not executable\"\n ERRORS=$((ERRORS + 1))\n fi\n done\n\n # Check CLAUDE.md\n if grep -q \"Two-Agent System\" \"$CLAUDE_MD\" 2>/dev/null; then\n print_status \"CLAUDE.md configured\"\n else\n print_error \"CLAUDE.md configuration missing\"\n ERRORS=$((ERRORS + 1))\n fi\n\n # Final status\n print_header \"Installation Complete\"\n\n if [ $ERRORS -eq 0 ]; then\n echo -e \"${GREEN}\"\n echo \" ╔══════════════════════════════════════════════════════════╗\"\n echo \" ║ Two-Agent Harness System Successfully Installed! ║\"\n echo \" ╚══════════════════════════════════════════════════════════╝\"\n echo -e \"${NC}\"\n echo \"\"\n echo \"Next steps:\"\n echo \" 1. Restart Claude Code for hooks to take effect\"\n echo \" 2. Start a new project: 'Initialize this project with feature breakdown'\"\n echo \" 3. The system will delegate to initializer-agent and coding-agent\"\n echo \"\"\n echo \"Documentation: ~/.claude/REFRENCE/TWO-AGENT-HARNESS/\"\n echo \"\"\n else\n echo -e \"${RED}\"\n echo \" Installation completed with $ERRORS error(s)\"\n echo \" Please review the errors above and fix manually\"\n echo -e \"${NC}\"\n exit 1\n fi\n}\n\nmain \"$@\"\n","content_type":"application/x-sh; charset=utf-8","language":"bash","size":9389,"content_sha256":"c95b6de715f6c678d0a78382588139c70c78f816af9931282fd068169d4f62be"}],"content_json":{"type":"doc","content":[{"type":"heading","attrs":{"level":1},"content":[{"text":"Two-Agent Harness System Setup","type":"text"}]},{"type":"paragraph","content":[{"text":"This skill installs a complete two-agent development architecture that separates planning from implementation. Based on the research paper \"Effective Harnesses for Long-Running Agents\", it enables Claude Code to handle complex, multi-session projects with proper progress tracking and state recovery.","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"System Overview","type":"text"}]},{"type":"paragraph","content":[{"text":"The two-agent harness creates a workflow where:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Opus","type":"text","marks":[{"type":"strong"}]},{"text":" (you) orchestrates and delegates - never implements directly","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Initializer Agent","type":"text","marks":[{"type":"strong"}]},{"text":" (sonnet) breaks down projects into 200+ trackable features","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Coding Agent","type":"text","marks":[{"type":"strong"}]},{"text":" (sonnet) implements features one at a time with quality assurance","type":"text"}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Auto-Setup Process","type":"text"}]},{"type":"paragraph","content":[{"text":"To set up the complete two-agent system, execute the setup script:","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"bash ~/.claude/skills/two-agent-harness/scripts/setup-two-agent-system.sh","type":"text"}]},{"type":"paragraph","content":[{"text":"This script will automatically:","type":"text"}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Create agent definitions in ","type":"text"},{"text":"~/.claude/agents/","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Install enforcement hooks in ","type":"text"},{"text":"~/.claude/hooks/","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Add reference documentation to ","type":"text"},{"text":"~/.claude/REFRENCE/TWO-AGENT-HARNESS/","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Configure ","type":"text"},{"text":"~/.claude/CLAUDE.md","type":"text","marks":[{"type":"code_inline"}]},{"text":" with delegation instructions","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Validate the installation","type":"text"}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"What Gets Installed","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Agents (","type":"text"},{"text":"~/.claude/agents/","type":"text","marks":[{"type":"code_inline"}]},{"text":")","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Agent","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Model","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Purpose","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"initializer-agent","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"sonnet","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Breaks down complex tasks into feature-list.json with 200+ features","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"coding-agent","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"sonnet","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Implements features systematically, one at a time","type":"text"}]}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Hooks (","type":"text"},{"text":"~/.claude/hooks/","type":"text","marks":[{"type":"code_inline"}]},{"text":")","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Hook","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Event","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Action","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"pre-tool-guard.sh","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"PreToolUse","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Blocks Opus from editing src/ files, updates heartbeat","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"post-tool-guard.sh","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"PostToolUse","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Reminds about progress updates after code changes","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"session-progress-check.sh","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"SessionStart","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Detects pending features and abnormal exits","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"verify-coding-agent.sh","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"SubagentStop","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Verifies coding-agent updated progress files","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"session-end.sh","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"SessionEnd","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Marks session complete for recovery detection","type":"text"}]}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Reference Documentation (","type":"text"},{"text":"~/.claude/REFRENCE/TWO-AGENT-HARNESS/","type":"text","marks":[{"type":"code_inline"}]},{"text":")","type":"text"}]},{"type":"paragraph","content":[{"text":"Nine comprehensive guides covering:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Framework overview and philosophy","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Agent specifications","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Feature tracking system","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Hook system","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Git integration","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Session workflow","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Testing strategy","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"File structure","type":"text"}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Post-Installation Usage","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Starting a New Project","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":""},"content":[{"text":"User: \"Initialize this as a new project with comprehensive feature breakdown\"\nOpus: [Invokes initializer-agent via Task tool]\nResult: Creates feature-list.json with 200+ features, init.sh, and progress tracking","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Implementing Features","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":""},"content":[{"text":"User: \"Implement the next feature\"\nOpus: [Invokes coding-agent via Task tool]\nResult: Implements one feature, updates progress, commits changes","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Delegation Rules","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Situation","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Agent to Use","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"New project, complex breakdown","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"initializer-agent","type":"text","marks":[{"type":"code_inline"}]}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Implement feature from feature-list","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"coding-agent","type":"text","marks":[{"type":"code_inline"}]}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Need codebase understanding","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Explore","type":"text","marks":[{"type":"code_inline"}]},{"text":" (built-in)","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Quick fix (\u003c5 min), explicit request","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Do directly (say \"quick fix\" or \"direct edit\")","type":"text"}]}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Bypass Keywords","type":"text"}]},{"type":"paragraph","content":[{"text":"When you need to bypass the enforcement hooks, include these keywords in your prompt:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"\"quick fix\"","type":"text","marks":[{"type":"code_inline"}]},{"text":" - Single line change","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"\"direct edit\"","type":"text","marks":[{"type":"code_inline"}]},{"text":" - User explicitly requested direct editing","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"\"no progress\"","type":"text","marks":[{"type":"code_inline"}]},{"text":" - No feature-list.json exists yet","type":"text"}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Project Progress Files","type":"text"}]},{"type":"paragraph","content":[{"text":"When a project is initialized, these files are created in ","type":"text"},{"text":".claude/progress/","type":"text","marks":[{"type":"code_inline"}]},{"text":":","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"feature-list.json","type":"text","marks":[{"type":"code_inline"}]},{"text":" - Comprehensive feature breakdown with status tracking","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"session-state.json","type":"text","marks":[{"type":"code_inline"}]},{"text":" - Session state for recovery detection","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"claude-progress.txt","type":"text","marks":[{"type":"code_inline"}]},{"text":" - Human-readable progress log","type":"text"}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Templates","type":"text"}]},{"type":"paragraph","content":[{"text":"The skill includes templates for new projects in ","type":"text"},{"text":"assets/templates/","type":"text","marks":[{"type":"code_inline"}]},{"text":":","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"feature-list-template.json","type":"text","marks":[{"type":"code_inline"}]},{"text":" - Starting point for feature breakdown","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"session-state-template.json","type":"text","marks":[{"type":"code_inline"}]},{"text":" - Initial session state","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"init-template.sh","type":"text","marks":[{"type":"code_inline"}]},{"text":" - Environment setup script","type":"text"}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Troubleshooting","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Agents Not Appearing in Task Tool","type":"text"}]},{"type":"paragraph","content":[{"text":"Verify agents are in ","type":"text"},{"text":"~/.claude/agents/","type":"text","marks":[{"type":"code_inline"}]},{"text":":","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"ls -la ~/.claude/agents/","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Hooks Not Triggering","type":"text"}]},{"type":"paragraph","content":[{"text":"Check hook configuration in ","type":"text"},{"text":"~/.claude/settings.json","type":"text","marks":[{"type":"code_inline"}]},{"text":" and verify hooks are executable:","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"chmod +x ~/.claude/hooks/*.sh","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Recovery After Crash","type":"text"}]},{"type":"paragraph","content":[{"text":"If a session ended abnormally, the ","type":"text"},{"text":"session-progress-check.sh","type":"text","marks":[{"type":"code_inline"}]},{"text":" hook will detect it on next startup and prompt you to invoke ","type":"text"},{"text":"coding-agent","type":"text","marks":[{"type":"code_inline"}]},{"text":" for recovery.","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Reference Documentation","type":"text"}]},{"type":"paragraph","content":[{"text":"For detailed information, see the reference files:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/two-agent-framework-overview.md","type":"text","marks":[{"type":"code_inline"}]},{"text":" - Full system design","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/initializer-agent-spec.md","type":"text","marks":[{"type":"code_inline"}]},{"text":" - Initializer agent details","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/coding-agent-spec.md","type":"text","marks":[{"type":"code_inline"}]},{"text":" - Coding agent details","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/hook-system.md","type":"text","marks":[{"type":"code_inline"}]},{"text":" - Hook configuration and behavior","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/feature-tracking-system.md","type":"text","marks":[{"type":"code_inline"}]},{"text":" - Progress tracking details","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/session-workflow.md","type":"text","marks":[{"type":"code_inline"}]},{"text":" - Session lifecycle management","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}}]},"metadata":{"date":"2026-06-05","name":"two-agent-harness","author":"@skillopedia","source":{"stars":7,"repo_name":"skills","origin_url":"https://github.com/ingpoc/skills/blob/HEAD/two-agent-harness/SKILL.md","repo_owner":"ingpoc","body_sha256":"ddc8fb5e9fcf6bbca758a3b21d0dd770d70d66c4682d5fe85678ce267e49957d","cluster_key":"7213eae6193e79334c0df1561ff9a5f508fd21c94ffb91cf388e1c0ce91addad","clean_bundle":{"format":"clean-skill-bundle-v1","source":"ingpoc/skills/two-agent-harness/SKILL.md","attachments":[{"id":"ed039d92-ad28-5375-a7b6-368eb3545677","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/ed039d92-ad28-5375-a7b6-368eb3545677/attachment.md","path":"assets/agents/coding-agent.md","size":6673,"sha256":"8913aef3e087ca9afcc639df2ae0348a6cdefaa3c768c21901704fadd044c77f","contentType":"text/markdown; charset=utf-8"},{"id":"3e2c3f30-c7c5-54d5-8e2e-c95e95a324e0","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/3e2c3f30-c7c5-54d5-8e2e-c95e95a324e0/attachment.md","path":"assets/agents/initializer-agent.md","size":7395,"sha256":"0443535c178c3b312e57b763ad965fff084c05a35e67776cb242e50f75f3b8eb","contentType":"text/markdown; charset=utf-8"},{"id":"aef83376-c730-5e65-9b3c-4b71bf079afa","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/aef83376-c730-5e65-9b3c-4b71bf079afa/attachment.md","path":"assets/claude-md-snippet.md","size":1620,"sha256":"ef473a06db5018d7c8c88c3fc0917468eb50a80f5099e487124eed190444c1fe","contentType":"text/markdown; charset=utf-8"},{"id":"fca88b47-71f5-50ef-871d-a15d31bd9c87","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/fca88b47-71f5-50ef-871d-a15d31bd9c87/attachment.sh","path":"assets/hooks/post-tool-guard.sh","size":2314,"sha256":"a47a1bfeb22a2ebec341ddf14620e16db46333fd820529c88a73143d54b6f011","contentType":"application/x-sh; charset=utf-8"},{"id":"866745ac-9d83-5fb7-b998-538d88fe13e2","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/866745ac-9d83-5fb7-b998-538d88fe13e2/attachment.sh","path":"assets/hooks/pre-tool-guard.sh","size":3770,"sha256":"ff87b74fb5f9adfd7a156cf91776ec68405876261f7053a9e94d4fab4ce860cb","contentType":"application/x-sh; charset=utf-8"},{"id":"70cb88b9-b310-511e-af96-33646ff10545","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/70cb88b9-b310-511e-af96-33646ff10545/attachment.sh","path":"assets/hooks/session-end.sh","size":891,"sha256":"b617e57ccb4d107d5ec440cd32cb1a678018ddedcda7b74b7888a66b4d411590","contentType":"application/x-sh; charset=utf-8"},{"id":"54c63d12-fccb-59e9-b0e6-e7b2f9876f71","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/54c63d12-fccb-59e9-b0e6-e7b2f9876f71/attachment.sh","path":"assets/hooks/session-progress-check.sh","size":4381,"sha256":"e781fa1ec4bcdb3b8af74b8da21151b3170431cf7f05a72fd624539dc2c39487","contentType":"application/x-sh; charset=utf-8"},{"id":"1d7ab706-4747-5bbf-8d55-a55b3ea7d417","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/1d7ab706-4747-5bbf-8d55-a55b3ea7d417/attachment.sh","path":"assets/hooks/verify-coding-agent.sh","size":1082,"sha256":"30c1e9f36330b9d7149d5805efcb21e8df76d52ceeb026770bb78fbb4f45b70f","contentType":"application/x-sh; charset=utf-8"},{"id":"ac4ef742-5567-5195-b11e-0a49ec8e2f02","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/ac4ef742-5567-5195-b11e-0a49ec8e2f02/attachment.json","path":"assets/templates/feature-list-template.json","size":986,"sha256":"05e995d3c8a69e2e5c2b3c58a2030cd4a104aa496e6e0e60c94e66deb910a1de","contentType":"application/json; charset=utf-8"},{"id":"3433a7db-75aa-59ab-a2a4-3d48d75c4222","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/3433a7db-75aa-59ab-a2a4-3d48d75c4222/attachment.sh","path":"assets/templates/init-template.sh","size":4339,"sha256":"b88b93ee6f6eb93ce94bb518fb7463b082e20b09e50d2fd9ecf8fa68b73be970","contentType":"application/x-sh; charset=utf-8"},{"id":"66504bf3-4137-5774-8c38-531884d7def8","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/66504bf3-4137-5774-8c38-531884d7def8/attachment.json","path":"assets/templates/session-state-template.json","size":769,"sha256":"8e75fe82dafeff8094fcb125fd8367d315c3ab56d35712615c9f53e4e33cc241","contentType":"application/json; charset=utf-8"},{"id":"a3953772-7cf7-5bc0-a274-6d96262f8f9a","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/a3953772-7cf7-5bc0-a274-6d96262f8f9a/attachment.md","path":"references/coding-agent-spec.md","size":21952,"sha256":"97fdf039c7c50c07eb031ea817f1fb08168de7fdff4ddc222baae1bbb1b4912c","contentType":"text/markdown; charset=utf-8"},{"id":"6d6f0be2-69fa-5c17-a49a-ec13e454fc6a","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/6d6f0be2-69fa-5c17-a49a-ec13e454fc6a/attachment.md","path":"references/feature-tracking-system.md","size":16720,"sha256":"739678cb49535df8169b02046ffcb74063c05636e926557559838892a1957eef","contentType":"text/markdown; charset=utf-8"},{"id":"a54a344a-d6f5-5556-a0cf-ca8ee481fd9b","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/a54a344a-d6f5-5556-a0cf-ca8ee481fd9b/attachment.md","path":"references/file-structure.md","size":20358,"sha256":"02f4b4b85638bbf95d3d0798849ba7bb858614ced7c9eb4d81f94e981504a69e","contentType":"text/markdown; charset=utf-8"},{"id":"83519f3e-0ca8-5b50-90d2-ea54e9c3830b","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/83519f3e-0ca8-5b50-90d2-ea54e9c3830b/attachment.md","path":"references/git-integration.md","size":18180,"sha256":"aa4ded0ebe12d97bbdaa11a41a4d52b9b07a7b589c084216e648978098a5f594","contentType":"text/markdown; charset=utf-8"},{"id":"4aa81db2-0318-589b-bac4-e8c31fbe601c","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/4aa81db2-0318-589b-bac4-e8c31fbe601c/attachment.md","path":"references/hook-system.md","size":19468,"sha256":"74ff2c6aacd089045c20268deddc6f914d731c2c096efc0cded9af8dec3f5308","contentType":"text/markdown; charset=utf-8"},{"id":"0bf7adc7-663e-5636-ac0f-c109af97399c","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/0bf7adc7-663e-5636-ac0f-c109af97399c/attachment.md","path":"references/initializer-agent-spec.md","size":19158,"sha256":"aae531ba2b93140bd49ad8c208fbd4ee5cdc625effe4d36f49df980ae5f51ec5","contentType":"text/markdown; charset=utf-8"},{"id":"cb03fb81-5c92-581a-a6f2-5dd572daa7fe","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/cb03fb81-5c92-581a-a6f2-5dd572daa7fe/attachment.md","path":"references/session-workflow.md","size":18416,"sha256":"abddeac97980df71b49f5058397887340c9215138a481977f93e3d35e0531b60","contentType":"text/markdown; charset=utf-8"},{"id":"dae3da7a-adc8-5965-81c7-d5db6ad1304d","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/dae3da7a-adc8-5965-81c7-d5db6ad1304d/attachment.md","path":"references/testing-strategy.md","size":16684,"sha256":"38d190089c1eb19984f8d11c4be3e30cb9832056a8fa51648b02579307116845","contentType":"text/markdown; charset=utf-8"},{"id":"ed4cd3eb-4c86-5a91-bd16-a2cd27e3c46c","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/ed4cd3eb-4c86-5a91-bd16-a2cd27e3c46c/attachment.md","path":"references/two-agent-framework-overview.md","size":7316,"sha256":"505d3ad030e71c44fe975d0bb3504ab275610d555572b46078f55f293e8ded50","contentType":"text/markdown; charset=utf-8"},{"id":"5f89f3ac-bc26-5b6e-b265-d4cdc8f09bd7","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/5f89f3ac-bc26-5b6e-b265-d4cdc8f09bd7/attachment.sh","path":"scripts/setup-two-agent-system.sh","size":9389,"sha256":"c95b6de715f6c678d0a78382588139c70c78f816af9931282fd068169d4f62be","contentType":"application/x-sh; charset=utf-8"}],"bundle_sha256":"36d1c63a8cf119b28848492bb0c475b85e1489e9925c36b0850226ccbf2efbe2","attachment_count":21,"text_attachments":21,"attachment_storage":"skillopedia-attachments-v1","binary_attachments":0,"excluded_attachments":[]},"cluster_size":1,"skill_md_path":"two-agent-harness/SKILL.md","import_metadata":{"date":"2026-06-05","author":"@skillopedia","version":"v1","category":"devops-infrastructure","category_label":"DevOps"},"exact_dupes_collapsed_into_this":0},"version":"v1","category":"devops-infrastructure","import_tag":"clean-skills-v1","description":"This skill sets up a complete two-agent development system based on the \"Effective Harnesses for Long-Running Agents\" research. It creates initializer-agent (for project planning) and coding-agent (for incremental implementation), along with enforcement hooks and progress tracking infrastructure. Use when users ask to \"set up two-agent system\", \"install agent harness\", \"configure Opus delegation\", or want to implement the two-agent architecture pattern."}},"renderedAt":1782980429123}

Two-Agent Harness System Setup This skill installs a complete two-agent development architecture that separates planning from implementation. Based on the research paper "Effective Harnesses for Long-Running Agents", it enables Claude Code to handle complex, multi-session projects with proper progress tracking and state recovery. System Overview The two-agent harness creates a workflow where: - Opus (you) orchestrates and delegates - never implements directly - Initializer Agent (sonnet) breaks down projects into 200+ trackable features - Coding Agent (sonnet) implements features one at a tim…