ralph-claude-code/tests/unit/test_enable_core.bats
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

388 lines
9.9 KiB
Bash

#!/usr/bin/env bats
# Unit tests for lib/enable_core.sh
# Tests idempotency, safe file creation, project detection, and template generation
load '../helpers/test_helper'
load '../helpers/fixtures'
# Path to enable_core.sh
ENABLE_CORE="${BATS_TEST_DIRNAME}/../../lib/enable_core.sh"
setup() {
# Create temporary test directory
TEST_DIR="$(mktemp -d)"
cd "$TEST_DIR"
# Source the library (disable set -e for testing)
set +e
source "$ENABLE_CORE"
set -e
}
teardown() {
if [[ -n "$TEST_DIR" ]] && [[ -d "$TEST_DIR" ]]; then
cd /
rm -rf "$TEST_DIR"
fi
}
# =============================================================================
# IDEMPOTENCY CHECKS (5 tests)
# =============================================================================
@test "check_existing_ralph returns 'none' when no .ralph directory exists" {
check_existing_ralph || true
assert_equal "$RALPH_STATE" "none"
}
@test "check_existing_ralph returns 'complete' when all required files exist" {
mkdir -p .ralph
echo "# PROMPT" > .ralph/PROMPT.md
echo "# Fix Plan" > .ralph/@fix_plan.md
echo "# Agent" > .ralph/@AGENT.md
check_existing_ralph || true
assert_equal "$RALPH_STATE" "complete"
}
@test "check_existing_ralph returns 'partial' when some files are missing" {
mkdir -p .ralph
echo "# PROMPT" > .ralph/PROMPT.md
# Missing @fix_plan.md and @AGENT.md
check_existing_ralph || true
assert_equal "$RALPH_STATE" "partial"
[[ " ${RALPH_MISSING_FILES[*]} " =~ ".ralph/@fix_plan.md" ]]
[[ " ${RALPH_MISSING_FILES[*]} " =~ ".ralph/@AGENT.md" ]]
}
@test "is_ralph_enabled returns 0 when fully enabled" {
mkdir -p .ralph
echo "# PROMPT" > .ralph/PROMPT.md
echo "# Fix Plan" > .ralph/@fix_plan.md
echo "# Agent" > .ralph/@AGENT.md
run is_ralph_enabled
assert_success
}
@test "is_ralph_enabled returns 1 when not enabled" {
run is_ralph_enabled
assert_failure
}
# =============================================================================
# SAFE FILE OPERATIONS (5 tests)
# =============================================================================
@test "safe_create_file creates file that doesn't exist" {
run safe_create_file "test.txt" "test content"
assert_success
[[ -f "test.txt" ]]
[[ "$(cat test.txt)" == "test content" ]]
}
@test "safe_create_file skips existing file" {
echo "original content" > existing.txt
run safe_create_file "existing.txt" "new content"
assert_failure # Returns 1 for skip
assert_equal "$(cat existing.txt)" "original content"
[[ "$output" =~ "SKIP" ]] || [[ "$output" =~ "already exists" ]]
}
@test "safe_create_file creates parent directories" {
run safe_create_file "nested/dir/file.txt" "nested content"
assert_success
[[ -f "nested/dir/file.txt" ]]
[[ "$(cat nested/dir/file.txt)" == "nested content" ]]
}
@test "safe_create_dir creates directory that doesn't exist" {
run safe_create_dir "new_dir"
assert_success
[[ -d "new_dir" ]]
}
@test "safe_create_dir succeeds when directory already exists" {
mkdir existing_dir
run safe_create_dir "existing_dir"
assert_success
[[ -d "existing_dir" ]]
}
# =============================================================================
# DIRECTORY STRUCTURE (2 tests)
# =============================================================================
@test "create_ralph_structure creates all required directories" {
run create_ralph_structure
assert_success
[[ -d ".ralph" ]]
[[ -d ".ralph/specs" ]]
[[ -d ".ralph/examples" ]]
[[ -d ".ralph/logs" ]]
[[ -d ".ralph/docs/generated" ]]
}
@test "create_ralph_structure is idempotent" {
create_ralph_structure
echo "test" > .ralph/specs/test.txt
run create_ralph_structure
assert_success
[[ -f ".ralph/specs/test.txt" ]]
}
# =============================================================================
# PROJECT DETECTION (6 tests)
# =============================================================================
@test "detect_project_context identifies TypeScript from package.json" {
cat > package.json << 'EOF'
{
"name": "my-ts-project",
"devDependencies": {
"typescript": "^5.0.0"
}
}
EOF
detect_project_context
assert_equal "$DETECTED_PROJECT_TYPE" "typescript"
assert_equal "$DETECTED_PROJECT_NAME" "my-ts-project"
}
@test "detect_project_context identifies JavaScript from package.json" {
cat > package.json << 'EOF'
{
"name": "my-js-project"
}
EOF
detect_project_context
assert_equal "$DETECTED_PROJECT_TYPE" "javascript"
}
@test "detect_project_context identifies Python from pyproject.toml" {
cat > pyproject.toml << 'EOF'
[project]
name = "my-python-project"
EOF
detect_project_context
assert_equal "$DETECTED_PROJECT_TYPE" "python"
}
@test "detect_project_context identifies Next.js framework" {
cat > package.json << 'EOF'
{
"name": "nextjs-app",
"dependencies": {
"next": "^14.0.0"
}
}
EOF
detect_project_context
assert_equal "$DETECTED_FRAMEWORK" "nextjs"
}
@test "detect_project_context identifies FastAPI framework" {
cat > pyproject.toml << 'EOF'
[project]
name = "fastapi-app"
dependencies = ["fastapi>=0.100.0"]
EOF
detect_project_context
assert_equal "$DETECTED_FRAMEWORK" "fastapi"
}
@test "detect_project_context falls back to folder name" {
detect_project_context
# Should use the temp directory name
[[ -n "$DETECTED_PROJECT_NAME" ]]
}
# =============================================================================
# GIT DETECTION (3 tests)
# =============================================================================
@test "detect_git_info detects git repository" {
git init >/dev/null 2>&1
detect_git_info
assert_equal "$DETECTED_GIT_REPO" "true"
}
@test "detect_git_info detects non-git directory" {
detect_git_info
assert_equal "$DETECTED_GIT_REPO" "false"
}
@test "detect_git_info detects GitHub remote" {
git init >/dev/null 2>&1
git remote add origin git@github.com:user/repo.git 2>/dev/null || true
detect_git_info
assert_equal "$DETECTED_GIT_GITHUB" "true"
}
# =============================================================================
# TASK SOURCE DETECTION (2 tests)
# =============================================================================
@test "detect_task_sources detects .beads directory" {
mkdir -p .beads
detect_task_sources
assert_equal "$DETECTED_BEADS_AVAILABLE" "true"
}
@test "detect_task_sources finds PRD files" {
mkdir -p docs
echo "# Requirements" > docs/requirements.md
detect_task_sources
[[ ${#DETECTED_PRD_FILES[@]} -gt 0 ]]
}
# =============================================================================
# TEMPLATE GENERATION (4 tests)
# =============================================================================
@test "generate_prompt_md includes project name" {
output=$(generate_prompt_md "my-project" "typescript")
[[ "$output" =~ "my-project" ]]
}
@test "generate_prompt_md includes project type" {
output=$(generate_prompt_md "my-project" "python")
[[ "$output" =~ "python" ]]
}
@test "generate_agent_md includes build command" {
output=$(generate_agent_md "npm run build" "npm test" "npm start")
[[ "$output" =~ "npm run build" ]]
[[ "$output" =~ "npm test" ]]
}
@test "generate_ralphrc includes project configuration" {
output=$(generate_ralphrc "my-project" "typescript" "local,beads")
[[ "$output" =~ "PROJECT_NAME=\"my-project\"" ]]
[[ "$output" =~ "PROJECT_TYPE=\"typescript\"" ]]
[[ "$output" =~ "TASK_SOURCES=\"local,beads\"" ]]
}
# =============================================================================
# FULL ENABLE FLOW (3 tests)
# =============================================================================
@test "enable_ralph_in_directory creates all required files" {
export ENABLE_FORCE="false"
export ENABLE_SKIP_TASKS="true"
export ENABLE_PROJECT_NAME="test-project"
run enable_ralph_in_directory
assert_success
[[ -f ".ralph/PROMPT.md" ]]
[[ -f ".ralph/@fix_plan.md" ]]
[[ -f ".ralph/@AGENT.md" ]]
[[ -f ".ralphrc" ]]
}
@test "enable_ralph_in_directory returns ALREADY_ENABLED when complete and no force" {
mkdir -p .ralph
echo "# PROMPT" > .ralph/PROMPT.md
echo "# Fix Plan" > .ralph/@fix_plan.md
echo "# Agent" > .ralph/@AGENT.md
export ENABLE_FORCE="false"
run enable_ralph_in_directory
assert_equal "$status" "$ENABLE_ALREADY_ENABLED"
}
@test "enable_ralph_in_directory overwrites with force flag" {
mkdir -p .ralph
echo "old content" > .ralph/PROMPT.md
echo "old fix plan" > .ralph/@fix_plan.md
echo "old agent" > .ralph/@AGENT.md
export ENABLE_FORCE="true"
export ENABLE_PROJECT_NAME="new-project"
run enable_ralph_in_directory
assert_success
# Verify files were actually overwritten, not just skipped
local prompt_content
prompt_content=$(cat .ralph/PROMPT.md)
# Should contain new project name, not "old content"
[[ "$prompt_content" != "old content" ]]
[[ "$prompt_content" == *"new-project"* ]]
}
@test "safe_create_file overwrites existing file when ENABLE_FORCE is true" {
# Create existing file with old content
echo "original content" > test_file.txt
export ENABLE_FORCE="true"
run safe_create_file "test_file.txt" "new content"
assert_success
# Verify file was overwritten
local content
content=$(cat test_file.txt)
[[ "$content" == "new content" ]]
}
@test "safe_create_file skips existing file when ENABLE_FORCE is false" {
# Create existing file with old content
echo "original content" > test_file.txt
export ENABLE_FORCE="false"
run safe_create_file "test_file.txt" "new content"
# Should return 1 (skipped)
assert_failure
# Verify file was NOT overwritten
local content
content=$(cat test_file.txt)
[[ "$content" == "original content" ]]
}