feat: add RALPH_STATUS block parsing and circuit breaker pattern

Phase 1 Ralph enhancement implementation:
- Parse RALPH_STATUS blocks from Claude output (status, tasks, files, tests)
- Circuit breaker state machine (CLOSED → HALF_OPEN → OPEN) for stuck detection
- Dual-condition exit gate (completion indicators >= 2 AND EXIT_SIGNAL)
- Frontend: circuit breaker badge (yellow warning, red stuck), status block display
- API: circuit breaker reset endpoint, ralph status endpoint
- Notifications when circuit breaker opens or exit gate is met

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
arkon
2026-01-27 00:29:38 +01:00
co-authored by Claude Opus 4.5
parent b896478ca6
commit 11d4666d19
8 changed files with 1699 additions and 1 deletions
+447
View File
@@ -18,7 +18,13 @@ import {
RalphTrackerState,
RalphTodoItem,
RalphTodoStatus,
RalphStatusBlock,
RalphStatusValue,
RalphTestsStatus,
RalphWorkType,
CircuitBreakerStatus,
createInitialRalphTrackerState,
createInitialCircuitBreakerStatus,
} from './types.js';
// ========== Configuration Constants ==========
@@ -220,6 +226,78 @@ const ANSI_ESCAPE_PATTERN = /\x1b\[[0-9;]*[A-Za-z]/g;
/** Maximum number of task number to content mappings to track */
const MAX_TASK_MAPPINGS = 100;
// ---------- RALPH_STATUS Block Patterns ----------
// Based on Ralph Claude Code structured status reporting
/**
* Matches the start of a RALPH_STATUS block
* Pattern: ---RALPH_STATUS---
*/
const RALPH_STATUS_START_PATTERN = /^---RALPH_STATUS---\s*$/;
/**
* Matches the end of a RALPH_STATUS block
* Pattern: ---END_RALPH_STATUS---
*/
const RALPH_STATUS_END_PATTERN = /^---END_RALPH_STATUS---\s*$/;
/**
* Matches STATUS field in RALPH_STATUS block
* Captures: IN_PROGRESS | COMPLETE | BLOCKED
*/
const RALPH_STATUS_FIELD_PATTERN = /^STATUS:\s*(IN_PROGRESS|COMPLETE|BLOCKED)\s*$/i;
/**
* Matches TASKS_COMPLETED_THIS_LOOP field
* Captures: number
*/
const RALPH_TASKS_COMPLETED_PATTERN = /^TASKS_COMPLETED_THIS_LOOP:\s*(\d+)\s*$/i;
/**
* Matches FILES_MODIFIED field
* Captures: number
*/
const RALPH_FILES_MODIFIED_PATTERN = /^FILES_MODIFIED:\s*(\d+)\s*$/i;
/**
* Matches TESTS_STATUS field
* Captures: PASSING | FAILING | NOT_RUN
*/
const RALPH_TESTS_STATUS_PATTERN = /^TESTS_STATUS:\s*(PASSING|FAILING|NOT_RUN)\s*$/i;
/**
* Matches WORK_TYPE field
* Captures: IMPLEMENTATION | TESTING | DOCUMENTATION | REFACTORING
*/
const RALPH_WORK_TYPE_PATTERN = /^WORK_TYPE:\s*(IMPLEMENTATION|TESTING|DOCUMENTATION|REFACTORING)\s*$/i;
/**
* Matches EXIT_SIGNAL field
* Captures: true | false
*/
const RALPH_EXIT_SIGNAL_PATTERN = /^EXIT_SIGNAL:\s*(true|false)\s*$/i;
/**
* Matches RECOMMENDATION field
* Captures: any text
*/
const RALPH_RECOMMENDATION_PATTERN = /^RECOMMENDATION:\s*(.+)$/i;
// ---------- Completion Indicator Patterns (for dual-condition exit) ----------
/**
* Patterns that indicate potential completion (natural language)
* Count >= 2 along with EXIT_SIGNAL: true triggers exit
*/
const COMPLETION_INDICATOR_PATTERNS = [
/all\s+(?:tasks?|items?|work)\s+(?:are\s+)?(?:completed?|done|finished)/i,
/(?:completed?|finished)\s+all\s+(?:tasks?|items?|work)/i,
/nothing\s+(?:left|remaining)\s+to\s+do/i,
/no\s+more\s+(?:tasks?|items?|work)/i,
/everything\s+(?:is\s+)?(?:completed?|done)/i,
/project\s+(?:is\s+)?(?:completed?|done|finished)/i,
];
// ========== Event Types ==========
/**
@@ -228,6 +306,9 @@ const MAX_TASK_MAPPINGS = 100;
* @event todoUpdate - Fired when todo list changes (items added, status changed)
* @event completionDetected - Fired when completion phrase is detected (task complete)
* @event enabled - Fired when tracker auto-enables due to Ralph pattern detection
* @event statusBlockDetected - Fired when a RALPH_STATUS block is parsed
* @event circuitBreakerUpdate - Fired when circuit breaker state changes
* @event exitGateMet - Fired when dual-condition exit gate is met
*/
export interface RalphTrackerEvents {
/** Emitted when loop state changes */
@@ -238,6 +319,12 @@ export interface RalphTrackerEvents {
completionDetected: (phrase: string) => void;
/** Emitted when tracker auto-enables from disabled state */
enabled: () => void;
/** Emitted when a RALPH_STATUS block is parsed */
statusBlockDetected: (block: RalphStatusBlock) => void;
/** Emitted when circuit breaker state changes */
circuitBreakerUpdate: (status: CircuitBreakerStatus) => void;
/** Emitted when dual-condition exit gate is met (completion indicators >= 2 AND EXIT_SIGNAL: true) */
exitGateMet: (data: { completionIndicators: number; exitSignal: boolean }) => void;
}
/**
@@ -315,6 +402,32 @@ export class RalphTracker extends EventEmitter {
/** Maps task numbers from "✔ Task #N" format to their content for status updates */
private _taskNumberToContent: Map<number, string> = new Map();
// ========== RALPH_STATUS Block State ==========
/** Circuit breaker state tracking */
private _circuitBreaker: CircuitBreakerStatus;
/** Buffer for RALPH_STATUS block lines */
private _statusBlockBuffer: string[] = [];
/** Flag indicating we're inside a RALPH_STATUS block */
private _inStatusBlock: boolean = false;
/** Last parsed RALPH_STATUS block */
private _lastStatusBlock: RalphStatusBlock | null = null;
/** Count of completion indicators detected (for dual-condition exit) */
private _completionIndicators: number = 0;
/** Whether dual-condition exit gate has been met */
private _exitGateMet: boolean = false;
/** Cumulative files modified across all iterations */
private _totalFilesModified: number = 0;
/** Cumulative tasks completed across all iterations */
private _totalTasksCompleted: number = 0;
/**
* Creates a new RalphTracker instance.
* Starts in disabled state until Ralph patterns are detected.
@@ -322,6 +435,7 @@ export class RalphTracker extends EventEmitter {
constructor() {
super();
this._loopState = createInitialRalphTrackerState();
this._circuitBreaker = createInitialCircuitBreakerStatus();
}
/**
@@ -411,6 +525,15 @@ export class RalphTracker extends EventEmitter {
this._completionPhraseCount.clear();
this._taskNumberToContent.clear();
this._lineBuffer = '';
// Reset RALPH_STATUS block state
this._statusBlockBuffer = [];
this._inStatusBlock = false;
this._lastStatusBlock = null;
this._completionIndicators = 0;
this._exitGateMet = false;
this._totalFilesModified = 0;
this._totalTasksCompleted = 0;
// Keep circuit breaker state on soft reset (it tracks across iterations)
// Emit immediately on reset (no debounce)
this.emit('loopUpdate', this.loopState);
this.emit('todoUpdate', this.todos);
@@ -432,6 +555,15 @@ export class RalphTracker extends EventEmitter {
this._completionPhraseCount.clear();
this._taskNumberToContent.clear();
this._lineBuffer = '';
// Reset all RALPH_STATUS block and circuit breaker state
this._statusBlockBuffer = [];
this._inStatusBlock = false;
this._lastStatusBlock = null;
this._completionIndicators = 0;
this._exitGateMet = false;
this._totalFilesModified = 0;
this._totalTasksCompleted = 0;
this._circuitBreaker = createInitialCircuitBreakerStatus();
// Emit immediately on reset (no debounce)
this.emit('loopUpdate', this.loopState);
this.emit('todoUpdate', this.todos);
@@ -689,6 +821,12 @@ export class RalphTracker extends EventEmitter {
const trimmed = line.trim();
if (!trimmed) return;
// Check for RALPH_STATUS block (structured status reporting)
this.processStatusBlockLine(trimmed);
// Check for completion indicators (for dual-condition exit gate)
this.detectCompletionIndicators(trimmed);
// Check for completion phrase
this.detectCompletionPhrase(trimmed);
@@ -1493,6 +1631,15 @@ export class RalphTracker extends EventEmitter {
this._taskNumberToContent.clear();
this._lineBuffer = '';
this._completionPhraseCount.clear();
// Clear RALPH_STATUS block and circuit breaker state
this._statusBlockBuffer = [];
this._inStatusBlock = false;
this._lastStatusBlock = null;
this._completionIndicators = 0;
this._exitGateMet = false;
this._totalFilesModified = 0;
this._totalTasksCompleted = 0;
this._circuitBreaker = createInitialCircuitBreakerStatus();
this.emit('loopUpdate', this.loopState);
this.emit('todoUpdate', this.todos);
}
@@ -1555,4 +1702,304 @@ export class RalphTracker extends EventEmitter {
this._todos.set(todo.id, { ...todo });
}
}
// ========== RALPH_STATUS Block Detection ==========
/**
* Process a line for RALPH_STATUS block detection.
* Buffers lines between ---RALPH_STATUS--- and ---END_RALPH_STATUS---
* then parses the complete block.
*
* @param line - Single line to process (already trimmed)
* @fires statusBlockDetected - When a complete block is parsed
*/
private processStatusBlockLine(line: string): void {
// Check for block start
if (RALPH_STATUS_START_PATTERN.test(line)) {
this._inStatusBlock = true;
this._statusBlockBuffer = [];
return;
}
// Check for block end
if (this._inStatusBlock && RALPH_STATUS_END_PATTERN.test(line)) {
this._inStatusBlock = false;
this.parseStatusBlock(this._statusBlockBuffer);
this._statusBlockBuffer = [];
return;
}
// Buffer lines while in block
if (this._inStatusBlock) {
this._statusBlockBuffer.push(line);
}
}
/**
* Parse buffered RALPH_STATUS block lines into structured data.
*
* @param lines - Array of lines between block markers
* @fires statusBlockDetected - When parsing succeeds
*/
private parseStatusBlock(lines: string[]): void {
const block: Partial<RalphStatusBlock> = {
parsedAt: Date.now(),
};
for (const line of lines) {
// STATUS field
const statusMatch = line.match(RALPH_STATUS_FIELD_PATTERN);
if (statusMatch) {
block.status = statusMatch[1].toUpperCase() as RalphStatusValue;
continue;
}
// TASKS_COMPLETED_THIS_LOOP field
const tasksMatch = line.match(RALPH_TASKS_COMPLETED_PATTERN);
if (tasksMatch) {
block.tasksCompletedThisLoop = parseInt(tasksMatch[1], 10);
continue;
}
// FILES_MODIFIED field
const filesMatch = line.match(RALPH_FILES_MODIFIED_PATTERN);
if (filesMatch) {
block.filesModified = parseInt(filesMatch[1], 10);
continue;
}
// TESTS_STATUS field
const testsMatch = line.match(RALPH_TESTS_STATUS_PATTERN);
if (testsMatch) {
block.testsStatus = testsMatch[1].toUpperCase() as RalphTestsStatus;
continue;
}
// WORK_TYPE field
const workMatch = line.match(RALPH_WORK_TYPE_PATTERN);
if (workMatch) {
block.workType = workMatch[1].toUpperCase() as RalphWorkType;
continue;
}
// EXIT_SIGNAL field
const exitMatch = line.match(RALPH_EXIT_SIGNAL_PATTERN);
if (exitMatch) {
block.exitSignal = exitMatch[1].toLowerCase() === 'true';
continue;
}
// RECOMMENDATION field
const recMatch = line.match(RALPH_RECOMMENDATION_PATTERN);
if (recMatch) {
block.recommendation = recMatch[1].trim();
continue;
}
}
// Only process if we have at least the STATUS field
if (block.status !== undefined) {
// Fill in defaults for missing fields
const fullBlock: RalphStatusBlock = {
status: block.status,
tasksCompletedThisLoop: block.tasksCompletedThisLoop ?? 0,
filesModified: block.filesModified ?? 0,
testsStatus: block.testsStatus ?? 'NOT_RUN',
workType: block.workType ?? 'IMPLEMENTATION',
exitSignal: block.exitSignal ?? false,
recommendation: block.recommendation ?? '',
parsedAt: block.parsedAt!,
};
this._lastStatusBlock = fullBlock;
this.handleStatusBlock(fullBlock);
}
}
/**
* Handle a parsed RALPH_STATUS block.
* Updates circuit breaker, checks exit conditions.
*
* @param block - Parsed status block
* @fires statusBlockDetected - With the block data
* @fires circuitBreakerUpdate - If state changes
* @fires exitGateMet - If dual-condition exit triggered
*/
private handleStatusBlock(block: RalphStatusBlock): void {
// Auto-enable tracker when we see a status block
if (!this._loopState.enabled && !this._autoEnableDisabled) {
this.enable();
}
// Update cumulative counts
this._totalFilesModified += block.filesModified;
this._totalTasksCompleted += block.tasksCompletedThisLoop;
// Check for progress (for circuit breaker)
const hasProgress = block.filesModified > 0 || block.tasksCompletedThisLoop > 0;
// Update circuit breaker
this.updateCircuitBreaker(hasProgress, block.testsStatus, block.status);
// Check completion indicators
if (block.status === 'COMPLETE') {
this._completionIndicators++;
}
// Check dual-condition exit gate
if (block.exitSignal && this._completionIndicators >= 2 && !this._exitGateMet) {
this._exitGateMet = true;
this.emit('exitGateMet', {
completionIndicators: this._completionIndicators,
exitSignal: true,
});
}
// Update loop state
this._loopState.lastActivity = Date.now();
// Emit the status block
this.emit('statusBlockDetected', block);
this.emitLoopUpdateDebounced();
}
// ========== Circuit Breaker ==========
/**
* Update circuit breaker state based on iteration results.
*
* @param hasProgress - Whether this iteration made progress
* @param testsStatus - Current test status
* @param status - Overall status from RALPH_STATUS
* @fires circuitBreakerUpdate - If state changes
*/
private updateCircuitBreaker(
hasProgress: boolean,
testsStatus: RalphTestsStatus,
status: RalphStatusValue
): void {
const prevState = this._circuitBreaker.state;
if (hasProgress) {
// Progress detected - reset counters, possibly close circuit
this._circuitBreaker.consecutiveNoProgress = 0;
this._circuitBreaker.consecutiveSameError = 0;
this._circuitBreaker.lastProgressIteration = this._loopState.cycleCount;
if (this._circuitBreaker.state === 'HALF_OPEN') {
this._circuitBreaker.state = 'CLOSED';
this._circuitBreaker.reason = 'Progress detected, circuit closed';
this._circuitBreaker.reasonCode = 'progress_detected';
}
} else {
// No progress
this._circuitBreaker.consecutiveNoProgress++;
// State transitions based on consecutive no-progress
if (this._circuitBreaker.state === 'CLOSED') {
if (this._circuitBreaker.consecutiveNoProgress >= 3) {
this._circuitBreaker.state = 'OPEN';
this._circuitBreaker.reason = `No progress for ${this._circuitBreaker.consecutiveNoProgress} iterations`;
this._circuitBreaker.reasonCode = 'no_progress_open';
} else if (this._circuitBreaker.consecutiveNoProgress >= 2) {
this._circuitBreaker.state = 'HALF_OPEN';
this._circuitBreaker.reason = 'Warning: no progress detected';
this._circuitBreaker.reasonCode = 'no_progress_warning';
}
} else if (this._circuitBreaker.state === 'HALF_OPEN') {
if (this._circuitBreaker.consecutiveNoProgress >= 3) {
this._circuitBreaker.state = 'OPEN';
this._circuitBreaker.reason = `No progress for ${this._circuitBreaker.consecutiveNoProgress} iterations`;
this._circuitBreaker.reasonCode = 'no_progress_open';
}
}
}
// Track tests failure
if (testsStatus === 'FAILING') {
this._circuitBreaker.consecutiveTestsFailure++;
if (this._circuitBreaker.consecutiveTestsFailure >= 5 && this._circuitBreaker.state !== 'OPEN') {
this._circuitBreaker.state = 'OPEN';
this._circuitBreaker.reason = `Tests failing for ${this._circuitBreaker.consecutiveTestsFailure} iterations`;
this._circuitBreaker.reasonCode = 'tests_failing_too_long';
}
} else {
this._circuitBreaker.consecutiveTestsFailure = 0;
}
// Track blocked status
if (status === 'BLOCKED' && this._circuitBreaker.state !== 'OPEN') {
this._circuitBreaker.state = 'OPEN';
this._circuitBreaker.reason = 'Claude reported BLOCKED status';
this._circuitBreaker.reasonCode = 'same_error_repeated';
}
// Emit if state changed
if (prevState !== this._circuitBreaker.state) {
this._circuitBreaker.lastTransitionAt = Date.now();
this.emit('circuitBreakerUpdate', { ...this._circuitBreaker });
}
}
/**
* Manually reset circuit breaker to CLOSED state.
* Use when user acknowledges the issue is resolved.
*
* @fires circuitBreakerUpdate
*/
resetCircuitBreaker(): void {
this._circuitBreaker = createInitialCircuitBreakerStatus();
this._circuitBreaker.reason = 'Manual reset';
this._circuitBreaker.reasonCode = 'manual_reset';
this.emit('circuitBreakerUpdate', { ...this._circuitBreaker });
}
/**
* Get current circuit breaker status.
*/
get circuitBreakerStatus(): CircuitBreakerStatus {
return { ...this._circuitBreaker };
}
/**
* Get last parsed RALPH_STATUS block.
*/
get lastStatusBlock(): RalphStatusBlock | null {
return this._lastStatusBlock ? { ...this._lastStatusBlock } : null;
}
/**
* Get cumulative stats from status blocks.
*/
get cumulativeStats(): { filesModified: number; tasksCompleted: number; completionIndicators: number } {
return {
filesModified: this._totalFilesModified,
tasksCompleted: this._totalTasksCompleted,
completionIndicators: this._completionIndicators,
};
}
/**
* Whether dual-condition exit gate has been met.
*/
get exitGateMet(): boolean {
return this._exitGateMet;
}
// ========== Completion Indicator Detection ==========
/**
* Check line for completion indicators (natural language patterns).
* Used for dual-condition exit gate.
*
* @param line - Line to check
*/
private detectCompletionIndicators(line: string): void {
for (const pattern of COMPLETION_INDICATOR_PATTERNS) {
if (pattern.test(line)) {
this._completionIndicators++;
break; // Only count once per line
}
}
}
}