Complete Ralph to Loop rename across entire codebase

Rename all Ralph references to Loop including types, services, hooks,
filenames, KV keys, API routes, frontend components, tests, and docs.

Key changes:
- Types: RalphState → LoopState, RalphConfig → LoopConfig
- Services: ralph.ts → loop.ts with worktree field (inverted from inPlace)
- KV keys: ralph: → loop:, ralph-session: → loop-session:
- API routes: /ralph/* → /loop/*
- Frontend: useLoopStatus, RepoLoopList, getLoopStatus, cancelLoop
- Config backward compatibility: accepts both loop and ralph (prefers loop)
- Automatic KV migration on plugin startup
- memory-plan-execute keeps inPlace parameter (different semantics)

Fixes critical bugs found in code review:
- Backend /loop/cancel route using wrong ralph: KV prefix
- Frontend error messages still referencing Ralph
- Log message consistency
This commit is contained in:
Chris Scott committed 2026-03-27 14:45:54 -04:00
1 parent 00489d9901
commit 2c4a9c9257
31 files changed
+789 -745

No files matched your search

+29 -29
View File
@@ -4,7 +4,7 @@ import { existsSync } from 'fs'
import { join } from 'path'
import { mkdtempSync, rmSync } from 'fs'
interface RalphState {
interface LoopState {
sessionId: string
worktreeName: string
worktreeBranch: string
@@ -42,13 +42,13 @@ function createTestKvDb(tempDir: string): Database {
return db
}
function insertRalphState(db: Database, projectId: string, worktreeName: string, state: Partial<RalphState>): void {
const defaultState: RalphState = {
function insertLoopState(db: Database, projectId: string, worktreeName: string, state: Partial<LoopState>): void {
const defaultState: LoopState = {
sessionId: 'test-session-id',
worktreeName,
worktreeBranch: 'main',
worktreeDir: '/tmp/test-worktree',
inPlace: false,
worktree: true,
iteration: 1,
maxIterations: 10,
phase: 'coding',
@@ -66,7 +66,7 @@ function insertRalphState(db: Database, projectId: string, worktreeName: string,
db.run(
'INSERT OR REPLACE INTO project_kv (project_id, key, data, expires_at, updated_at) VALUES (?, ?, ?, ?, ?)',
[projectId, `ralph:${worktreeName}`, data, expiresAt, now]
[projectId, `loop:${worktreeName}`, data, expiresAt, now]
)
}
@@ -104,12 +104,12 @@ describe('CLI Cancel', () => {
})
const output = outputLines.join('\n')
expect(output).toContain('No active Ralph loops')
expect(output).toContain('No active memory loops')
})
test('shows no active loops when all are inactive', async () => {
const db = createTestKvDb(tempDir)
insertRalphState(db, 'test-project', 'inactive-worktree', {
insertLoopState(db, 'test-project', 'inactive-worktree', {
active: false,
completedAt: new Date().toISOString(),
})
@@ -126,12 +126,12 @@ describe('CLI Cancel', () => {
})
const output = outputLines.join('\n')
expect(output).toContain('No active Ralph loops')
expect(output).toContain('No active memory loops')
})
test('auto-selects single active loop with force', async () => {
const db = createTestKvDb(tempDir)
insertRalphState(db, 'test-project', 'single-loop', {})
insertLoopState(db, 'test-project', 'single-loop', {})
db.close()
const outputLines: string[] = []
@@ -145,8 +145,8 @@ describe('CLI Cancel', () => {
})
const db2 = new Database(join(tempDir, 'memory.db'))
const row = db2.prepare('SELECT data FROM project_kv WHERE key = ?').get('ralph:single-loop') as { data: string }
const state = JSON.parse(row.data) as RalphState
const row = db2.prepare('SELECT data FROM project_kv WHERE key = ?').get('loop:single-loop') as { data: string }
const state = JSON.parse(row.data) as LoopState
db2.close()
expect(state.active).toBe(false)
@@ -156,7 +156,7 @@ describe('CLI Cancel', () => {
test('cancellation sets correct state fields', async () => {
const db = createTestKvDb(tempDir)
insertRalphState(db, 'test-project', 'test-loop', {})
insertLoopState(db, 'test-project', 'test-loop', {})
db.close()
const beforeCancel = new Date()
@@ -168,8 +168,8 @@ describe('CLI Cancel', () => {
})
const db2 = new Database(join(tempDir, 'memory.db'))
const row = db2.prepare('SELECT data FROM project_kv WHERE key = ?').get('ralph:test-loop') as { data: string }
const state = JSON.parse(row.data) as RalphState
const row = db2.prepare('SELECT data FROM project_kv WHERE key = ?').get('loop:test-loop') as { data: string }
const state = JSON.parse(row.data) as LoopState
db2.close()
expect(state.active).toBe(false)
@@ -180,8 +180,8 @@ describe('CLI Cancel', () => {
test('lists active loops when multiple exist and no name given', async () => {
const db = createTestKvDb(tempDir)
insertRalphState(db, 'test-project', 'loop-one', {})
insertRalphState(db, 'test-project', 'loop-two', {})
insertLoopState(db, 'test-project', 'loop-one', {})
insertLoopState(db, 'test-project', 'loop-two', {})
db.close()
const outputLines: string[] = []
@@ -208,15 +208,15 @@ describe('CLI Cancel', () => {
expect(exited).toBe(true)
const output = outputLines.join('\n')
expect(output).toContain('Multiple active Ralph loops')
expect(output).toContain('Multiple active memory loops')
expect(output).toContain('loop-one')
expect(output).toContain('loop-two')
})
test('finds loop by name when multiple active', async () => {
const db = createTestKvDb(tempDir)
insertRalphState(db, 'test-project', 'loop-alpha', {})
insertRalphState(db, 'test-project', 'loop-beta', {})
insertLoopState(db, 'test-project', 'loop-alpha', {})
insertLoopState(db, 'test-project', 'loop-beta', {})
db.close()
const outputLines: string[] = []
@@ -231,10 +231,10 @@ describe('CLI Cancel', () => {
})
const db2 = new Database(join(tempDir, 'memory.db'))
const alphaRow = db2.prepare('SELECT data FROM project_kv WHERE key = ?').get('ralph:loop-alpha') as { data: string }
const betaRow = db2.prepare('SELECT data FROM project_kv WHERE key = ?').get('ralph:loop-beta') as { data: string }
const alphaState = JSON.parse(alphaRow.data) as RalphState
const betaState = JSON.parse(betaRow.data) as RalphState
const alphaRow = db2.prepare('SELECT data FROM project_kv WHERE key = ?').get('loop:loop-alpha') as { data: string }
const betaRow = db2.prepare('SELECT data FROM project_kv WHERE key = ?').get('loop:loop-beta') as { data: string }
const alphaState = JSON.parse(alphaRow.data) as LoopState
const betaState = JSON.parse(betaRow.data) as LoopState
db2.close()
expect(alphaState.active).toBe(true)
@@ -244,8 +244,8 @@ describe('CLI Cancel', () => {
test('partial name matches single loop proceeds with cancel', async () => {
const db = createTestKvDb(tempDir)
insertRalphState(db, 'test-project', 'ralph-feat-auth', {})
insertRalphState(db, 'test-project', 'ralph-fix-bug', {})
insertLoopState(db, 'test-project', 'ralph-feat-auth', {})
insertLoopState(db, 'test-project', 'ralph-fix-bug', {})
db.close()
const outputLines: string[] = []
@@ -260,8 +260,8 @@ describe('CLI Cancel', () => {
})
const db2 = new Database(join(tempDir, 'memory.db'))
const authRow = db2.prepare('SELECT data FROM project_kv WHERE key = ?').get('ralph:ralph-feat-auth') as { data: string }
const authState = JSON.parse(authRow.data) as RalphState
const authRow = db2.prepare('SELECT data FROM project_kv WHERE key = ?').get('loop:ralph-feat-auth') as { data: string }
const authState = JSON.parse(authRow.data) as LoopState
db2.close()
expect(authState.active).toBe(false)
@@ -270,8 +270,8 @@ describe('CLI Cancel', () => {
test('partial name matches multiple loops lists ambiguous and exits', async () => {
const db = createTestKvDb(tempDir)
insertRalphState(db, 'test-project', 'ralph-feat-auth', {})
insertRalphState(db, 'test-project', 'ralph-auth-fix', {})
insertLoopState(db, 'test-project', 'ralph-feat-auth', {})
insertLoopState(db, 'test-project', 'ralph-auth-fix', {})
db.close()
const outputLines: string[] = []
+38 -38
View File
@@ -4,7 +4,7 @@ import { existsSync } from 'fs'
import { join } from 'path'
import { mkdtempSync, rmSync } from 'fs'
interface RalphState {
interface LoopState {
sessionId: string
worktreeName: string
worktreeBranch: string
@@ -42,13 +42,13 @@ function createTestKvDb(tempDir: string): Database {
return db
}
function insertRalphState(db: Database, projectId: string, worktreeName: string, state: Partial<RalphState>): void {
const defaultState: RalphState = {
function insertLoopState(db: Database, projectId: string, worktreeName: string, state: Partial<LoopState>): void {
const defaultState: LoopState = {
sessionId: 'test-session-id',
worktreeName,
worktreeBranch: 'main',
worktreeDir: '/tmp/test-worktree',
inPlace: false,
worktree: true,
iteration: 1,
maxIterations: 10,
phase: 'coding',
@@ -66,7 +66,7 @@ function insertRalphState(db: Database, projectId: string, worktreeName: string,
db.run(
'INSERT OR REPLACE INTO project_kv (project_id, key, data, expires_at, updated_at) VALUES (?, ?, ?, ?, ?)',
[projectId, `ralph:${worktreeName}`, data, expiresAt, now]
[projectId, `loop:${worktreeName}`, data, expiresAt, now]
)
}
@@ -88,8 +88,8 @@ describe('CLI Status - list-worktrees', () => {
test('lists active worktree names', async () => {
const db = createTestKvDb(tempDir)
insertRalphState(db, 'test-project', 'worktree-one', {})
insertRalphState(db, 'test-project', 'worktree-two', {})
insertLoopState(db, 'test-project', 'worktree-one', {})
insertLoopState(db, 'test-project', 'worktree-two', {})
db.close()
const outputLines: string[] = []
@@ -113,12 +113,12 @@ describe('CLI Status - list-worktrees', () => {
const now = Date.now()
const expiredAt = now - 86400000
const expiredState: RalphState = {
const expiredState: LoopState = {
sessionId: 'test-session',
worktreeName: 'expired-worktree',
worktreeBranch: 'main',
worktreeDir: '/tmp/test',
inPlace: false,
worktree: true,
iteration: 1,
maxIterations: 10,
phase: 'coding',
@@ -131,7 +131,7 @@ describe('CLI Status - list-worktrees', () => {
db2.run(
'INSERT INTO project_kv (project_id, key, data, expires_at, updated_at) VALUES (?, ?, ?, ?, ?)',
['test-project', 'ralph:expired-worktree', JSON.stringify(expiredState), expiredAt, now]
['test-project', 'loop:expired-worktree', JSON.stringify(expiredState), expiredAt, now]
)
db2.close()
@@ -151,7 +151,7 @@ describe('CLI Status - list-worktrees', () => {
test('includes inactive loops in list', async () => {
const db = createTestKvDb(tempDir)
insertRalphState(db, 'test-project', 'inactive-worktree', { active: false, completedAt: new Date().toISOString() })
insertLoopState(db, 'test-project', 'inactive-worktree', { active: false, completedAt: new Date().toISOString() })
db.close()
const outputLines: string[] = []
@@ -190,8 +190,8 @@ describe('CLI Status - summary', () => {
test('shows active loops when no name given', async () => {
const db = createTestKvDb(tempDir)
insertRalphState(db, 'test-project', 'active-one', { startedAt: new Date(Date.now() - 3600000).toISOString() })
insertRalphState(db, 'test-project', 'active-two', { startedAt: new Date(Date.now() - 1800000).toISOString() })
insertLoopState(db, 'test-project', 'active-one', { startedAt: new Date(Date.now() - 3600000).toISOString() })
insertLoopState(db, 'test-project', 'active-two', { startedAt: new Date(Date.now() - 1800000).toISOString() })
db.close()
const outputLines: string[] = []
@@ -205,7 +205,7 @@ describe('CLI Status - summary', () => {
})
const output = outputLines.join('\n')
expect(output).toContain('Active Ralph Loops:')
expect(output).toContain('Active Memory Loops:')
expect(output).toContain('active-one')
expect(output).toContain('active-two')
})
@@ -225,12 +225,12 @@ describe('CLI Status - summary', () => {
})
const output = outputLines.join('\n')
expect(output).toContain('No Ralph loops found')
expect(output).toContain('No memory loops found')
})
test('shows recently completed loops', async () => {
const db = createTestKvDb(tempDir)
insertRalphState(db, 'test-project', 'completed-one', {
insertLoopState(db, 'test-project', 'completed-one', {
active: false,
completedAt: new Date().toISOString(),
terminationReason: 'success',
@@ -274,10 +274,10 @@ describe('CLI Status - partial matching', () => {
test('partial name matches single active loop', async () => {
const db = createTestKvDb(tempDir)
insertRalphState(db, 'test-project', 'ralph-feat-auth', {
insertLoopState(db, 'test-project', 'ralph-feat-auth', {
startedAt: new Date(Date.now() - 3600000).toISOString(),
})
insertRalphState(db, 'test-project', 'ralph-fix-bug', {
insertLoopState(db, 'test-project', 'ralph-fix-bug', {
startedAt: new Date(Date.now() - 1800000).toISOString(),
})
db.close()
@@ -294,17 +294,17 @@ describe('CLI Status - partial matching', () => {
})
const output = outputLines.join('\n')
expect(output).toContain('Ralph Loop: ralph-feat-auth')
expect(output).toContain('Memory Loop: ralph-feat-auth')
})
test('partial name matches single recent loop', async () => {
const db = createTestKvDb(tempDir)
insertRalphState(db, 'test-project', 'ralph-completed-auth', {
insertLoopState(db, 'test-project', 'ralph-completed-auth', {
active: false,
completedAt: new Date().toISOString(),
terminationReason: 'success',
})
insertRalphState(db, 'test-project', 'ralph-fix-bug', {
insertLoopState(db, 'test-project', 'ralph-fix-bug', {
active: true,
startedAt: new Date(Date.now() - 1800000).toISOString(),
})
@@ -322,13 +322,13 @@ describe('CLI Status - partial matching', () => {
})
const output = outputLines.join('\n')
expect(output).toContain('Ralph Loop (Completed): ralph-completed-auth')
expect(output).toContain('Memory Loop (Completed): ralph-completed-auth')
})
test('partial name matches multiple loops lists ambiguous', async () => {
const db = createTestKvDb(tempDir)
insertRalphState(db, 'test-project', 'ralph-feat-auth', {})
insertRalphState(db, 'test-project', 'ralph-auth-fix', {})
insertLoopState(db, 'test-project', 'ralph-feat-auth', {})
insertLoopState(db, 'test-project', 'ralph-auth-fix', {})
db.close()
const outputLines: string[] = []
@@ -363,11 +363,11 @@ describe('CLI Status - partial matching', () => {
test('partial name matches via worktreeBranch field', async () => {
const db = createTestKvDb(tempDir)
insertRalphState(db, 'test-project', 'ralph-feat-auth', {
insertLoopState(db, 'test-project', 'ralph-feat-auth', {
worktreeBranch: 'feat/auth',
startedAt: new Date(Date.now() - 3600000).toISOString(),
})
insertRalphState(db, 'test-project', 'ralph-fix-bug', {
insertLoopState(db, 'test-project', 'ralph-fix-bug', {
worktreeBranch: 'fix/bug',
startedAt: new Date(Date.now() - 1800000).toISOString(),
})
@@ -385,13 +385,13 @@ describe('CLI Status - partial matching', () => {
})
const output = outputLines.join('\n')
expect(output).toContain('Ralph Loop: ralph-feat-auth')
expect(output).toContain('Memory Loop: ralph-feat-auth')
expect(output).toContain('Branch: feat/auth')
})
test('case-insensitive matching works', async () => {
const db = createTestKvDb(tempDir)
insertRalphState(db, 'test-project', 'ralph-feat-auth', {
insertLoopState(db, 'test-project', 'ralph-feat-auth', {
startedAt: new Date(Date.now() - 3600000).toISOString(),
})
db.close()
@@ -408,15 +408,15 @@ describe('CLI Status - partial matching', () => {
})
const output = outputLines.join('\n')
expect(output).toContain('Ralph Loop: ralph-feat-auth')
expect(output).toContain('Memory Loop: ralph-feat-auth')
})
test('exact match takes priority over partial', async () => {
const db = createTestKvDb(tempDir)
insertRalphState(db, 'test-project', 'auth', {
insertLoopState(db, 'test-project', 'auth', {
startedAt: new Date(Date.now() - 3600000).toISOString(),
})
insertRalphState(db, 'test-project', 'ralph-auth', {
insertLoopState(db, 'test-project', 'ralph-auth', {
startedAt: new Date(Date.now() - 1800000).toISOString(),
})
db.close()
@@ -433,15 +433,15 @@ describe('CLI Status - partial matching', () => {
})
const output = outputLines.join('\n')
expect(output).toContain('Ralph Loop: auth')
expect(output).not.toContain('Ralph Loop: ralph-auth')
expect(output).toContain('Memory Loop: auth')
expect(output).not.toContain('Memory Loop: ralph-auth')
})
test('--list-worktrees with filter returns filtered results', async () => {
const db = createTestKvDb(tempDir)
insertRalphState(db, 'test-project', 'ralph-feat-auth', { worktreeBranch: 'feat/auth' })
insertRalphState(db, 'test-project', 'ralph-fix-bug', { worktreeBranch: 'fix/bug' })
insertRalphState(db, 'test-project', 'ralph-update-deps', {})
insertLoopState(db, 'test-project', 'ralph-feat-auth', { worktreeBranch: 'feat/auth' })
insertLoopState(db, 'test-project', 'ralph-fix-bug', { worktreeBranch: 'fix/bug' })
insertLoopState(db, 'test-project', 'ralph-update-deps', {})
db.close()
const outputLines: string[] = []
@@ -464,8 +464,8 @@ describe('CLI Status - partial matching', () => {
test('--list-worktrees without filter returns all', async () => {
const db = createTestKvDb(tempDir)
insertRalphState(db, 'test-project', 'ralph-feat-auth', {})
insertRalphState(db, 'test-project', 'ralph-fix-bug', {})
insertLoopState(db, 'test-project', 'ralph-feat-auth', {})
insertLoopState(db, 'test-project', 'ralph-fix-bug', {})
db.close()
const outputLines: string[] = []
@@ -1,6 +1,6 @@
import { describe, test, expect } from 'bun:test'
import { formatTokens, formatSessionOutput, formatAuditResult } from '../src/utils/ralph-format'
import type { RalphSessionOutput } from '../src/services/ralph'
import { formatTokens, formatSessionOutput, formatAuditResult } from '../src/utils/loop-format'
import type { LoopSessionOutput } from '../src/services/ralph'
describe('formatTokens', () => {
test('numbers less than 1000 returned as string', () => {
@@ -27,7 +27,7 @@ describe('formatTokens', () => {
describe('formatSessionOutput', () => {
test('includes cost string with dollar prefix', () => {
const sessionOutput: RalphSessionOutput = {
const sessionOutput: LoopSessionOutput = {
totalCost: 0.0123,
totalTokens: {
input: 1000,
@@ -45,7 +45,7 @@ describe('formatSessionOutput', () => {
})
test('includes token breakdown', () => {
const sessionOutput: RalphSessionOutput = {
const sessionOutput: LoopSessionOutput = {
totalCost: 0.01,
totalTokens: {
input: 1500,
@@ -67,7 +67,7 @@ describe('formatSessionOutput', () => {
})
test('includes file changes when present', () => {
const sessionOutput: RalphSessionOutput = {
const sessionOutput: LoopSessionOutput = {
totalCost: 0.01,
totalTokens: {
input: 100,
@@ -89,7 +89,7 @@ describe('formatSessionOutput', () => {
})
test('omits file changes line when not present', () => {
const sessionOutput: RalphSessionOutput = {
const sessionOutput: LoopSessionOutput = {
totalCost: 0.01,
totalTokens: {
input: 100,
@@ -108,7 +108,7 @@ describe('formatSessionOutput', () => {
})
test('includes recent activity messages', () => {
const sessionOutput: RalphSessionOutput = {
const sessionOutput: LoopSessionOutput = {
totalCost: 0.01,
totalTokens: {
input: 100,
@@ -131,7 +131,7 @@ describe('formatSessionOutput', () => {
})
test('handles empty messages array', () => {
const sessionOutput: RalphSessionOutput = {
const sessionOutput: LoopSessionOutput = {
totalCost: 0.01,
totalTokens: {
input: 100,
@@ -151,7 +151,7 @@ describe('formatSessionOutput', () => {
test('truncates long message text', () => {
const longMessage = 'a'.repeat(250)
const sessionOutput: RalphSessionOutput = {
const sessionOutput: LoopSessionOutput = {
totalCost: 0.01,
totalTokens: {
input: 100,
@@ -171,7 +171,7 @@ describe('formatSessionOutput', () => {
})
test('handles multiline messages', () => {
const sessionOutput: RalphSessionOutput = {
const sessionOutput: LoopSessionOutput = {
totalCost: 0.01,
totalTokens: {
input: 100,
@@ -2,7 +2,7 @@ import { describe, test, expect, beforeEach, afterEach } from 'bun:test'
import { Database } from 'bun:sqlite'
import { createKvQuery } from '../src/storage/kv-queries'
import { createKvService } from '../src/services/kv'
import { createRalphService } from '../src/services/ralph'
import { createLoopService } from '../src/services/loop'
const TEST_DIR = '/tmp/opencode-manager-ralph-test-' + Date.now()
@@ -31,16 +31,16 @@ function createMockLogger() {
}
}
describe('RalphService', () => {
describe('LoopService', () => {
let db: Database
let kvService: ReturnType<typeof createKvService>
let ralphService: ReturnType<typeof createRalphService>
let loopService: ReturnType<typeof createLoopService>
const projectId = 'test-project'
beforeEach(() => {
db = createTestDb()
kvService = createKvService(db)
ralphService = createRalphService(kvService, projectId, createMockLogger())
loopService = createLoopService(kvService, projectId, createMockLogger())
})
afterEach(() => {
@@ -66,16 +66,16 @@ describe('RalphService', () => {
auditCount: 0,
}
ralphService.setState('session-123', state)
const retrieved = ralphService.getActiveState('session-123')
loopService.setState('session-123', state)
const retrieved = loopService.getActiveState('session-123')
expect(retrieved).toEqual(state)
ralphService.setState('session-123', { ...state, iteration: 2 })
const updated = ralphService.getActiveState('session-123')
loopService.setState('session-123', { ...state, iteration: 2 })
const updated = loopService.getActiveState('session-123')
expect(updated?.iteration).toBe(2)
ralphService.deleteState('session-123')
const deleted = ralphService.getActiveState('session-123')
loopService.deleteState('session-123')
const deleted = loopService.getActiveState('session-123')
expect(deleted).toBeNull()
})
@@ -98,45 +98,45 @@ describe('RalphService', () => {
auditCount: 0,
}
ralphService.setState('session-456', inactiveState)
const retrieved = ralphService.getActiveState('session-456')
loopService.setState('session-456', inactiveState)
const retrieved = loopService.getActiveState('session-456')
expect(retrieved).toBeNull()
})
test('getActiveState returns null for non-existent session', () => {
const retrieved = ralphService.getActiveState('non-existent')
const retrieved = loopService.getActiveState('non-existent')
expect(retrieved).toBeNull()
})
test('checkCompletionPromise matches exact promise', () => {
const text = 'Some response text <promise>DONE</promise> more text'
expect(ralphService.checkCompletionPromise(text, 'DONE')).toBe(true)
expect(loopService.checkCompletionPromise(text, 'DONE')).toBe(true)
})
test('checkCompletionPromise returns false when no promise tags', () => {
const text = 'Some response text without promise tags'
expect(ralphService.checkCompletionPromise(text, 'DONE')).toBe(false)
expect(loopService.checkCompletionPromise(text, 'DONE')).toBe(false)
})
test('checkCompletionPromise returns false when promise does not match', () => {
const text = 'Some response <promise>NOT_DONE</promise> text'
expect(ralphService.checkCompletionPromise(text, 'DONE')).toBe(false)
expect(loopService.checkCompletionPromise(text, 'DONE')).toBe(false)
})
test('checkCompletionPromise handles whitespace normalization', () => {
const text = 'Response <promise> DONE WITH SPACES </promise> text'
expect(ralphService.checkCompletionPromise(text, 'DONE WITH SPACES')).toBe(true)
expect(loopService.checkCompletionPromise(text, 'DONE WITH SPACES')).toBe(true)
})
test('checkCompletionPromise matches first promise tag when multiple present', () => {
const text = 'First <promise>FIRST</promise> second <promise>SECOND</promise>'
expect(ralphService.checkCompletionPromise(text, 'FIRST')).toBe(true)
expect(ralphService.checkCompletionPromise(text, 'SECOND')).toBe(false)
expect(loopService.checkCompletionPromise(text, 'FIRST')).toBe(true)
expect(loopService.checkCompletionPromise(text, 'SECOND')).toBe(false)
})
test('checkCompletionPromise handles multiline promise', () => {
const text = 'Response <promise>\n MULTI\n LINE\n</promise> text'
expect(ralphService.checkCompletionPromise(text, 'MULTI LINE')).toBe(true)
expect(loopService.checkCompletionPromise(text, 'MULTI LINE')).toBe(true)
})
test('buildContinuationPrompt includes iteration number', () => {
@@ -158,8 +158,8 @@ describe('RalphService', () => {
auditCount: 0,
}
const prompt = ralphService.buildContinuationPrompt(state)
expect(prompt).toContain('Ralph iteration 3')
const prompt = loopService.buildContinuationPrompt(state)
expect(prompt).toContain('Loop iteration 3')
expect(prompt).toContain('My test prompt')
})
@@ -182,8 +182,8 @@ describe('RalphService', () => {
auditCount: 0,
}
const prompt = ralphService.buildContinuationPrompt(state)
expect(prompt).toContain('[Ralph iteration 1 | To stop: output <promise>COMPLETE_TASK</promise> (ONLY when all requirements are met)]')
const prompt = loopService.buildContinuationPrompt(state)
expect(prompt).toContain('[Loop iteration 1 | To stop: output <promise>COMPLETE_TASK</promise> (ONLY when all requirements are met)]')
})
test('buildContinuationPrompt includes max iterations when no promise', () => {
@@ -205,8 +205,8 @@ describe('RalphService', () => {
auditCount: 0,
}
const prompt = ralphService.buildContinuationPrompt(state)
expect(prompt).toContain('[Ralph iteration 2 / 10]')
const prompt = loopService.buildContinuationPrompt(state)
expect(prompt).toContain('[Loop iteration 2 / 10]')
})
test('buildContinuationPrompt shows unlimited message when no promise and no max', () => {
@@ -228,8 +228,8 @@ describe('RalphService', () => {
auditCount: 0,
}
const prompt = ralphService.buildContinuationPrompt(state)
expect(prompt).toContain('[Ralph iteration 1 | No completion promise set - loop runs until cancelled]')
const prompt = loopService.buildContinuationPrompt(state)
expect(prompt).toContain('[Loop iteration 1 | No completion promise set - loop runs until cancelled]')
})
test('state persists across service recreation', () => {
@@ -251,12 +251,12 @@ describe('RalphService', () => {
auditCount: 0,
}
ralphService.setState('session-persist', state)
loopService.setState('session-persist', state)
const newKvService = createKvService(db)
const newRalphService = createRalphService(newKvService, projectId, createMockLogger())
const newLoopService = createLoopService(newKvService, projectId, createMockLogger())
const retrieved = newRalphService.getActiveState('session-persist')
const retrieved = newLoopService.getActiveState('session-persist')
expect(retrieved).toEqual(state)
})
@@ -279,7 +279,7 @@ describe('RalphService', () => {
auditCount: 0,
}
const prompt = ralphService.buildAuditPrompt(state)
const prompt = loopService.buildAuditPrompt(state)
expect(prompt).toContain('Review the code changes')
expect(prompt).toContain('bugs, logic errors, missing error handling')
expect(prompt).toContain('No issues found')
@@ -306,8 +306,8 @@ describe('RalphService', () => {
}
const auditFindings = 'Found a bug in line 10'
const prompt = ralphService.buildContinuationPrompt(state, auditFindings)
expect(prompt).toContain('Ralph iteration 2')
const prompt = loopService.buildContinuationPrompt(state, auditFindings)
expect(prompt).toContain('Loop iteration 2')
expect(prompt).toContain('Test prompt')
expect(prompt).toContain('The code auditor reviewed your changes')
expect(prompt).toContain('do not dismiss findings as unrelated to the task')
@@ -333,8 +333,8 @@ describe('RalphService', () => {
auditCount: 0,
}
const prompt = ralphService.buildContinuationPrompt(state)
expect(prompt).toContain('Ralph iteration 2')
const prompt = loopService.buildContinuationPrompt(state)
expect(prompt).toContain('Loop iteration 2')
expect(prompt).toContain('Test prompt')
expect(prompt).not.toContain('The following issues were found')
})
@@ -359,7 +359,7 @@ describe('RalphService', () => {
}
const auditFindings = 'Found a bug in line 10'
const prompt = ralphService.buildContinuationPrompt(state, auditFindings)
const prompt = loopService.buildContinuationPrompt(state, auditFindings)
expect(prompt).toContain('After fixing all issues, output the completion signal')
expect(prompt).toContain('without creating a plan or asking for approval')
})
@@ -419,11 +419,11 @@ describe('RalphService', () => {
auditCount: 0,
}
ralphService.setState('active-1', activeState1)
ralphService.setState('active-2', activeState2)
ralphService.setState('inactive-1', inactiveState)
loopService.setState('active-1', activeState1)
loopService.setState('active-2', activeState2)
loopService.setState('inactive-1', inactiveState)
const active = ralphService.listActive()
const active = loopService.listActive()
expect(active.length).toBe(2)
expect(active.map((s) => s.sessionId)).toContain('active-1')
expect(active.map((s) => s.sessionId)).toContain('active-2')
@@ -449,12 +449,12 @@ describe('RalphService', () => {
auditCount: 0,
}
ralphService.setState('session-1', state1)
loopService.setState('session-1', state1)
const found = ralphService.findByWorktreeName('unique-worktree-name')
const found = loopService.findByWorktreeName('unique-worktree-name')
expect(found).toEqual(state1)
const notFound = ralphService.findByWorktreeName('non-existent')
const notFound = loopService.findByWorktreeName('non-existent')
expect(notFound).toBeNull()
})
@@ -477,8 +477,8 @@ describe('RalphService', () => {
auditCount: 1,
terminationReason: undefined,
}
ralphService.setState('session-err', state)
const retrieved = ralphService.getActiveState('session-err')
loopService.setState('session-err', state)
const retrieved = loopService.getActiveState('session-err')
expect(retrieved?.errorCount).toBe(2)
expect(retrieved?.auditCount).toBe(1)
})
@@ -501,8 +501,8 @@ describe('RalphService', () => {
errorCount: 0,
auditCount: 0,
}
ralphService.setState('session-default', state)
const retrieved = ralphService.getActiveState('session-default')
loopService.setState('session-default', state)
const retrieved = loopService.getActiveState('session-default')
expect(retrieved?.errorCount).toBe(0)
expect(retrieved?.auditCount).toBe(0)
})
@@ -524,11 +524,11 @@ describe('RalphService', () => {
audit: false,
errorCount: 0,
auditCount: 0,
inPlace: true,
worktree: false,
}
ralphService.setState('session-inplace', inPlaceState)
const retrieved = ralphService.getActiveState('session-inplace')
expect(retrieved?.inPlace).toBe(true)
loopService.setState('session-inplace', inPlaceState)
const retrieved = loopService.getActiveState('session-inplace')
expect(retrieved?.worktree).toBe(false)
expect(retrieved?.workspaceId).toBe('')
expect(retrieved?.worktreeDir).toBe('/path/to/project')
})
@@ -550,12 +550,12 @@ describe('RalphService', () => {
audit: true,
errorCount: 0,
auditCount: 1,
inPlace: true,
worktree: false,
}
ralphService.setState('session-inplace-2', inPlaceState)
const found = ralphService.findByWorktreeName('unique-inplace-name')
loopService.setState('session-inplace-2', inPlaceState)
const found = loopService.findByWorktreeName('unique-inplace-name')
expect(found).toEqual(inPlaceState)
expect(found?.inPlace).toBe(true)
expect(found?.worktree).toBe(false)
})
test('buildContinuationPrompt works with inPlace state', () => {
@@ -575,10 +575,10 @@ describe('RalphService', () => {
audit: false,
errorCount: 0,
auditCount: 0,
inPlace: true,
worktree: false,
}
const prompt = ralphService.buildContinuationPrompt(inPlaceState)
expect(prompt).toContain('Ralph iteration 3')
const prompt = loopService.buildContinuationPrompt(inPlaceState)
expect(prompt).toContain('Loop iteration 3')
expect(prompt).toContain('In-place prompt test')
expect(prompt).toContain('<promise>COMPLETE</promise>')
})
@@ -600,11 +600,11 @@ describe('RalphService', () => {
audit: true,
errorCount: 0,
auditCount: 0,
inPlace: true,
worktree: false,
}
const auditFindings = 'Bug found in component'
const prompt = ralphService.buildContinuationPrompt(inPlaceState, auditFindings)
expect(prompt).toContain('Ralph iteration 2')
const prompt = loopService.buildContinuationPrompt(inPlaceState, auditFindings)
expect(prompt).toContain('Loop iteration 2')
expect(prompt).toContain('In-place audit test')
expect(prompt).toContain('The code auditor reviewed your changes')
expect(prompt).toContain('do not dismiss findings as unrelated to the task')
@@ -612,14 +612,14 @@ describe('RalphService', () => {
})
test('getMinAudits returns default when not configured', () => {
const minAudits = ralphService.getMinAudits()
const minAudits = loopService.getMinAudits()
expect(minAudits).toBe(1)
})
test('getMinAudits returns configured value', () => {
const kvService = createKvService(db)
const customRalphService = createRalphService(kvService, projectId, createMockLogger(), { minAudits: 3 })
expect(customRalphService.getMinAudits()).toBe(3)
const customLoopService = createLoopService(kvService, projectId, createMockLogger(), { minAudits: 3 })
expect(customLoopService.getMinAudits()).toBe(3)
})
})
@@ -627,7 +627,7 @@ describe('Stall Detection', () => {
test('getStallInfo returns null when no watchdog running', () => {
const db = createTestDb()
const kvService = createKvService(db)
const ralphService = createRalphService(kvService, 'test-project', createMockLogger())
const loopService = createLoopService(kvService, 'test-project', createMockLogger())
const mockClient = {
session: {
promptAsync: async () => ({ data: undefined, error: undefined }),
@@ -653,9 +653,9 @@ describe('Stall Detection', () => {
},
} as any
const { createRalphEventHandler } = require('../src/hooks/ralph')
const { createLoopEventHandler } = require('../src/hooks/loop')
const mockGetConfig = () => ({ ralph: {}, executionModel: undefined, auditorModel: undefined })
const handler = createRalphEventHandler(ralphService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const handler = createLoopEventHandler(loopService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const info = handler.getStallInfo('test')
expect(info).toBeNull()
@@ -664,7 +664,7 @@ describe('Stall Detection', () => {
test('startWatchdog initializes stall state', () => {
const db = createTestDb()
const kvService = createKvService(db)
const ralphService = createRalphService(kvService, 'test-project', createMockLogger(), { stallTimeoutMs: 100 })
const loopService = createLoopService(kvService, 'test-project', createMockLogger(), { stallTimeoutMs: 100 })
const mockClient = {
session: {
promptAsync: async () => ({ data: undefined, error: undefined }),
@@ -690,13 +690,13 @@ describe('Stall Detection', () => {
},
} as any
const { createRalphEventHandler } = require('../src/hooks/ralph')
const { createLoopEventHandler } = require('../src/hooks/loop')
const mockGetConfig = () => ({ ralph: {}, executionModel: undefined, auditorModel: undefined })
const handler = createRalphEventHandler(ralphService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const handler = createLoopEventHandler(loopService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const sessionId = 'test-session'
const worktreeName = 'test'
ralphService.setState(worktreeName, {
loopService.setState(worktreeName, {
active: true,
sessionId,
worktreeName,
@@ -726,7 +726,7 @@ describe('Stall Detection', () => {
test('session.created event tracks child sessions', async () => {
const db = createTestDb()
const kvService = createKvService(db)
const ralphService = createRalphService(kvService, 'test-project', createMockLogger(), { stallTimeoutMs: 1000 })
const loopService = createLoopService(kvService, 'test-project', createMockLogger(), { stallTimeoutMs: 1000 })
const mockClient = {
session: {
promptAsync: async () => ({ data: undefined, error: undefined }),
@@ -752,15 +752,15 @@ describe('Stall Detection', () => {
},
} as any
const { createRalphEventHandler } = require('../src/hooks/ralph')
const { createLoopEventHandler } = require('../src/hooks/loop')
const mockGetConfig = () => ({ ralph: {}, executionModel: undefined, auditorModel: undefined })
const handler = createRalphEventHandler(ralphService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const handler = createLoopEventHandler(loopService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const parentId = 'parent-session'
const childId = 'child-session'
const worktreeName = 'test'
ralphService.setState(worktreeName, {
loopService.setState(worktreeName, {
active: true,
sessionId: parentId,
worktreeName: 'test',
@@ -801,7 +801,7 @@ describe('Stall Detection', () => {
test('session.status event updates activity time', async () => {
const db = createTestDb()
const kvService = createKvService(db)
const ralphService = createRalphService(kvService, 'test-project', createMockLogger(), { stallTimeoutMs: 1000 })
const loopService = createLoopService(kvService, 'test-project', createMockLogger(), { stallTimeoutMs: 1000 })
const mockClient = {
session: {
promptAsync: async () => ({ data: undefined, error: undefined }),
@@ -827,13 +827,13 @@ describe('Stall Detection', () => {
},
} as any
const { createRalphEventHandler } = require('../src/hooks/ralph')
const { createLoopEventHandler } = require('../src/hooks/loop')
const mockGetConfig = () => ({ ralph: {}, executionModel: undefined, auditorModel: undefined })
const handler = createRalphEventHandler(ralphService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const handler = createLoopEventHandler(loopService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const sessionId = 'test-session'
const worktreeName = 'test'
ralphService.setState(worktreeName, {
loopService.setState(worktreeName, {
active: true,
sessionId,
worktreeName: 'test',
@@ -873,7 +873,7 @@ describe('Stall Detection', () => {
test('stopWatchdog cleans up all state', () => {
const db = createTestDb()
const kvService = createKvService(db)
const ralphService = createRalphService(kvService, 'test-project', createMockLogger(), { stallTimeoutMs: 1000 })
const loopService = createLoopService(kvService, 'test-project', createMockLogger(), { stallTimeoutMs: 1000 })
const mockClient = {
session: {
promptAsync: async () => ({ data: undefined, error: undefined }),
@@ -899,13 +899,13 @@ describe('Stall Detection', () => {
},
} as any
const { createRalphEventHandler } = require('../src/hooks/ralph')
const { createLoopEventHandler } = require('../src/hooks/loop')
const mockGetConfig = () => ({ ralph: {}, executionModel: undefined, auditorModel: undefined })
const handler = createRalphEventHandler(ralphService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const handler = createLoopEventHandler(loopService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const sessionId = 'test-session'
const worktreeName = 'test'
ralphService.setState(worktreeName, {
loopService.setState(worktreeName, {
active: true,
sessionId,
worktreeName: 'test',
@@ -935,21 +935,21 @@ describe('Minimum Audits', () => {
test('getMinAudits returns configured value', () => {
const db = createTestDb()
const kvService = createKvService(db)
const ralphService = createRalphService(kvService, 'test-project', createMockLogger(), { minAudits: 2 })
expect(ralphService.getMinAudits()).toBe(2)
const loopService = createLoopService(kvService, 'test-project', createMockLogger(), { minAudits: 2 })
expect(loopService.getMinAudits()).toBe(2)
})
})
describe('session rotation', () => {
let db: Database
let kvService: ReturnType<typeof createKvService>
let ralphService: ReturnType<typeof createRalphService>
let loopService: ReturnType<typeof createLoopService>
const projectId = 'test-project'
beforeEach(() => {
db = createTestDb()
kvService = createKvService(db)
ralphService = createRalphService(kvService, projectId, createMockLogger())
loopService = createLoopService(kvService, projectId, createMockLogger())
})
afterEach(() => {
@@ -957,7 +957,7 @@ describe('session rotation', () => {
})
test('rotates session on coding phase iteration boundary', async () => {
const { createRalphEventHandler } = require('../src/hooks/ralph')
const { createLoopEventHandler } = require('../src/hooks/loop')
const oldSessionId = 'old-session-id'
const newSessionId = 'new-session-id'
@@ -987,7 +987,7 @@ describe('session rotation', () => {
} as any
const mockGetConfig = () => ({ ralph: {}, executionModel: undefined, auditorModel: undefined })
const handler = createRalphEventHandler(ralphService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const handler = createLoopEventHandler(loopService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const state = {
active: true,
@@ -1007,8 +1007,8 @@ describe('session rotation', () => {
auditCount: 0,
}
ralphService.setState('test-worktree', state)
ralphService.registerSession(oldSessionId, 'test-worktree')
loopService.setState('test-worktree', state)
loopService.registerSession(oldSessionId, 'test-worktree')
await handler.onEvent({
event: {
@@ -1017,18 +1017,18 @@ describe('session rotation', () => {
},
})
const oldState = ralphService.getActiveState('test-worktree')
const oldState = loopService.getActiveState('test-worktree')
expect(oldState).not.toBeNull()
expect(oldState?.sessionId).toBe(newSessionId)
const newState = ralphService.getActiveState('test-worktree')
const newState = loopService.getActiveState('test-worktree')
expect(newState).not.toBeNull()
expect(newState?.iteration).toBe(2)
expect(newState?.sessionId).toBe(newSessionId)
})
test('rotates session on auditing phase completion', async () => {
const { createRalphEventHandler } = require('../src/hooks/ralph')
const { createLoopEventHandler } = require('../src/hooks/loop')
const oldSessionId = 'old-session-id'
const newSessionId = 'new-session-id'
@@ -1072,7 +1072,7 @@ describe('session rotation', () => {
} as any
const mockGetConfig = () => ({ ralph: {}, executionModel: undefined, auditorModel: undefined })
const handler = createRalphEventHandler(ralphService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const handler = createLoopEventHandler(loopService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const state = {
active: true,
@@ -1092,8 +1092,8 @@ describe('session rotation', () => {
auditCount: 0,
}
ralphService.setState('test-worktree', state)
ralphService.registerSession(oldSessionId, 'test-worktree')
loopService.setState('test-worktree', state)
loopService.registerSession(oldSessionId, 'test-worktree')
await handler.onEvent({
event: {
@@ -1102,7 +1102,7 @@ describe('session rotation', () => {
},
})
const newState = ralphService.getActiveState('test-worktree')
const newState = loopService.getActiveState('test-worktree')
expect(newState).not.toBeNull()
expect(newState?.phase).toBe('coding')
expect(newState?.iteration).toBe(2)
@@ -1110,7 +1110,7 @@ describe('session rotation', () => {
})
test('falls back to existing session when rotation fails', async () => {
const { createRalphEventHandler } = require('../src/hooks/ralph')
const { createLoopEventHandler } = require('../src/hooks/loop')
const sessionId = 'existing-session-id'
const mockClient = {
@@ -1139,7 +1139,7 @@ describe('session rotation', () => {
} as any
const mockGetConfig = () => ({ ralph: {}, executionModel: undefined, auditorModel: undefined })
const handler = createRalphEventHandler(ralphService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const handler = createLoopEventHandler(loopService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const state = {
active: true,
@@ -1159,8 +1159,8 @@ describe('session rotation', () => {
auditCount: 0,
}
ralphService.setState('test-worktree', state)
ralphService.registerSession(sessionId, 'test-worktree')
loopService.setState('test-worktree', state)
loopService.registerSession(sessionId, 'test-worktree')
await handler.onEvent({
event: {
@@ -1169,7 +1169,7 @@ describe('session rotation', () => {
},
})
const existingState = ralphService.getActiveState('test-worktree')
const existingState = loopService.getActiveState('test-worktree')
expect(existingState).not.toBeNull()
expect(existingState?.iteration).toBe(2)
expect(existingState?.sessionId).toBe(sessionId)
@@ -1179,13 +1179,13 @@ describe('session rotation', () => {
describe('Assistant Error Detection', () => {
let db: Database
let kvService: ReturnType<typeof createKvService>
let ralphService: ReturnType<typeof createRalphService>
let loopService: ReturnType<typeof createLoopService>
const projectId = 'test-project'
beforeEach(() => {
db = createTestDb()
kvService = createKvService(db)
ralphService = createRalphService(kvService, projectId, createMockLogger())
loopService = createLoopService(kvService, projectId, createMockLogger())
})
afterEach(() => {
@@ -1193,7 +1193,7 @@ describe('Assistant Error Detection', () => {
})
test('detects assistant error in coding phase and triggers error handling', async () => {
const { createRalphEventHandler } = require('../src/hooks/ralph')
const { createLoopEventHandler } = require('../src/hooks/loop')
const sessionId = 'error-session'
const mockClient = {
@@ -1232,7 +1232,7 @@ describe('Assistant Error Detection', () => {
} as any
const mockGetConfig = () => ({ ralph: {}, executionModel: undefined, auditorModel: undefined })
const handler = createRalphEventHandler(ralphService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const handler = createLoopEventHandler(loopService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const state = {
active: true,
@@ -1252,8 +1252,8 @@ describe('Assistant Error Detection', () => {
auditCount: 0,
}
ralphService.setState('test-worktree', state)
ralphService.registerSession(sessionId, 'test-worktree')
loopService.setState('test-worktree', state)
loopService.registerSession(sessionId, 'test-worktree')
await handler.onEvent({
event: {
@@ -1262,13 +1262,13 @@ describe('Assistant Error Detection', () => {
},
})
const updatedState = ralphService.getActiveState('test-worktree')
const updatedState = loopService.getActiveState('test-worktree')
expect(updatedState?.errorCount).toBe(1)
expect(updatedState?.modelFailed).toBe(true)
})
test('detects assistant error in auditing phase and triggers error handling', async () => {
const { createRalphEventHandler } = require('../src/hooks/ralph')
const { createLoopEventHandler } = require('../src/hooks/loop')
const sessionId = 'audit-error-session'
const mockClient = {
@@ -1307,7 +1307,7 @@ describe('Assistant Error Detection', () => {
} as any
const mockGetConfig = () => ({ ralph: {}, executionModel: undefined, auditorModel: undefined })
const handler = createRalphEventHandler(ralphService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const handler = createLoopEventHandler(loopService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const state = {
active: true,
@@ -1327,8 +1327,8 @@ describe('Assistant Error Detection', () => {
auditCount: 0,
}
ralphService.setState('test-worktree', state)
ralphService.registerSession(sessionId, 'test-worktree')
loopService.setState('test-worktree', state)
loopService.registerSession(sessionId, 'test-worktree')
await handler.onEvent({
event: {
@@ -1337,13 +1337,13 @@ describe('Assistant Error Detection', () => {
},
})
const updatedState = ralphService.getActiveState('test-worktree')
const updatedState = loopService.getActiveState('test-worktree')
expect(updatedState?.errorCount).toBe(1)
expect(updatedState?.modelFailed).toBe(true)
})
test('session.error event with non-abort error sets modelFailed flag', async () => {
const { createRalphEventHandler } = require('../src/hooks/ralph')
const { createLoopEventHandler } = require('../src/hooks/loop')
const sessionId = 'session-error-test'
const mockClient = {
@@ -1372,7 +1372,7 @@ describe('Assistant Error Detection', () => {
} as any
const mockGetConfig = () => ({ ralph: {}, executionModel: undefined, auditorModel: undefined })
const handler = createRalphEventHandler(ralphService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const handler = createLoopEventHandler(loopService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const state = {
active: true,
@@ -1392,8 +1392,8 @@ describe('Assistant Error Detection', () => {
auditCount: 0,
}
ralphService.setState('test-worktree', state)
ralphService.registerSession(sessionId, 'test-worktree')
loopService.setState('test-worktree', state)
loopService.registerSession(sessionId, 'test-worktree')
await handler.onEvent({
event: {
@@ -1408,12 +1408,12 @@ describe('Assistant Error Detection', () => {
},
})
const updatedState = ralphService.getActiveState('test-worktree')
const updatedState = loopService.getActiveState('test-worktree')
expect(updatedState?.modelFailed).toBe(true)
})
test('session.error event with abort error terminates loop immediately', async () => {
const { createRalphEventHandler } = require('../src/hooks/ralph')
const { createLoopEventHandler } = require('../src/hooks/loop')
const sessionId = 'abort-session'
const mockClient = {
@@ -1442,7 +1442,7 @@ describe('Assistant Error Detection', () => {
} as any
const mockGetConfig = () => ({ ralph: {}, executionModel: undefined, auditorModel: undefined })
const handler = createRalphEventHandler(ralphService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const handler = createLoopEventHandler(loopService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const state = {
active: true,
@@ -1462,8 +1462,8 @@ describe('Assistant Error Detection', () => {
auditCount: 0,
}
ralphService.setState('test-worktree', state)
ralphService.registerSession(sessionId, 'test-worktree')
loopService.setState('test-worktree', state)
loopService.registerSession(sessionId, 'test-worktree')
await handler.onEvent({
event: {
@@ -1477,12 +1477,12 @@ describe('Assistant Error Detection', () => {
},
})
const updatedState = ralphService.getActiveState('test-worktree')
const updatedState = loopService.getActiveState('test-worktree')
expect(updatedState).toBeNull()
})
test('modelFailed flag causes default model usage in coding phase', async () => {
const { createRalphEventHandler } = require('../src/hooks/ralph')
const { createLoopEventHandler } = require('../src/hooks/loop')
const sessionId = 'model-fail-session'
let modelUsed: string | undefined
@@ -1520,7 +1520,7 @@ describe('Assistant Error Detection', () => {
executionModel: 'execution/model',
auditorModel: undefined,
})
const handler = createRalphEventHandler(ralphService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const handler = createLoopEventHandler(loopService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const state = {
active: true,
@@ -1541,7 +1541,7 @@ describe('Assistant Error Detection', () => {
modelFailed: true,
}
ralphService.setState('test-worktree', state)
loopService.setState('test-worktree', state)
await handler.onEvent({
event: {
@@ -1554,7 +1554,7 @@ describe('Assistant Error Detection', () => {
})
test('three consecutive errors terminate loop', async () => {
const { createRalphEventHandler } = require('../src/hooks/ralph')
const { createLoopEventHandler } = require('../src/hooks/loop')
const sessionId = 'three-errors-session'
const mockClient = {
@@ -1593,7 +1593,7 @@ describe('Assistant Error Detection', () => {
} as any
const mockGetConfig = () => ({ ralph: {}, executionModel: undefined, auditorModel: undefined })
const handler = createRalphEventHandler(ralphService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const handler = createLoopEventHandler(loopService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const state = {
active: true,
@@ -1613,8 +1613,8 @@ describe('Assistant Error Detection', () => {
auditCount: 0,
}
ralphService.setState('test-worktree', state)
ralphService.registerSession(sessionId, 'test-worktree')
loopService.setState('test-worktree', state)
loopService.registerSession(sessionId, 'test-worktree')
await handler.onEvent({
event: {
@@ -1623,7 +1623,7 @@ describe('Assistant Error Detection', () => {
},
})
let stateAfterSecondError = ralphService.getActiveState('test-worktree')
let stateAfterSecondError = loopService.getActiveState('test-worktree')
expect(stateAfterSecondError?.errorCount).toBe(1)
await handler.onEvent({
@@ -1633,7 +1633,7 @@ describe('Assistant Error Detection', () => {
},
})
let stateAfterThirdError = ralphService.getActiveState('test-worktree')
let stateAfterThirdError = loopService.getActiveState('test-worktree')
expect(stateAfterThirdError?.errorCount).toBe(2)
await handler.onEvent({
@@ -1643,10 +1643,10 @@ describe('Assistant Error Detection', () => {
},
})
const finalState = ralphService.getActiveState('test-worktree')
const finalState = loopService.getActiveState('test-worktree')
expect(finalState).toBeNull()
const terminatedState = ralphService.getAnyState('test-worktree')
const terminatedState = loopService.getAnyState('test-worktree')
expect(terminatedState?.active).toBe(false)
expect(terminatedState?.terminationReason).toContain('error_max_retries')
})
+66 -66
View File
@@ -1,7 +1,7 @@
import { describe, test, expect, beforeEach, afterEach } from 'bun:test'
import { Database } from 'bun:sqlite'
import { createKvService } from '../src/services/kv'
import { createRalphService } from '../src/services/ralph'
import { createLoopService } from '../src/services/loop'
import type { Logger } from '../src/types'
const TEST_DIR = '/tmp/opencode-manager-plan-approval-test-' + Date.now()
@@ -33,11 +33,11 @@ function createMockLogger(): Logger {
describe('Plan Approval Tool Interception', () => {
let db: Database
let ralphService: ReturnType<typeof createRalphService>
let ralphService: ReturnType<typeof createLoopService>
const projectId = 'test-project'
const sessionID = 'test-session-123'
const PLAN_APPROVAL_LABELS = ['New session', 'Execute here', 'Ralph (worktree)', 'Ralph (in place)']
const PLAN_APPROVAL_LABELS = ['New session', 'Execute here', 'Loop (worktree)', 'Loop']
const PLAN_APPROVAL_DIRECTIVES: Record<string, string> = {
'New session': `<system-reminder>
@@ -54,28 +54,28 @@ The user selected "Execute here". You MUST now call memory-plan-execute in this
- inPlace: true
Do NOT output text without also making this tool call.
</system-reminder>`,
'Ralph (worktree)': `<system-reminder>
The user selected "Ralph (worktree)". You MUST now call memory-plan-ralph in this response with:
- plan: The FULL self-contained implementation plan (Ralph runs in an isolated worktree with no prior context)
'Loop (worktree)': `<system-reminder>
The user selected "Loop (worktree)". You MUST now call memory-loop in this response with:
- plan: The FULL self-contained implementation plan (runs in an isolated worktree with no prior context)
- title: A short descriptive title for the session
- inPlace: false (or omit)
- worktree: true
Do NOT output text without also making this tool call.
</system-reminder>`,
'Ralph (in place)': `<system-reminder>
The user selected "Ralph (in place)". You MUST now call memory-plan-ralph in this response with:
- plan: The FULL self-contained implementation plan (Ralph runs in the current directory with no prior context)
'Loop': `<system-reminder>
The user selected "Loop". You MUST now call memory-loop in this response with:
- plan: The FULL self-contained implementation plan (runs in the current directory with no prior context)
- title: A short descriptive title for the session
- inPlace: true
- worktree: false
Do NOT output text without also making this tool call.
</system-reminder>`,
}
const CANCEL_DIRECTIVE = '<system-reminder>\nThe user provided a custom response instead of selecting a predefined option. Review their answer and respond accordingly. If they want to proceed with execution, use the appropriate tool (memory-plan-execute or memory-plan-ralph) based on their intent. If they want to cancel or revise the plan, help them with that instead.\n</system-reminder>'
const CANCEL_DIRECTIVE = '<system-reminder>\nThe user provided a custom response instead of selecting a predefined option. Review their answer and respond accordingly. If they want to proceed with execution, use the appropriate tool (memory-plan-execute or memory-loop) based on their intent. If they want to cancel or revise the plan, help them with that instead.\n</system-reminder>'
beforeEach(() => {
db = createTestDb()
const kvService = createKvService(db)
ralphService = createRalphService(kvService, projectId, createMockLogger())
ralphService = createLoopService(kvService, projectId, createMockLogger())
})
afterEach(() => {
@@ -130,9 +130,9 @@ Do NOT output text without also making this tool call.
if (!sessionActive) return
const RALPH_BLOCKED_TOOLS: Record<string, string> = {
question: 'The question tool is not available during a Ralph loop. Do not ask questions — continue working on the task autonomously.',
'memory-plan-execute': 'The memory-plan-execute tool is not available during a Ralph loop. Focus on executing the current plan.',
'memory-plan-ralph': 'The memory-plan-ralph tool is not available during a Ralph loop. Focus on executing the current plan.',
question: 'The question tool is not available during a memory loop. Do not ask questions — continue working on the task autonomously.',
'memory-plan-execute': 'The memory-plan-execute tool is not available during a memory loop. Focus on executing the current plan.',
'memory-loop': 'The memory-loop tool is not available during a memory loop. Focus on executing the current plan.',
}
if (!(tool in RALPH_BLOCKED_TOOLS)) return
@@ -148,8 +148,8 @@ Do NOT output text without also making this tool call.
options: [
{ label: 'New session', description: 'Create new session' },
{ label: 'Execute here', description: 'Execute here' },
{ label: 'Ralph (worktree)', description: 'Ralph worktree' },
{ label: 'Ralph (in place)', description: 'Ralph in place' },
{ label: 'Loop (worktree)', description: 'Loop worktree' },
{ label: 'Loop', description: 'Loop in place' },
],
}],
}
@@ -170,8 +170,8 @@ Do NOT output text without also making this tool call.
options: [
{ label: 'New session', description: 'Create new session' },
{ label: 'Execute here', description: 'Execute here' },
{ label: 'Ralph (worktree)', description: 'Ralph worktree' },
{ label: 'Ralph (in place)', description: 'Ralph in place' },
{ label: 'Loop (worktree)', description: 'Loop worktree' },
{ label: 'Loop', description: 'Loop in place' },
],
}],
}
@@ -185,48 +185,48 @@ Do NOT output text without also making this tool call.
expect(output.output).toContain('inPlace: true')
})
test('Detects plan approval question and injects "Ralph (worktree)" directive', () => {
test('Detects plan approval question and injects "Loop (worktree)" directive', () => {
const args = {
questions: [{
question: 'How would you like to proceed?',
options: [
{ label: 'New session', description: 'Create new session' },
{ label: 'Execute here', description: 'Execute here' },
{ label: 'Ralph (worktree)', description: 'Ralph worktree' },
{ label: 'Ralph (in place)', description: 'Ralph in place' },
{ label: 'Loop (worktree)', description: 'Loop worktree' },
{ label: 'Loop', description: 'Loop in place' },
],
}],
}
const output = { title: '', output: 'Ralph (worktree)', metadata: {} }
const output = { title: '', output: 'Loop (worktree)', metadata: {} }
simulateToolExecuteAfter('question', args, output)
expect(output.output).toContain('Ralph (worktree)')
expect(output.output).toContain('Loop (worktree)')
expect(output.output).toContain('<system-reminder>')
expect(output.output).toContain('memory-plan-ralph')
expect(output.output).toContain('inPlace: false')
expect(output.output).toContain('memory-loop')
expect(output.output).toContain('worktree: true')
})
test('Detects plan approval question and injects "Ralph (in place)" directive', () => {
test('Detects plan approval question and injects "Loop" directive', () => {
const args = {
questions: [{
question: 'How would you like to proceed?',
options: [
{ label: 'New session', description: 'Create new session' },
{ label: 'Execute here', description: 'Execute here' },
{ label: 'Ralph (worktree)', description: 'Ralph worktree' },
{ label: 'Ralph (in place)', description: 'Ralph in place' },
{ label: 'Loop (worktree)', description: 'Loop worktree' },
{ label: 'Loop', description: 'Loop in place' },
],
}],
}
const output = { title: '', output: 'Ralph (in place)', metadata: {} }
const output = { title: '', output: 'Loop', metadata: {} }
simulateToolExecuteAfter('question', args, output)
expect(output.output).toContain('Ralph (in place)')
expect(output.output).toContain('Loop')
expect(output.output).toContain('<system-reminder>')
expect(output.output).toContain('memory-plan-ralph')
expect(output.output).toContain('inPlace: true')
expect(output.output).toContain('memory-loop')
expect(output.output).toContain('worktree: false')
})
test('Injects cancel directive for unknown answer', () => {
@@ -236,8 +236,8 @@ Do NOT output text without also making this tool call.
options: [
{ label: 'New session', description: 'Create new session' },
{ label: 'Execute here', description: 'Execute here' },
{ label: 'Ralph (worktree)', description: 'Ralph worktree' },
{ label: 'Ralph (in place)', description: 'Ralph in place' },
{ label: 'Loop (worktree)', description: 'Loop worktree' },
{ label: 'Loop', description: 'Loop in place' },
],
}],
}
@@ -258,8 +258,8 @@ Do NOT output text without also making this tool call.
options: [
{ label: 'New session', description: 'Create new session' },
{ label: 'Execute here', description: 'Execute here' },
{ label: 'Ralph (worktree)', description: 'Ralph worktree' },
{ label: 'Ralph (in place)', description: 'Ralph in place' },
{ label: 'Loop (worktree)', description: 'Loop worktree' },
{ label: 'Loop', description: 'Loop in place' },
],
}],
}
@@ -279,8 +279,8 @@ Do NOT output text without also making this tool call.
options: [
{ label: 'New session', description: 'Create new session' },
{ label: 'Execute here', description: 'Execute here' },
{ label: 'Ralph (worktree)', description: 'Ralph worktree' },
{ label: 'Ralph (in place)', description: 'Ralph in place' },
{ label: 'Loop (worktree)', description: 'Loop worktree' },
{ label: 'Loop', description: 'Loop in place' },
],
}],
}
@@ -339,13 +339,13 @@ Do NOT output text without also making this tool call.
expect(output.output).toContain('memory-plan-execute tool is not available')
})
test('Ralph blocking works for memory-plan-ralph tool', () => {
test('Ralph blocking works for memory-loop tool', () => {
const output = { title: '', output: 'test', metadata: {} }
simulateToolExecuteAfter('memory-plan-ralph', {}, output, true)
simulateToolExecuteAfter('memory-loop', {}, output, true)
expect(output.title).toBe('Tool blocked')
expect(output.output).toContain('memory-plan-ralph tool is not available')
expect(output.output).toContain('memory-loop tool is not available')
})
test('Ralph blocking does not affect non-blocked tools', () => {
@@ -373,49 +373,49 @@ Do NOT output text without also making this tool call.
options: [
{ label: 'New session', description: 'Create new session' },
{ label: 'Execute here', description: 'Execute here' },
{ label: 'Ralph (worktree)', description: 'Ralph worktree' },
{ label: 'Ralph (in place)', description: 'Ralph in place' },
{ label: 'Loop (worktree)', description: 'Loop worktree' },
{ label: 'Loop', description: 'Loop in place' },
],
}],
}
const output = {
title: 'Asked 1 question',
output: 'User has answered your questions: "How would you like to proceed?"="Ralph (worktree)". You can now continue with the user\'s answers in mind.',
metadata: { answers: [['Ralph (worktree)']] },
output: 'User has answered your questions: "How would you like to proceed?"="Loop (worktree)". You can now continue with the user\'s answers in mind.',
metadata: { answers: [['Loop (worktree)']] },
}
simulateToolExecuteAfter('question', args, output)
expect(output.output).toContain('Ralph (worktree)')
expect(output.output).toContain('Loop (worktree)')
expect(output.output).toContain('<system-reminder>')
expect(output.output).toContain('memory-plan-ralph')
expect(output.output).toContain('inPlace: false')
expect(output.output).toContain('memory-loop')
expect(output.output).toContain('worktree: true')
})
test('Detects "Ralph (in place)" using metadata.answers when output is full sentence', () => {
test('Detects "Loop" using metadata.answers when output is full sentence', () => {
const args = {
questions: [{
question: 'How would you like to proceed?',
options: [
{ label: 'New session', description: 'Create new session' },
{ label: 'Execute here', description: 'Execute here' },
{ label: 'Ralph (worktree)', description: 'Ralph worktree' },
{ label: 'Ralph (in place)', description: 'Ralph in place' },
{ label: 'Loop (worktree)', description: 'Loop worktree' },
{ label: 'Loop', description: 'Loop in place' },
],
}],
}
const output = {
title: 'Asked 1 question',
output: 'User has answered your questions: "How would you like to proceed?"="Ralph (in place)". You can now continue with the user\'s answers in mind.',
metadata: { answers: [['Ralph (in place)']] },
output: 'User has answered your questions: "How would you like to proceed?"="Loop". You can now continue with the user\'s answers in mind.',
metadata: { answers: [['Loop']] },
}
simulateToolExecuteAfter('question', args, output)
expect(output.output).toContain('Ralph (in place)')
expect(output.output).toContain('Loop')
expect(output.output).toContain('<system-reminder>')
expect(output.output).toContain('memory-plan-ralph')
expect(output.output).toContain('inPlace: true')
expect(output.output).toContain('memory-loop')
expect(output.output).toContain('worktree: false')
})
test('Detects "New session" using metadata.answers when output is full sentence', () => {
@@ -425,8 +425,8 @@ Do NOT output text without also making this tool call.
options: [
{ label: 'New session', description: 'Create new session' },
{ label: 'Execute here', description: 'Execute here' },
{ label: 'Ralph (worktree)', description: 'Ralph worktree' },
{ label: 'Ralph (in place)', description: 'Ralph in place' },
{ label: 'Loop (worktree)', description: 'Loop worktree' },
{ label: 'Loop', description: 'Loop in place' },
],
}],
}
@@ -451,8 +451,8 @@ Do NOT output text without also making this tool call.
options: [
{ label: 'New session', description: 'Create new session' },
{ label: 'Execute here', description: 'Execute here' },
{ label: 'Ralph (worktree)', description: 'Ralph worktree' },
{ label: 'Ralph (in place)', description: 'Ralph in place' },
{ label: 'Loop (worktree)', description: 'Loop worktree' },
{ label: 'Loop', description: 'Loop in place' },
],
}],
}
@@ -477,8 +477,8 @@ Do NOT output text without also making this tool call.
options: [
{ label: 'New session', description: 'Create new session' },
{ label: 'Execute here', description: 'Execute here' },
{ label: 'Ralph (worktree)', description: 'Ralph worktree' },
{ label: 'Ralph (in place)', description: 'Ralph in place' },
{ label: 'Loop (worktree)', description: 'Loop worktree' },
{ label: 'Loop', description: 'Loop in place' },
],
}],
}
@@ -503,8 +503,8 @@ Do NOT output text without also making this tool call.
options: [
{ label: 'New session', description: 'Create new session' },
{ label: 'Execute here', description: 'Execute here' },
{ label: 'Ralph (worktree)', description: 'Ralph worktree' },
{ label: 'Ralph (in place)', description: 'Ralph in place' },
{ label: 'Loop (worktree)', description: 'Loop worktree' },
{ label: 'Loop', description: 'Loop in place' },
],
}],
}
+21 -21
View File
@@ -1,7 +1,7 @@
import { describe, test, expect, beforeEach, afterEach } from 'bun:test'
import { Database } from 'bun:sqlite'
import { createKvService } from '../src/services/kv'
import { createRalphService } from '../src/services/ralph'
import { createLoopService } from '../src/services/loop'
import type { Logger } from '../src/types'
const TEST_DIR = '/tmp/opencode-manager-tool-blocking-test-' + Date.now()
@@ -33,14 +33,14 @@ function createMockLogger(): Logger {
describe('Tool Blocking Logic', () => {
let db: Database
let ralphService: ReturnType<typeof createRalphService>
let loopService: ReturnType<typeof createLoopService>
const projectId = 'test-project'
const sessionID = 'test-session-123'
beforeEach(() => {
db = createTestDb()
const kvService = createKvService(db)
ralphService = createRalphService(kvService, projectId, createMockLogger())
loopService = createLoopService(kvService, projectId, createMockLogger())
})
afterEach(() => {
@@ -67,15 +67,15 @@ describe('Tool Blocking Logic', () => {
auditCount: 0,
inPlace: false,
}
ralphService.setState(sessionID, state)
loopService.setState(sessionID, state)
const retrieved = ralphService.getActiveState(sessionID)
const retrieved = loopService.getActiveState(sessionID)
expect(retrieved).toEqual(state)
expect(retrieved?.active).toBe(true)
})
test('getActiveState returns null when no Ralph loop exists', () => {
const retrieved = ralphService.getActiveState('non-existent-session')
const retrieved = loopService.getActiveState('non-existent-session')
expect(retrieved).toBeNull()
})
@@ -98,36 +98,36 @@ describe('Tool Blocking Logic', () => {
auditCount: 0,
inPlace: false,
}
ralphService.setState(sessionID, inactiveState)
loopService.setState(sessionID, inactiveState)
const retrieved = ralphService.getActiveState(sessionID)
const retrieved = loopService.getActiveState(sessionID)
expect(retrieved).toBeNull()
})
})
describe('Blocked tools list', () => {
test('includes question tool', () => {
const blockedTools = ['question', 'memory-plan-execute', 'memory-plan-ralph']
const blockedTools = ['question', 'memory-plan-execute', 'memory-loop']
expect(blockedTools).toContain('question')
})
test('includes memory-plan-execute tool', () => {
const blockedTools = ['question', 'memory-plan-execute', 'memory-plan-ralph']
const blockedTools = ['question', 'memory-plan-execute', 'memory-loop']
expect(blockedTools).toContain('memory-plan-execute')
})
test('includes memory-plan-ralph tool', () => {
const blockedTools = ['question', 'memory-plan-execute', 'memory-plan-ralph']
expect(blockedTools).toContain('memory-plan-ralph')
test('includes memory-loop tool', () => {
const blockedTools = ['question', 'memory-plan-execute', 'memory-loop']
expect(blockedTools).toContain('memory-loop')
})
test('does not include memory-read tool', () => {
const blockedTools = ['question', 'memory-plan-execute', 'memory-plan-ralph']
const blockedTools = ['question', 'memory-plan-execute', 'memory-loop']
expect(blockedTools).not.toContain('memory-read')
})
test('does not include memory-write tool', () => {
const blockedTools = ['question', 'memory-plan-execute', 'memory-plan-ralph']
const blockedTools = ['question', 'memory-plan-execute', 'memory-loop']
expect(blockedTools).not.toContain('memory-write')
})
})
@@ -135,18 +135,18 @@ describe('Tool Blocking Logic', () => {
describe('Error messages', () => {
test('question tool has appropriate error message', () => {
const messages: Record<string, string> = {
'question': 'The question tool is not available during a Ralph loop. Do not ask questions — continue working on the task autonomously.',
'memory-plan-execute': 'The memory-plan-execute tool is not available during a Ralph loop. Focus on executing the current plan.',
'memory-plan-ralph': 'The memory-plan-ralph tool is not available during a Ralph loop. Focus on executing the current plan.',
'question': 'The question tool is not available during a memory loop. Do not ask questions — continue working on the task autonomously.',
'memory-plan-execute': 'The memory-plan-execute tool is not available during a memory loop. Focus on executing the current plan.',
'memory-loop': 'The memory-loop tool is not available during a memory loop. Focus on executing the current plan.',
}
expect(messages['question']).toContain('question tool is not available')
})
test('memory-plan-execute tool has appropriate error message', () => {
const messages: Record<string, string> = {
'question': 'The question tool is not available during a Ralph loop. Do not ask questions — continue working on the task autonomously.',
'memory-plan-execute': 'The memory-plan-execute tool is not available during a Ralph loop. Focus on executing the current plan.',
'memory-plan-ralph': 'The memory-plan-ralph tool is not available during a Ralph loop. Focus on executing the current plan.',
'question': 'The question tool is not available during a memory loop. Do not ask questions — continue working on the task autonomously.',
'memory-plan-execute': 'The memory-plan-execute tool is not available during a memory loop. Focus on executing the current plan.',
'memory-loop': 'The memory-loop tool is not available during a memory loop. Focus on executing the current plan.',
}
expect(messages['memory-plan-execute']).toContain('memory-plan-execute tool is not available')
})