ralphblaster-agent 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +294 -0
  3. package/bin/agent-dashboard.sh +168 -0
  4. package/bin/monitor-agent.sh +264 -0
  5. package/bin/ralphblaster.js +247 -0
  6. package/package.json +64 -0
  7. package/postinstall-colored.js +66 -0
  8. package/src/api-client.js +764 -0
  9. package/src/claude-plugin/.claude-plugin/plugin.json +9 -0
  10. package/src/claude-plugin/README.md +42 -0
  11. package/src/claude-plugin/skills/ralph/SKILL.md +259 -0
  12. package/src/commands/add-project.js +257 -0
  13. package/src/commands/init.js +79 -0
  14. package/src/config-file-manager.js +84 -0
  15. package/src/config.js +66 -0
  16. package/src/error-window.js +86 -0
  17. package/src/executor/claude-runner.js +716 -0
  18. package/src/executor/error-handler.js +65 -0
  19. package/src/executor/git-helper.js +196 -0
  20. package/src/executor/index.js +296 -0
  21. package/src/executor/job-handlers/clarifying-questions.js +213 -0
  22. package/src/executor/job-handlers/code-execution.js +145 -0
  23. package/src/executor/job-handlers/prd-generation.js +259 -0
  24. package/src/executor/path-helper.js +74 -0
  25. package/src/executor/prompt-validator.js +51 -0
  26. package/src/executor.js +4 -0
  27. package/src/index.js +342 -0
  28. package/src/logger.js +193 -0
  29. package/src/logging/README.md +93 -0
  30. package/src/logging/config.js +179 -0
  31. package/src/logging/destinations/README.md +290 -0
  32. package/src/logging/destinations/api-destination-unbatched.js +118 -0
  33. package/src/logging/destinations/api-destination.js +40 -0
  34. package/src/logging/destinations/base-destination.js +85 -0
  35. package/src/logging/destinations/batched-destination.js +198 -0
  36. package/src/logging/destinations/console-destination.js +172 -0
  37. package/src/logging/destinations/file-destination.js +208 -0
  38. package/src/logging/destinations/index.js +29 -0
  39. package/src/logging/destinations/progress-batch-destination-unbatched.js +92 -0
  40. package/src/logging/destinations/progress-batch-destination.js +41 -0
  41. package/src/logging/formatter.js +288 -0
  42. package/src/logging/log-manager.js +426 -0
  43. package/src/progress-throttle.js +101 -0
  44. package/src/system-monitor.js +64 -0
  45. package/src/utils/format.js +16 -0
  46. package/src/utils/log-file-helper.js +265 -0
  47. package/src/utils/progress-parser.js +250 -0
  48. package/src/worktree-manager.js +255 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Wildfront LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,294 @@
1
+ # RalphBlaster Agent
2
+
3
+ RalphBlaster Agent is a distributed autonomous coding agent that polls a Rails API for jobs and executes them locally using Claude CLI.
4
+
5
+ # Requirements
6
+
7
+ Compatibility range:
8
+ - ✅ macOS 10.15+ (any recent version)
9
+ - ✅ Linux (Ubuntu, Debian, RHEL, Fedora, Arch, etc.)
10
+ - ✅ Works with different shells (bash, zsh, sh) since it doesn't rely on shell execution
11
+
12
+ The only requirement is that users have Node.js 18+, Claude CLI, and Git installed - all of which are readily available on both platforms.
13
+
14
+ ## Features
15
+
16
+ - 🔄 **Automatic Job Polling**: Continuously polls the RalphBlaster API for new coding jobs
17
+ - 🤖 **Claude CLI Integration**: Executes jobs using the Claude CLI
18
+ - 🚀 **Multi-Agent Support**: Run multiple agents concurrently for parallel job processing
19
+ - 💪 **Resilient**: Handles failures gracefully with automatic retries and timeouts
20
+ - 🔐 **Secure**: Uses API tokens with specific permissions for authentication
21
+ - 📊 **Real-time Updates**: Reports job progress and status back to the API
22
+ - ⚡ **Heartbeat System**: Keeps jobs alive during long-running executions
23
+
24
+ ## Prerequisites
25
+
26
+ - Node.js >= 18.0.0
27
+ - Claude CLI installed and available in PATH (`claude --version` should work)
28
+ - A RalphBlaster API token with `ralphblaster_agent` permission
29
+
30
+ ## Installation
31
+
32
+ ### Global Installation
33
+
34
+ ```bash
35
+ npm install -g ralphblaster-agent
36
+ ```
37
+
38
+ ### Local Installation
39
+
40
+ ```bash
41
+ git clone <repository>
42
+ cd ralphblaster-agent
43
+ npm install
44
+ ```
45
+
46
+ ### Using npx (No Installation Required)
47
+
48
+ ```bash
49
+ npx ralphblaster-agent --token=your_token_here
50
+ ```
51
+
52
+ ## Usage
53
+
54
+ ### Basic Usage
55
+
56
+ ```bash
57
+ # Single agent (default)
58
+ ralphblaster --token=your_api_token_here
59
+
60
+ # Using environment variable
61
+ RALPHBLASTER_API_TOKEN=your_api_token_here ralphblaster
62
+
63
+ # Local development (override API URL)
64
+ ralphblaster --token=your_token --api-url=http://localhost:5002
65
+ ```
66
+
67
+ ### Multi-Agent Mode (Parallel Processing)
68
+
69
+ Run multiple agents concurrently to process jobs in parallel:
70
+
71
+ ```bash
72
+ # Run 3 agents for 3x throughput
73
+ ralphblaster --agents=3
74
+
75
+ # With npm
76
+ npm start -- --agents=3
77
+
78
+ # Or use convenience scripts
79
+ npm run start:multi # 3 agents
80
+ npm run start:multi:5 # 5 agents
81
+
82
+ # Advanced: Use bash scripts for production
83
+ ./scripts/start-agents.sh 3
84
+ ./scripts/agent-status.sh
85
+ ```
86
+
87
+ **Benefits:**
88
+ - 3x job processing throughput with 3 agents
89
+ - Process isolation - one crash doesn't affect others
90
+ - Full log traceability with agent IDs
91
+ - Easy to scale up/down
92
+
93
+ **See:** `MULTI_AGENT_USAGE.md` for complete guide
94
+
95
+ ### Configuration Options
96
+
97
+ The agent can be configured via environment variables or command-line flags:
98
+
99
+ | Environment Variable | CLI Flag | Default | Description |
100
+ |---------------------|----------|---------|-------------|
101
+ | `RALPHBLASTER_API_TOKEN` | `--token=` | *Required* | API authentication token |
102
+ | `RALPHBLASTER_API_URL` | `--api-url=` | `https://ralphblaster.com` | RalphBlaster API base URL |
103
+ | `RALPHBLASTER_AGENT_ID` | `--agents=` | `agent-default` / `1` | Agent ID or agent count for multi-agent mode |
104
+ | `RALPHBLASTER_POLL_INTERVAL` | - | `5000` | Polling interval in milliseconds |
105
+ | `RALPHBLASTER_LOG_LEVEL` | - | `info` | Log level (error, warn, info, debug) |
106
+ | `RALPHBLASTER_MAX_RETRIES` | - | `3` | Maximum retry attempts |
107
+
108
+ ### Using .env File
109
+
110
+ Create a `.env` file in the ralphblaster-agent directory:
111
+
112
+ ```env
113
+ RALPHBLASTER_API_TOKEN=your_api_token_here
114
+ # RALPHBLASTER_API_URL=http://localhost:5002 # Uncomment for local development
115
+ RALPHBLASTER_POLL_INTERVAL=5000
116
+ RALPHBLASTER_LOG_LEVEL=info
117
+ ```
118
+
119
+ Then run:
120
+
121
+ ```bash
122
+ ralphblaster
123
+ ```
124
+
125
+ ## How It Works
126
+
127
+ 1. **Polling**: The agent continuously polls the API endpoint `/api/v1/ralphblaster/jobs/next` for available jobs
128
+ 2. **Job Claiming**: When a job is found, it's automatically claimed by the agent
129
+ 3. **Status Update**: The agent marks the job as "running" and starts sending heartbeats
130
+ 4. **Execution**: The job is executed based on its type:
131
+ - **PRD Generation**: Uses Claude `/prd` skill or direct prompts
132
+ - **Code Execution**: Creates a RalphBlaster agent instance (see below)
133
+ 5. **Completion**: Results are parsed and reported back to the API
134
+ 6. **Cleanup**: The agent marks the job as completed or failed and continues polling
135
+
136
+ ### Agent Status System
137
+
138
+ The agent uses a heartbeat system to maintain connection status with the backend:
139
+
140
+ - **Heartbeat Interval**: 20 seconds (3 heartbeats per minute)
141
+ - **Offline Threshold**: 35 seconds (backend considers agent offline after this)
142
+ - **Safety Margin**: 15 seconds buffer to prevent false offline readings
143
+
144
+ This ensures the agent is always shown as "online" in the UI during normal operation, while still detecting real disconnections within 35-40 seconds. Status updates are broadcast in real-time via ActionCable WebSocket connections.
145
+
146
+ ## RalphBlaster Agent Integration
147
+
148
+ For `code_execution` job types, the agent uses the RalphBlaster system - an iterative, PRD-driven execution framework that enables complex, multi-step implementations.
149
+
150
+ ### How the Agent Works
151
+
152
+ 1. **Poll for Jobs**: Agent continuously polls `/api/v1/ralphblaster/jobs/next` for available work
153
+ 2. **Worktree Creation**: Creates an isolated git worktree for each job in `{repo}-worktrees/job-{id}/`
154
+ 3. **Claude Execution**: Runs Claude CLI directly in the worktree with the server-provided prompt
155
+ 4. **Progress Streaming**: Real-time output streamed to `.ralphblaster-logs/job-{id}.log` and sent to API
156
+ 5. **Git Activity**: Commits are made in the worktree, then pushed to remote
157
+ 6. **Completion**: Job status and results reported back to API via `/api/v1/ralphblaster/jobs/{id}`
158
+ 7. **Cleanup**: Worktrees are automatically removed after job completion (configurable)
159
+
160
+ ### Directory Structure
161
+
162
+ Worktrees are created as siblings to your project (not inside it) to prevent git conflicts:
163
+
164
+ ```
165
+ my-project/ # Your main repository
166
+ my-project-worktrees/ # Worktrees (sibling directory)
167
+ └── job-{id}/ # Isolated worktree for each job
168
+ └── [project files...] # Isolated copy of project code
169
+ .ralphblaster-logs/ # Log files (persisted)
170
+ └── job-{id}.log # Agent execution log
171
+ └── job-{id}-stderr.log # Error output (if any)
172
+ ```
173
+
174
+ ### Key Features
175
+
176
+ Agent directly executes Claude CLI with:
177
+
178
+ - `RALPHBLASTER_WORKTREE_PATH` - Path to the git worktree
179
+ - `RALPHBLASTER_INSTANCE_DIR` - Path to the RalphBlaster instance directory
180
+ - `RALPHBLASTER_MAIN_REPO` - Path to the main repository
181
+
182
+ ### RalphBlaster Execution Limits
183
+
184
+ - **Max Iterations**: 10
185
+ - **Timeout**: 2 hours
186
+ - **Completion**: All user stories must pass quality checks
187
+
188
+ ### Advantages of RalphBlaster Agent Integration
189
+
190
+ - **Structured Approach**: PRD-driven development ensures clear requirements
191
+ - **Quality Assurance**: Each story is validated with tests before proceeding
192
+ - **Progress Tracking**: Detailed logs of what was accomplished
193
+ - **Isolation**: Git worktrees keep work separate from main repository
194
+ - **Iterative Refinement**: Can fix issues and retry failed stories automatically
195
+
196
+ ## API Token Setup
197
+
198
+ To create an API token with ralphblaster_agent permission:
199
+
200
+ 1. Log into your RalphBlaster account
201
+ 2. Navigate to API Tokens settings
202
+ 3. Create a new token
203
+ 4. Check the "RalphBlaster Agent Access" permission
204
+ 5. Copy the token (shown only once!)
205
+
206
+ ## Example Output
207
+
208
+ ```
209
+ [2026-01-16T20:00:00.000Z] [INFO]
210
+ ╔═══════════════════════════════════════╗
211
+ ║ RalphBlaster Agent Starting... ║
212
+ ╚═══════════════════════════════════════╝
213
+
214
+ [2026-01-16T20:00:00.123Z] [INFO] RalphBlaster Agent starting...
215
+ [2026-01-16T20:00:00.124Z] [INFO] API URL: https://ralphblaster.com
216
+ [2026-01-16T20:00:00.125Z] [INFO] Poll interval: 5000ms
217
+ [2026-01-16T20:00:05.234Z] [INFO] Claimed job #42 - Implement user authentication
218
+ [2026-01-16T20:00:05.345Z] [INFO] Job #42 marked as running
219
+ [2026-01-16T20:00:05.456Z] [INFO] Executing job #42 in /path/to/project
220
+ [2026-01-16T20:05:30.789Z] [INFO] Job #42 marked as completed
221
+ [2026-01-16T20:05:30.890Z] [INFO] Job #42 completed successfully
222
+ ```
223
+
224
+ ## Graceful Shutdown
225
+
226
+ The agent handles shutdown signals gracefully:
227
+
228
+ - `SIGINT` (Ctrl+C): Marks current job as failed and exits
229
+ - `SIGTERM`: Same as SIGINT
230
+ - Uncaught exceptions: Logged and triggers shutdown
231
+
232
+ ## Troubleshooting
233
+
234
+ ### "API token requires 'ralphblaster_agent' permission"
235
+
236
+ Your API token doesn't have the correct permissions. Create a new token with the `ralphblaster_agent` permission checked.
237
+
238
+ ### "Cannot connect to API"
239
+
240
+ Check that:
241
+ - The API URL is correct
242
+ - The Rails server is running
243
+ - There are no firewall issues
244
+
245
+ ### "Failed to execute Claude CLI"
246
+
247
+ Ensure:
248
+ - Claude CLI is installed (`claude --version`)
249
+ - Claude CLI is in your PATH
250
+ - You're authenticated with Claude
251
+
252
+ ### "Project path does not exist"
253
+
254
+ The project's `system_path` in RalphBlaster is incorrect or the directory doesn't exist on your machine.
255
+
256
+ ## Development
257
+
258
+ ### Running Locally
259
+
260
+ ```bash
261
+ npm start
262
+ ```
263
+
264
+ ### Debugging
265
+
266
+ Enable debug logging:
267
+
268
+ ```bash
269
+ RALPHBLASTER_LOG_LEVEL=debug ralphblaster --token=your_token
270
+ ```
271
+
272
+ ## Architecture
273
+
274
+ ```
275
+ ┌──────────────────────┐ ┌──────────────────┐
276
+ │ RalphBlaster Agent │ │ Rails API │
277
+ │ │ │ │
278
+ │ ┌──────────┐ │ Poll │ ┌────────────┐ │
279
+ │ │ Polling │────────┼────────>│ │ Job Queue │ │
280
+ │ │ Loop │ │ │ └────────────┘ │
281
+ │ └──────────┘ │ │ │
282
+ │ │ │ Claim │ │
283
+ │ ▼ │<────────┤ │
284
+ │ ┌──────────┐ │ │ │
285
+ │ │ Executor │ │ │ │
286
+ │ │ (Claude)│ │ Status │ │
287
+ │ └──────────┘ │────────>│ │
288
+ │ │ │ │
289
+ └──────────────────────┘ └──────────────────┘
290
+ ```
291
+
292
+ ## License
293
+
294
+ MIT
@@ -0,0 +1,168 @@
1
+ #!/bin/bash
2
+ # Ralph Agent Dashboard - Live monitoring of agent activity
3
+
4
+ LOG_DIR="$HOME/.ralph-agent-logs"
5
+ CURRENT_LOG="$LOG_DIR/agent-$(date +%Y%m%d).log"
6
+
7
+ # Colors for terminal output
8
+ RED='\033[0;31m'
9
+ GREEN='\033[0;32m'
10
+ YELLOW='\033[1;33m'
11
+ BLUE='\033[0;34m'
12
+ MAGENTA='\033[0;35m'
13
+ CYAN='\033[0;36m'
14
+ NC='\033[0m' # No Color
15
+ BOLD='\033[1m'
16
+
17
+ # Clear screen and hide cursor
18
+ clear
19
+ tput civis
20
+
21
+ # Restore cursor on exit
22
+ trap 'tput cnorm; exit' INT TERM
23
+
24
+ # Function to draw header
25
+ draw_header() {
26
+ echo -e "${BOLD}${CYAN}╔════════════════════════════════════════════════════════════════╗${NC}"
27
+ echo -e "${BOLD}${CYAN}║${NC} ${BOLD}Ralph Agent Activity Dashboard${NC} ${BOLD}${CYAN}║${NC}"
28
+ echo -e "${BOLD}${CYAN}╚════════════════════════════════════════════════════════════════╝${NC}"
29
+ echo ""
30
+ }
31
+
32
+ # Function to show agent status
33
+ show_agent_status() {
34
+ local pid_file="$LOG_DIR/agent.pid"
35
+
36
+ echo -e "${BOLD}Agent Status:${NC}"
37
+ if [ -f "$pid_file" ]; then
38
+ local pid=$(cat "$pid_file")
39
+ if ps -p "$pid" > /dev/null 2>&1; then
40
+ local uptime=$(ps -p "$pid" -o etime= | tr -d ' ')
41
+ echo -e " ${GREEN}●${NC} Running (PID: ${pid}, Uptime: ${uptime})"
42
+ else
43
+ echo -e " ${RED}●${NC} Not running (stale PID file)"
44
+ fi
45
+ else
46
+ echo -e " ${RED}●${NC} Not running"
47
+ fi
48
+
49
+ # Check for multiple agents
50
+ local all_agents=$(pgrep -f "ralphblaster.js" | wc -l)
51
+ if [ "$all_agents" -gt 1 ]; then
52
+ echo -e " ${YELLOW}⚠${NC} Warning: ${all_agents} agent processes detected!"
53
+ fi
54
+ echo ""
55
+ }
56
+
57
+ # Function to show recent jobs (extracted from logs)
58
+ show_recent_jobs() {
59
+ echo -e "${BOLD}Recent Jobs (last 5):${NC}"
60
+
61
+ if [ ! -f "$CURRENT_LOG" ]; then
62
+ echo " No log file found"
63
+ return
64
+ fi
65
+
66
+ # Extract job claims from logs
67
+ grep "Claimed job" "$CURRENT_LOG" | tail -5 | while read -r line; do
68
+ # Parse job ID and title
69
+ if [[ $line =~ \#([0-9]+)\ -\ (.+)$ ]]; then
70
+ local job_id="${BASH_REMATCH[1]}"
71
+ local job_title="${BASH_REMATCH[2]}"
72
+ local timestamp=$(echo "$line" | grep -oE '\[.*?\]' | head -1 | tr -d '[]')
73
+
74
+ # Check if it's a PRD job
75
+ if grep -q "🔴.*#${job_id}" "$CURRENT_LOG"; then
76
+ echo -e " ${MAGENTA}📄 PRD${NC} Job #${job_id}: ${job_title:0:50}..."
77
+ else
78
+ echo -e " ${BLUE}💻 Code${NC} Job #${job_id}: ${job_title:0:50}..."
79
+ fi
80
+ echo -e " ${timestamp}"
81
+ fi
82
+ done
83
+
84
+ if ! grep -q "Claimed job" "$CURRENT_LOG"; then
85
+ echo " (No jobs processed yet)"
86
+ fi
87
+ echo ""
88
+ }
89
+
90
+ # Function to show live activity
91
+ show_live_activity() {
92
+ echo -e "${BOLD}Live Activity (last 10 seconds):${NC}"
93
+
94
+ if [ ! -f "$CURRENT_LOG" ]; then
95
+ echo " No log file found"
96
+ return
97
+ fi
98
+
99
+ # Get logs from last 10 seconds
100
+ local cutoff=$(date -u -v-10S +"%Y-%m-%dT%H:%M:%S" 2>/dev/null || date -u -d "10 seconds ago" +"%Y-%m-%dT%H:%M:%S")
101
+
102
+ local recent_activity=$(awk -v cutoff="$cutoff" '
103
+ $0 ~ /\[.*\]/ {
104
+ match($0, /\[([^\]]+)\]/, ts)
105
+ if (ts[1] >= cutoff) print
106
+ }
107
+ ' "$CURRENT_LOG" | tail -8)
108
+
109
+ if [ -z "$recent_activity" ]; then
110
+ echo -e " ${YELLOW}⏸${NC} Waiting for jobs..."
111
+ else
112
+ echo "$recent_activity" | while read -r line; do
113
+ # Color-code different activities
114
+ if [[ $line =~ "Claimed job" ]]; then
115
+ echo -e " ${GREEN}→${NC} ${line}"
116
+ elif [[ $line =~ "Executing" ]]; then
117
+ echo -e " ${BLUE}⚙${NC} ${line}"
118
+ elif [[ $line =~ "completed" ]]; then
119
+ echo -e " ${GREEN}✓${NC} ${line}"
120
+ elif [[ $line =~ "failed\|error" ]]; then
121
+ echo -e " ${RED}✗${NC} ${line}"
122
+ else
123
+ echo " ${line}"
124
+ fi
125
+ done
126
+ fi
127
+ echo ""
128
+ }
129
+
130
+ # Function to show statistics
131
+ show_statistics() {
132
+ if [ ! -f "$CURRENT_LOG" ]; then
133
+ return
134
+ fi
135
+
136
+ echo -e "${BOLD}Today's Statistics:${NC}"
137
+
138
+ local total_jobs=$(grep -c "Claimed job" "$CURRENT_LOG" 2>/dev/null || echo 0)
139
+ local prd_jobs=$(grep -c "🔴🔴🔴 PRD" "$CURRENT_LOG" 2>/dev/null || echo 0)
140
+ local code_jobs=$((total_jobs - prd_jobs))
141
+ local completed=$(grep -c "completed successfully" "$CURRENT_LOG" 2>/dev/null || echo 0)
142
+ local errors=$(grep -c -E "failed|ERROR" "$CURRENT_LOG" 2>/dev/null || echo 0)
143
+
144
+ echo " Total jobs: ${total_jobs}"
145
+ echo " ├─ PRD generation: ${prd_jobs}"
146
+ echo " └─ Code execution: ${code_jobs}"
147
+ echo ""
148
+ echo " Completed: ${GREEN}${completed}${NC}"
149
+ echo " Errors: ${RED}${errors}${NC}"
150
+ echo ""
151
+ }
152
+
153
+ # Main dashboard loop
154
+ while true; do
155
+ clear
156
+ draw_header
157
+ show_agent_status
158
+ show_statistics
159
+ show_recent_jobs
160
+ show_live_activity
161
+
162
+ echo -e "${CYAN}Press Ctrl+C to exit${NC}"
163
+ echo ""
164
+ echo -e "Logs: ${CURRENT_LOG}"
165
+ echo -e "Refreshing in 5 seconds..."
166
+
167
+ sleep 5
168
+ done