Commit graph

9 commits

Author SHA1 Message Date
Test User
b4b9db6b76 feat(circuit-breaker): add auto-recovery from OPEN state (#160)
The OPEN state was terminal — once triggered, it persisted across
restarts with no automatic recovery. This adds two recovery mechanisms:

1. Cooldown timer (default): OPEN → HALF_OPEN after CB_COOLDOWN_MINUTES
   (default 30). The existing HALF_OPEN logic handles recovery or re-trip.
2. Auto-reset option: CB_AUTO_RESET=true bypasses cooldown, resets to
   CLOSED on startup for fully unattended operation.

Changes:
- Add parse_iso_to_epoch() to lib/date_utils.sh (cross-platform)
- Add cooldown + auto-reset logic to init_circuit_breaker()
- Add opened_at field to state file when entering/staying OPEN
- Add --auto-reset-circuit CLI flag and .ralphrc config vars
- Add 19 tests in test_circuit_breaker_recovery.bats
- Update CLAUDE.md and README.md documentation
2026-02-07 01:33:41 -07:00
Frank Bria
c7e7a1c6a3
refactor(naming): remove @ prefix from on-disk filenames (#131)
* refactor(naming): remove @ prefix from on-disk filenames

BREAKING CHANGE: Renames @fix_plan.md → fix_plan.md and @AGENT.md → AGENT.md

This change improves POSIX compliance and compatibility with command-line tools.
The @ prefix was originally used to avoid naming conflicts, but with the .ralph/
folder structure introduced in v0.10.0, this convention is no longer necessary.

Changes:
- Update all scripts to use new naming (fix_plan.md, AGENT.md)
- Update migration script to handle both old and new naming conventions
- Update templates to use new naming
- Update all documentation references
- Update all 420 tests to expect new naming (TDD approach)

Migration:
- Existing projects with @-prefixed files will be automatically renamed
  when running ralph-migrate
- Projects already using the new naming will continue to work unchanged

* docs(claude): update file naming conventions section

* fix(migrate): prevent orphaned @-prefixed files during migration

When both root/@fix_plan.md and .ralph/@fix_plan.md exist, the root file
now takes priority and the .ralph/@fix_plan.md is removed (backup exists).
This prevents orphaned legacy files after migration.

---------

Co-authored-by: Test User <test@example.com>
2026-01-26 15:40:27 -07:00
Frank Bria
910f794fcc
feat(enable): add ralph-enable wizard for existing projects (v0.11.0) (#124)
* feat(enable): add ralph-enable wizard for existing projects (v0.11.0)

Add interactive wizard and CI version for enabling Ralph in existing projects.

New commands:
- ralph-enable: Interactive 5-phase wizard for humans
- ralph-enable-ci: Non-interactive version with JSON output for CI/automation

New library components:
- lib/enable_core.sh: Shared logic for idempotency, project detection, templates
- lib/wizard_utils.sh: Interactive prompt utilities
- lib/task_sources.sh: Task import from beads, GitHub Issues, PRD documents

Features:
- Auto-detects project type (TypeScript, Python, Rust, Go)
- Auto-detects framework (Next.js, FastAPI, Django, Express)
- Imports tasks from beads, GitHub Issues, or PRD documents
- Generates .ralphrc project configuration file
- Idempotent: safe to run multiple times, respects existing files
- Exit codes: 0 (success), 1 (error), 2 (already enabled)

Updated:
- install.sh: Added new commands to global installation
- ralph_loop.sh: Loads .ralphrc configuration at startup

Tests: 75 new tests (30 enable_core + 23 task_sources + 22 integration)
Total: 396 tests passing (100% pass rate)

Closes #85, #121, #64, #87, #99

* fix(enable): address code review feedback

Fixes from PR #124 review:

1. sed -i portability (ralph_enable.sh:456)
   - Use portable sed + mv pattern instead of GNU-only sed -i

2. sed regex portability (lib/task_sources.sh)
   - Replace \s with POSIX [[:space:]] character class
   - Add sed -E flag for extended regex

3. jq availability check (ralph_enable_ci.sh:177)
   - Add check for jq when --json flag is used

4. Unused filter parameter (lib/task_sources.sh:44)
   - Pass filter to bd list --filter command

5. Word-splitting in select_multiple (ralph_enable.sh:322)
   - Return comma-separated indices instead of space-separated text
   - Update caller to parse indices correctly

6. Missing || true for check_existing_ralph (ralph_enable.sh:185)
   - Prevent set -e from exiting on non-zero return

7. select_multiple stdout corruption (lib/wizard_utils.sh)
   - Redirect interactive output to stderr
   - Only final result goes to stdout

8. Color variables not exported (lib/wizard_utils.sh:12)
   - Export WIZARD_* color variables for subshells

9. select_option infinite loop (lib/wizard_utils.sh:179)
   - Add guard for empty options array

* fix(tests): add missing mocks and exports for new enable feature

- Add RESPONSE_ANALYSIS_FILE export to test_session_continuity.bats setup
- Add mock ralph_enable.sh and ralph_enable_ci.sh to test_installation.bats
- Add mock lib files: enable_core.sh, wizard_utils.sh, task_sources.sh, timeout_utils.sh

All 396 tests now pass.

* fix(config): fix critical issues from PR review

1. .ralphrc Configuration Loading Fix:
   - Captured env var state BEFORE setting defaults with _env_* variables
   - load_ralphrc now only restores values explicitly set by environment
   - .ralphrc settings are now properly applied (not overwritten by defaults)

2. sed Command Injection Fix:
   - Replaced sed with awk for .ralphrc updates in ralph_enable.sh
   - awk -v pattern safely handles user input without shell injection risk

3. Shell Injection Fix in safe_create_file():
   - Replaced echo with printf '%s\n' for safer content handling
   - Prevents issues with backslashes, -n, and special characters

4. Specific Error Codes:
   - Added ENABLE_INVALID_ARGS=3 for argument errors
   - Added ENABLE_FILE_NOT_FOUND=4 for missing files
   - Added ENABLE_DEPENDENCY_MISSING=5 for missing deps (e.g., jq)
   - Added ENABLE_PERMISSION_DENIED=6 for permission errors
   - Updated ralph_enable.sh and ralph_enable_ci.sh to use specific codes

5. Added tests for .ralphrc loading pattern verification

Test count: 398 (up from 396)

* fix(enable): make --force flag actually overwrite existing files

The --force flag was accepted but safe_create_file() always skipped
existing files regardless of ENABLE_FORCE value.

Changes:
- safe_create_file() now checks ENABLE_FORCE environment variable
- When ENABLE_FORCE="true", overwrites existing files instead of skipping
- Added proper logging for overwrite operations

Added tests:
- Verify enable_ralph_in_directory actually changes file contents with --force
- Test safe_create_file overwrites when ENABLE_FORCE is true
- Test safe_create_file skips when ENABLE_FORCE is false

Test count: 400 (up from 398)

---------

Co-authored-by: Test User <test@example.com>
2026-01-25 14:37:25 -07:00
Frank Bria
9b19d70e35
feat(structure): migrate Ralph files to .ralph/ subfolder (#109)
* feat(structure): migrate Ralph files to .ralph/ subfolder

BREAKING CHANGE: Ralph configuration files now live in .ralph/ subfolder

This refactoring moves all Ralph-specific files into a hidden .ralph/
directory while keeping src/ at the project root. This improves
compatibility with existing tooling and keeps the project root clean.

Changes:
- Move PROMPT.md, @fix_plan.md, @AGENT.md to .ralph/
- Move specs/, logs/, docs/generated/, examples/ to .ralph/
- Move state files (.response_analysis, .circuit_breaker_state, etc.) to .ralph/
- Keep src/ at project root (unchanged)
- Add RALPH_DIR=".ralph" configuration variable
- Add ralph-migrate command for existing projects
- Create migrate_to_ralph_folder.sh migration script
- Update all path references in scripts and tests
- Update documentation (README.md, CLAUDE.md)

New project structure:
  project/
  ├── .ralph/           # Ralph configuration
  │   ├── PROMPT.md
  │   ├── @fix_plan.md
  │   ├── @AGENT.md
  │   ├── specs/
  │   ├── logs/
  │   └── docs/generated/
  └── src/              # Source code (unchanged)

Migration: Run `ralph-migrate` in existing projects to upgrade.

All 310 tests pass (100% pass rate).

* chore: add .claude/settings.local.json to .gitignore

* fix: address code review feedback for .ralph/ subfolder structure

Fixes multiple path-related issues identified in code review:

Test fixes:
- Fix create_sample_prompt to use $RALPH_DIR/PROMPT.md in test_session_continuity.bats
- Fix result_file path to use $RALPH_DIR/.json_parse_result in test_json_parsing.bats
- Fix @fix_plan.md and .response_analysis paths in test_cli_modern.bats
- Update templates directory missing test to account for global fallback

Template fix:
- Fix @fix_plan.md reference in templates/PROMPT.md to use .ralph/ prefix

Script fixes:
- Fix PROMPT_FILE comparison in ralph_loop.sh to use $RALPH_DIR/PROMPT.md
- Fix examples migration logic in migrate_to_ralph_folder.sh (remove premature mkdir)
- Move templates directory check AFTER cd in setup.sh (was checking wrong location)
- Add template directory validation with fallback to global templates

All 310 tests pass.

* Update migrate_to_ralph_folder.sh

Co-authored-by: macroscopeapp[bot] <170038800+macroscopeapp[bot]@users.noreply.github.com>

* fix: address code review feedback for .ralph/ subfolder structure

Code Review Fixes:
- Fix test_json_parsing.bats: all result_file and session file paths now use $RALPH_DIR prefix
- Fix ralph_loop.sh help text: paths now show .ralph/.ralph_session, .ralph/.call_count, etc.
- Fix migrate_to_ralph_folder.sh:
  - Proper error handling for date command (separate local declaration)
  - Use cp -a source/. dest/ pattern to preserve dotfiles and attributes
  - Remove 2>/dev/null suppression to surface copy errors
- Update create_files.sh to use .ralph/ structure for embedded scripts
- Update .gitignore with all .ralph/ state file paths
- Add old structure detection in ralph_loop.sh with helpful migration message

Version Update:
- Bump to v0.10.0 (breaking change: structural reorganization)
- Update README.md and CLAUDE.md with new version and release notes
- Add ralph-migrate documentation to Key Commands section

All 310 tests pass.

---------

Co-authored-by: macroscopeapp[bot] <170038800+macroscopeapp[bot]@users.noreply.github.com>
2026-01-20 23:22:30 -07:00
frankbria
cc8d2b52b9 docs(claude): add feature development quality standards
- Add comprehensive testing requirements (85% coverage minimum)
- Add git workflow requirements with conventional commits
- Add documentation synchronization requirements
- Add feature completion checklist
- Integrate with Ralph loop and @fix_plan.md workflow
- Include template file updates for AGENT.md
- Add Ralph-specific testing patterns and quality gates
2025-10-10 16:13:49 -07:00
frankbria
3ae67f66ac Phase 2: Requirements, testing, and documentation enhancements
Implements all Phase 2 high-priority recommendations from expert panel:

**1. Requirements Improvement** (Karl Wiegers, Gojko Adzic)
- Enhanced templates/PROMPT.md with 6 concrete Given/When/Then scenarios
- Specification by Example format for all exit conditions
- Clear expectations for each scenario type:
  * Successful completion
  * Test-only loops
  * Stuck on errors
  * No work remaining
  * Making progress
  * Blocked on dependencies

**2. Use Case Documentation** (Alistair Cockburn)
- Created comprehensive USE_CASES.md (600+ lines)
- Defined 6 primary use cases with full Cockburn format:
  * UC-1: Execute Development Loop
  * UC-2: Detect Project Completion
  * UC-3: Prevent Resource Waste
  * UC-4: Handle API Rate Limits
  * UC-5: Provide Loop Monitoring
  * UC-6: Reset Circuit Breaker
- Includes actors, goals, success scenarios, extensions, edge cases
- Clear goal hierarchy and success metrics

**3. Enhanced Test Coverage** (Lisa Crispin, Janet Gregory)
- Added tests/integration/test_edge_cases.bats (20 new tests)
- Edge cases: empty files, large files, corrupted JSON, unicode
- Boundary conditions: exact thresholds, overflow scenarios
- Error conditions: missing git, malformed data, rapid transitions
- All 40 integration tests passing (100% success rate)

**4. Circuit Breaker Robustness**
- Enhanced init_circuit_breaker() with corruption detection
- Auto-recovery from corrupted state/history files
- Validates JSON before use, recreates if invalid

**5. Specification Workshop Guide**
- Created SPECIFICATION_WORKSHOP.md
- Three Amigos methodology with templates
- Includes complete example workshop
- Best practices and red flags
- Quick 15-minute template for small features

**Test Results**: 40/40 integration tests passing
**Documentation Added**: 1,200+ lines (USE_CASES.md, SPECIFICATION_WORKSHOP.md)
**Coverage Improvement**: Edge cases and error conditions fully tested

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-01 21:34:54 -07:00
frankbria
2cf06b0de2 Implement Phase 1 critical fixes: Response analyzer & circuit breaker
Implements all Phase 1 recommendations from expert panel review:

1. **Response Analysis Pipeline** (Martin Fowler recommendation)
   - New lib/response_analyzer.sh component
   - Parses Claude Code output for completion signals
   - Detects test-only loops and stagnation
   - Updates .exit_signals file with structured data
   - Tracks confidence scores and progress indicators

2. **Circuit Breaker Pattern** (Michael Nygard recommendation)
   - New lib/circuit_breaker.sh component
   - Three-state pattern: CLOSED → HALF_OPEN → OPEN
   - Prevents runaway token consumption
   - Detects: no progress (3 loops), same errors (5 loops)
   - Automatic halt with clear user guidance
   - Manual reset capability

3. **Structured Output Contract** (Sam Newman recommendation)
   - Updated PROMPT.md template with RALPH_STATUS format
   - Defines clear JSON-parseable exit signals
   - SMART criteria for completion detection
   - Concrete examples for all scenarios

4. **Integration & Testing**
   - ralph_loop.sh integration of both components
   - 20 comprehensive BATS integration tests (all passing)
   - Tests cover: signal detection, circuit states, full loop flows
   - Validates Phase 1 implementation correctness

**Impact**: Solves infinite loop problem, enables reliable exit detection,
prevents token waste through systematic stagnation detection.

**Test Results**: 20/20 integration tests passing

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-01 21:11:18 -07:00
frankbria
907f36c820 Add directory structure with .gitkeep files
- Add .gitkeep files to ensure all essential directories are tracked by git
- Update .gitignore to allow .gitkeep files in logs/ and docs/generated/
- Preserve directory structure for Ralph project template system
- Directories added: src/, examples/, specs/stdlib/, templates/specs/,
  logs/, docs/generated/

This ensures the complete Ralph project structure is available when
cloning the repository, even before any actual project files are created.
2025-08-27 09:27:33 -07:00
frankbria
48bd008701 Fix create_files.sh syntax errors and complete Ralph implementation
- Fix nested EOF heredoc conflicts in update_status() and show_help() functions
- Use unique delimiters (STATUSEOF, HELPEOF) to avoid conflicts
- Complete Ralph for Claude Code implementation with all components:
  - ralph_loop.sh: Main autonomous development loop with rate limiting
  - ralph_monitor.sh: Live monitoring dashboard
  - setup.sh: Project initialization script
  - templates/: Template files for new projects
  - .gitignore: Comprehensive ignore rules

All scripts are now executable and syntax-validated.
2025-08-27 09:15:00 -07:00