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

+16 -16
View File
@@ -17,9 +17,9 @@ import {
PluginConfigSchema,
CreateKvEntryRequestSchema,
UpdateKvEntryRequestSchema,
RalphStateSchema,
LoopStateSchema,
type PluginConfig,
type RalphState,
type LoopState,
} from '@opencode-manager/shared/schemas'
function resolveMemoryDataDir(): string {
@@ -528,7 +528,7 @@ export function createMemoryRoutes(db: Database): Hono {
}
})
app.get('/ralph/status', async (c) => {
app.get('/loop/status', async (c) => {
const repoIdParam = c.req.query('repoId')
if (!repoIdParam) {
@@ -554,26 +554,26 @@ export function createMemoryRoutes(db: Database): Hono {
return c.json({ loops: [], projectId: null })
}
const entries = pluginMemory.listKv(projectId, 'ralph:')
const entries = pluginMemory.listKv(projectId, 'loop:')
const loops = entries
.map(e => e.data)
.filter((data): data is Record<string, unknown> =>
data !== null && typeof data === 'object' && 'active' in data
)
.map(data => {
const result = RalphStateSchema.safeParse(data)
const result = LoopStateSchema.safeParse(data)
return result.success ? result.data : null
})
.filter((loop): loop is RalphState => loop !== null)
.filter((loop): loop is LoopState => loop !== null)
return c.json({ loops, projectId })
} catch (error) {
logger.error('Failed to get Ralph status:', error)
return c.json({ error: 'Failed to get Ralph status' }, 500)
logger.error('Failed to get Loop:', error)
return c.json({ error: 'Failed to get Loop' }, 500)
}
})
app.post('/ralph/cancel', async (c) => {
app.post('/loop/cancel', async (c) => {
try {
const body = await c.req.json()
const { repoId, worktreeName, sessionId } = body
@@ -599,7 +599,7 @@ export function createMemoryRoutes(db: Database): Hono {
if (worktreeName) {
worktreeNameToUse = worktreeName
} else if (sessionId) {
const sessionMappingEntry = pluginMemory.getKv(projectId, `ralph-session:${sessionId}`)
const sessionMappingEntry = pluginMemory.getKv(projectId, `loop-session:${sessionId}`)
if (!sessionMappingEntry) {
return c.json({ cancelled: false })
}
@@ -610,15 +610,15 @@ export function createMemoryRoutes(db: Database): Hono {
return c.json({ cancelled: false })
}
const kvEntry = pluginMemory.getKv(projectId, `ralph:${worktreeNameToUse}`)
const kvEntry = pluginMemory.getKv(projectId, `loop:${worktreeNameToUse}`)
if (!kvEntry) {
return c.json({ cancelled: false })
}
const result = RalphStateSchema.safeParse(kvEntry.data)
const result = LoopStateSchema.safeParse(kvEntry.data)
if (!result.success) {
logger.warn('Failed to parse Ralph state for cancel:', result.error)
logger.warn('Failed to parse Loop state for cancel:', result.error)
return c.json({ cancelled: false })
}
@@ -635,7 +635,7 @@ export function createMemoryRoutes(db: Database): Hono {
completedAt: new Date().toISOString(),
}
pluginMemory.setKv(projectId, `ralph:${worktreeNameToUse}`, updatedState)
pluginMemory.setKv(projectId, `loop:${worktreeNameToUse}`, updatedState)
try {
const abortUrl = new URL(`${OPENCODE_SERVER_URL}/session/${state.sessionId}/abort`)
@@ -647,8 +647,8 @@ export function createMemoryRoutes(db: Database): Hono {
return c.json({ cancelled: true, worktreeName: state.worktreeName })
} catch (error) {
logger.error('Failed to cancel Ralph loop:', error)
return c.json({ error: 'Failed to cancel Ralph loop' }, 500)
logger.error('Failed to cancel Loop:', error)
return c.json({ error: 'Failed to cancel Loop' }, 500)
}
})
+11 -11
View File
@@ -63,7 +63,7 @@ import { getRepoById } from '../../src/db/queries'
const mockResolveProjectId = resolveProjectId as ReturnType<typeof vi.fn>
const mockGetRepoById = getRepoById as ReturnType<typeof vi.fn>
describe('Memory Routes - Ralph Status', () => {
describe('Memory Routes - Loop Status', () => {
let memoryApp: ReturnType<typeof createMemoryRoutes>
let testDb: any
@@ -77,9 +77,9 @@ describe('Memory Routes - Ralph Status', () => {
memoryApp = createMemoryRoutes(testDb)
})
describe('GET /ralph/status', () => {
describe('GET /loop/status', () => {
it('should return 400 when repoId query param is missing', async () => {
const req = new Request('http://localhost/ralph/status')
const req = new Request('http://localhost/loop/status')
const res = await memoryApp.fetch(req)
expect(res.status).toBe(400)
@@ -88,7 +88,7 @@ describe('Memory Routes - Ralph Status', () => {
})
it('should return 400 when repoId is not a valid number', async () => {
const req = new Request('http://localhost/ralph/status?repoId=abc')
const req = new Request('http://localhost/loop/status?repoId=abc')
const res = await memoryApp.fetch(req)
expect(res.status).toBe(400)
@@ -99,7 +99,7 @@ describe('Memory Routes - Ralph Status', () => {
it('should return 200 with empty loops when repo is not found in DB', async () => {
mockGetRepoById.mockReturnValue(null)
const req = new Request('http://localhost/ralph/status?repoId=1')
const req = new Request('http://localhost/loop/status?repoId=1')
const res = await memoryApp.fetch(req)
expect(res.status).toBe(200)
@@ -122,7 +122,7 @@ describe('Memory Routes - Ralph Status', () => {
})
mockResolveProjectId.mockResolvedValue(null)
const req = new Request('http://localhost/ralph/status?repoId=1')
const req = new Request('http://localhost/loop/status?repoId=1')
const res = await memoryApp.fetch(req)
expect(res.status).toBe(200)
@@ -147,7 +147,7 @@ describe('Memory Routes - Ralph Status', () => {
mockResolveProjectId.mockResolvedValue('test-project-id')
mockListKv.mockReturnValue([
{
key: 'ralph:test-worktree',
key: 'loop:test-worktree',
data: {
active: true,
sessionId: 'session-123',
@@ -168,7 +168,7 @@ describe('Memory Routes - Ralph Status', () => {
},
])
const req = new Request('http://localhost/ralph/status?repoId=1')
const req = new Request('http://localhost/loop/status?repoId=1')
const res = await memoryApp.fetch(req)
expect(res.status).toBe(200)
@@ -235,7 +235,7 @@ describe('Memory Routes - Ralph Status', () => {
},
])
const req = new Request('http://localhost/ralph/status?repoId=1')
const req = new Request('http://localhost/loop/status?repoId=1')
const res = await memoryApp.fetch(req)
expect(res.status).toBe(200)
@@ -249,12 +249,12 @@ describe('Memory Routes - Ralph Status', () => {
throw new Error('Database error')
})
const req = new Request('http://localhost/ralph/status?repoId=1')
const req = new Request('http://localhost/loop/status?repoId=1')
const res = await memoryApp.fetch(req)
expect(res.status).toBe(500)
const json = await res.json() as Record<string, unknown>
expect(json.error).toBe('Failed to get Ralph status')
expect(json.error).toBe('Failed to get Loop')
})
})
})
+19 -19
View File
@@ -74,7 +74,7 @@ The file is only created if it does not already exist. The config is validated o
},
"executionModel": "",
"auditorModel": "",
"ralph": {
"loop": {
"enabled": true,
"defaultMaxIterations": 15,
"cleanupWorktree": false,
@@ -158,7 +158,7 @@ The plugin is composed of several subsystems that work together:
│ Embedding │ Vec Search │ Cache │
│ Service │ (sqlite-vec) │ (In-Memory) │
├──────────────┴────────────────┬───────────────────┤
│ KV Service │ Ralph Service │ Auto-Cleanup │
│ KV Service │ Loop Service │ Auto-Cleanup │
│ (TTL state) │ (loop mgmt) │ (30min) │
├─────────────────┴─────────────────┴───────────────┤
│ SQLite Database (WAL) │
@@ -194,11 +194,11 @@ The KV store provides ephemeral project state management with automatic TTL-base
The KV service is initialized on plugin startup and begins its cleanup interval automatically. Call `kvService.destroy()` during cleanup to stop the interval.
### Ralph Service
### Loop Service
The Ralph service manages iterative development loops using the KV store for state persistence:
- **State Management**: Each loop's state is stored in the KV store under `ralph:{sessionId}` with fields: `active` (boolean), `sessionId`, `worktreeName`, `worktreeDir`, `worktreeBranch`, `workspaceId`, `iteration`, `maxIterations`, `completionPromise`, `startedAt`, `prompt`, `phase` (coding/auditing), `audit`, `lastAuditResult`, `errorCount`, `auditCount`, `terminationReason`, `completedAt`, `parentSessionId`, `inPlace`
- **State Management**: Each loop's state is stored in the KV store under `loop:{sessionId}` with fields: `active` (boolean), `sessionId`, `worktreeName`, `worktreeDir`, `worktreeBranch`, `workspaceId`, `iteration`, `maxIterations`, `completionPromise`, `startedAt`, `prompt`, `phase` (coding/auditing), `audit`, `lastAuditResult`, `errorCount`, `auditCount`, `terminationReason`, `completedAt`, `parentSessionId`, `inPlace`
- **Two-Phase Cycle**: Alternates between coding (Code agent works on the task) and auditing (Auditor agent reviews changes). Audit findings feed back into the next coding iteration
- **Completion Criteria**: Requires the `completionPromise` to be detected in `<promise>` tags AND `minAudits` (default 1) audit iterations before marking the loop as completed. Without a `completionPromise`, the loop only terminates via other conditions (max iterations, errors, cancellation, etc.)
- **Error Handling**: Tracks consecutive errors with `MAX_RETRIES` (3). If 3 consecutive iterations fail, the loop terminates with reason `error_max_retries`
@@ -425,7 +425,7 @@ No parameters required.
Returns a list of all stored keys with their values and expiration times. Useful for debugging or inspecting current project state.
### ralph-cancel
### memory-loop-cancel
Cancel an active Ralph loop and optionally clean up the worktree.
@@ -433,7 +433,7 @@ Cancel an active Ralph loop and optionally clean up the worktree.
|-----------|------|----------|-------------|
| `name` | string | No | Worktree name of the loop to cancel (auto-selects if only one active) |
### ralph-status
### memory-loop-status
Check the status of Ralph loops. With no arguments, lists all active loops for the current project. Pass a worktree name for detailed status.
@@ -443,7 +443,7 @@ Check the status of Ralph loops. With no arguments, lists all active loops for t
Returns iteration count, current phase, audit results, model configuration, and termination status.
### memory-plan-ralph
### memory-loop
Execute an architect plan using a Ralph iterative development loop. Designed to be called by the Architect agent after the user approves a plan with the "Execute with Ralph loop" or "Ralph in place" option.
@@ -471,7 +471,7 @@ The Architect and Code agents work together in a plan-then-execute pattern. The
3. **Review the plan** — the Architect presents a structured plan with objectives, phases, and decisions for your approval
4. **Approve the plan** — choose an execution mode:
- **Approve plan** → `memory-plan-execute` creates a new Code session with the plan
- **Execute with Ralph loop** → `memory-plan-ralph` runs the plan in an isolated worktree with iterative coding/auditing
- **Execute with Ralph loop** → `memory-loop` runs the plan in an isolated worktree with iterative coding/auditing
- **Ralph in place** → Same as Ralph loop but in the current directory (no worktree isolation)
- **Reject plan** → Cancel
5. **Switch to the new session** — the Code agent executes the plan phase by phase
@@ -497,7 +497,7 @@ Or set it from the UI: **Settings > Memory Plugin > Execution Model**.
!!! tip "Cost Optimization"
With this setup, only the planning phase uses the expensive model. The Code session — which typically consumes far more tokens implementing the plan — runs on the cheaper model. The Architect's plan provides enough structure and detail that the Code agent doesn't need the same level of reasoning capability.
### Ralph Loop
### Loop
The Ralph loop is an iterative development system that alternates between coding and auditing phases until the task is complete.
@@ -515,7 +515,7 @@ The Ralph loop is an iterative development system that alternates between coding
- **Error limit**: 3 consecutive failures (`MAX_RETRIES`)
- **Stall timeout**: 5 consecutive stalls detected by the watchdog (`MAX_CONSECUTIVE_STALLS`)
- **Worktree failure**: The worktree becomes unavailable
- **Cancelled**: User cancels via `ralph-cancel` or `/cancel-ralph`
- **Cancelled**: User cancels via `memory-loop-cancel` or `/cancel-loop`
- **User abort**: Session is aborted
#### Worktree vs In-Place
@@ -582,7 +582,7 @@ During a Ralph loop, certain tools are blocked to keep the agent focused:
- `question` — No interactive questions; work autonomously
- `memory-plan-execute` — Cannot start new plan sessions
- `memory-plan-ralph` — Cannot start nested Ralph loops
- `memory-loop` — Cannot start nested Ralph loops
Blocking is enforced via `tool.execute.before` (throws error) with `tool.execute.after` as defense in depth.
@@ -603,8 +603,8 @@ The fallback is permanent within a loop — once triggered, the `modelFailed` fl
| Command | Description |
|---------|-------------|
| `/ralph-loop <prompt>` | Start a Ralph loop (delegates to memory-plan-ralph) |
| `/cancel-ralph` | Cancel the active Ralph loop |
| `/loop <prompt>` | Start a Ralph loop (delegates to memory-loop) |
| `/cancel-loop` | Cancel the active Ralph loop |
---
@@ -655,9 +655,9 @@ The Architect agent follows a Research → Design → Plan → Execute workflow:
1. **Research** — Reads relevant files, searches the codebase, checks memory for conventions and decisions
2. **Design** — Considers approaches, weighs tradeoffs, asks clarifying questions
3. **Plan** — Presents a structured plan with objectives, phases, decisions, conventions, and key context
4. **Execute** — When the user approves via the question tool, calls `memory-plan-execute` or `memory-plan-ralph` depending on the chosen execution mode.
4. **Execute** — When the user approves via the question tool, calls `memory-plan-execute` or `memory-loop` depending on the chosen execution mode.
The Architect is the only agent with access to `memory-plan-execute` and `memory-plan-ralph`. Plans must be fully self-contained since the Code agent receiving them has no access to the Architect's conversation.
The Architect is the only agent with access to `memory-plan-execute` and `memory-loop`. Plans must be fully self-contained since the Code agent receiving them has no access to the Architect's conversation.
### Auditor Agent (subagent)
@@ -669,7 +669,7 @@ The Architect is the only agent with access to `memory-plan-execute` and `memory
The Auditor agent is a read-only subagent invoked by other agents via the Task tool to review diffs, commits, branches, or PRs. It checks changes against stored project conventions and decisions, then returns a structured review summary with issues (bug/warning/suggestion), observations, and next steps.
The agent can read memory (`memory-read`) but cannot write, edit, or delete memories. It also cannot execute plans — `memory-plan-execute`, `memory-plan-ralph`, `memory-health`, `memory-write`, `memory-edit`, and `memory-delete` are excluded.
The agent can read memory (`memory-read`) but cannot write, edit, or delete memories. It also cannot execute plans — `memory-plan-execute`, `memory-loop`, `memory-health`, `memory-write`, `memory-edit`, and `memory-delete` are excluded.
The Auditor persists review findings to the KV store (key pattern: `review-finding:<file_path>:<line_number>`) and retrieves past findings at the start of every review for continuity. Each finding is a JSON object containing severity, file, line, description, scenario, status, date, and branch. Only bugs and warnings are persisted — suggestions are not stored. Resolved findings are deleted during subsequent reviews. See [Review Finding Persistence](#review-finding-persistence) for the full lifecycle.
@@ -691,8 +691,8 @@ The default agent is set to `code`.
| Command | Description | Agent | Mode |
|---------|-------------|-------|------|
| `/review` | Run a code review on current changes | auditor | subtask |
| `/ralph-loop` | Start a Ralph loop (delegates to memory-plan-ralph) | code | direct |
| `/cancel-ralph` | Cancel the active Ralph loop | code | direct |
| `/loop` | Start a Ralph loop (delegates to memory-loop) | code | direct |
| `/cancel-loop` | Cancel the active Ralph loop | code | direct |
---
@@ -748,7 +748,7 @@ Memory injection is controlled independently by `memoryInjection.enabled` (defau
### tool.execute.before
Blocks certain tools during active Ralph loops to keep the agent focused on the current task. Throws an error with a descriptive message when a blocked tool is called. Blocked tools: `question`, `memory-plan-execute`, `memory-plan-ralph`.
Blocks certain tools during active Ralph loops to keep the agent focused on the current task. Throws an error with a descriptive message when a blocked tool is called. Blocked tools: `question`, `memory-plan-execute`, `memory-loop`.
### tool.execute.after
+1 -1
View File
@@ -68,7 +68,7 @@ OpenCode Manager provides a comprehensive web interface for managing OpenCode AI
- **Automatic Extraction** - Durable knowledge extracted after session compaction
- **Compaction Awareness** - Injects project memories into compaction context
- **Architect → Code** - Plan with a smart model, execute with a fast model for cost-optimized workflows
- **Ralph Loops** - Iterative development with automatic auditing in isolated worktrees
- **Loops** - Iterative development with automatic auditing in isolated worktrees
[Learn more →](memory.md)
+5 -5
View File
@@ -1,6 +1,6 @@
import { fetchWrapper, fetchWrapperVoid } from './fetchWrapper'
import { API_BASE_URL } from '@/config'
import type { Memory, MemoryStats, CreateMemoryRequest, UpdateMemoryRequest, PluginConfig, KvEntry, CreateKvEntryRequest, UpdateKvEntryRequest, RalphState } from '@opencode-manager/shared/types'
import type { Memory, MemoryStats, CreateMemoryRequest, UpdateMemoryRequest, PluginConfig, KvEntry, CreateKvEntryRequest, UpdateKvEntryRequest, LoopState } from '@opencode-manager/shared/types'
export async function listMemories(filters?: {
projectId?: string
@@ -123,12 +123,12 @@ export async function updateKvEntry(projectId: string, key: string, data: Update
})
}
export async function getRalphStatus(repoId: number): Promise<{ loops: RalphState[]; projectId?: string | null }> {
return fetchWrapper(`${API_BASE_URL}/api/memory/ralph/status?repoId=${repoId}`)
export async function getLoopStatus(repoId: number): Promise<{ loops: LoopState[]; projectId?: string | null }> {
return fetchWrapper(`${API_BASE_URL}/api/memory/loop/status?repoId=${repoId}`)
}
export async function cancelRalphLoop(repoId: number, sessionId: string): Promise<{ cancelled: boolean; worktreeName?: string }> {
return fetchWrapper(`${API_BASE_URL}/api/memory/ralph/cancel`, {
export async function cancelLoop(repoId: number, sessionId: string): Promise<{ cancelled: boolean; worktreeName?: string }> {
return fetchWrapper(`${API_BASE_URL}/api/memory/loop/cancel`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ repoId, sessionId }),
@@ -1,17 +1,17 @@
import { Loader2, CheckCircle2, XCircle, Ban, AlertCircle } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import type { RalphState } from '@opencode-manager/shared'
import type { LoopState } from '@opencode-manager/shared'
interface RepoRalphListProps {
interface RepoLoopListProps {
isLoading: boolean
data: RalphState[] | undefined
data: LoopState[] | undefined
error: Error | null
onCancel: (sessionId: string) => void
pendingSessionId: string | null
}
function StatusIcon({ loop }: { loop: RalphState }) {
function StatusIcon({ loop }: { loop: LoopState }) {
if (loop.active) return <Loader2 className="h-4 w-4 animate-spin text-blue-400" />
if (loop.terminationReason === 'completed') return <CheckCircle2 className="h-4 w-4 text-green-400" />
if (loop.terminationReason === 'cancelled' || loop.terminationReason === 'user_aborted') return <Ban className="h-4 w-4 text-yellow-400" />
@@ -28,7 +28,7 @@ function formatDuration(startedAt: string, completedAt?: string): string {
return `${Math.floor(minutes / 60)}h ${minutes % 60}m`
}
export function RepoRalphList({ isLoading, data, error, onCancel, pendingSessionId }: RepoRalphListProps) {
export function RepoLoopList({ isLoading, data, error, onCancel, pendingSessionId }: RepoLoopListProps) {
if (isLoading) {
return (
<div className="flex items-center justify-center p-8">
@@ -41,7 +41,7 @@ export function RepoRalphList({ isLoading, data, error, onCancel, pendingSession
return (
<div className="flex items-center gap-2 p-6 text-destructive">
<AlertCircle className="h-4 w-4" />
<span className="text-sm">Failed to load Ralph status</span>
<span className="text-sm">Failed to load loop status</span>
</div>
)
}
@@ -49,7 +49,7 @@ export function RepoRalphList({ isLoading, data, error, onCancel, pendingSession
if (!data?.length) {
return (
<div className="flex flex-col items-center justify-center p-8 text-muted-foreground">
<span className="text-sm">No Ralph loops found</span>
<span className="text-sm">No loops found</span>
</div>
)
}
@@ -1,13 +1,13 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { getRalphStatus, cancelRalphLoop } from '@/api/memory'
import { getLoopStatus, cancelLoop } from '@/api/memory'
import { showToast } from '@/lib/toast'
export function useRalphStatus(repoId: number | undefined, open: boolean) {
export function useLoopStatus(repoId: number | undefined, open: boolean) {
const queryClient = useQueryClient()
const { data, isLoading, error } = useQuery({
queryKey: ['ralph-status', repoId],
queryFn: () => getRalphStatus(repoId!),
queryKey: ['memory-loop-status', repoId],
queryFn: () => getLoopStatus(repoId!),
enabled: open && !!repoId,
staleTime: 0,
refetchInterval: ({ state }) => {
@@ -18,16 +18,16 @@ export function useRalphStatus(repoId: number | undefined, open: boolean) {
const cancelMutation = useMutation({
mutationFn: ({ sessionId }: { sessionId: string }) =>
cancelRalphLoop(repoId!, sessionId),
cancelLoop(repoId!, sessionId),
onSuccess: (result) => {
if (result.cancelled) {
queryClient.invalidateQueries({ queryKey: ['ralph-status', repoId] })
queryClient.invalidateQueries({ queryKey: ['memory-loop-status', repoId] })
} else {
showToast.error('Ralph loop is no longer active')
showToast.error('Memory loop is no longer active')
}
},
onError: () => {
showToast.error('Unable to cancel the Ralph loop. Please try again.')
showToast.error('Unable to cancel the memory loop. Please try again.')
},
})
@@ -36,10 +36,10 @@ export function useRalphStatus(repoId: number | undefined, open: boolean) {
return { data, isLoading, error, cancelMutation, pendingSessionId }
}
export function useRalphActiveCount(repoId: number | undefined, enabled: boolean) {
export function useLoopActiveCount(repoId: number | undefined, enabled: boolean) {
const { data } = useQuery({
queryKey: ['ralph-status', repoId],
queryFn: () => getRalphStatus(repoId!),
queryKey: ['memory-loop-status', repoId],
queryFn: () => getLoopStatus(repoId!),
enabled: enabled && !!repoId,
staleTime: 0,
refetchInterval: 10000,
+2 -2
View File
@@ -3,7 +3,7 @@ import { useMemo, useRef, useEffect, useCallback, useState } from "react";
import { OpenCodeClient } from "../api/opencode";
import { API_BASE_URL } from "../config";
import { fetchWrapper } from "../api/fetchWrapper";
import { cancelRalphLoop } from "../api/memory";
import { cancelLoop } from "../api/memory";
import type {
Message,
Part,
@@ -544,7 +544,7 @@ export const useAbortSession = (
attemptAbort();
if (repoId) {
cancelRalphLoop(repoId, targetSessionID).catch(() => {})
cancelLoop(repoId, targetSessionID).catch(() => {})
}
retryIntervalRef.current = setInterval(() => {
+10 -10
View File
@@ -3,7 +3,7 @@ import { useParams } from 'react-router-dom'
import { useQuery } from '@tanstack/react-query'
import { getRepo } from '@/api/repos'
import { useProjectSummary, useKvEntries } from '@/hooks/useMemories'
import { useRalphStatus } from '@/hooks/useRalphStatus'
import { useLoopStatus } from '@/hooks/useLoopStatus'
import { Header } from '@/components/ui/header'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
@@ -14,7 +14,7 @@ import { getRepoDisplayName } from '@/lib/utils'
import { MemoryList } from '@/components/memory/MemoryList'
import { MemoryFormDialog } from '@/components/memory/MemoryFormDialog'
import { KvList } from '@/components/memory/KvList'
import { RepoRalphList } from '@/components/repo/RepoRalphList'
import { RepoLoopList } from '@/components/repo/RepoLoopList'
export function Memories() {
const { id } = useParams<{ id: string }>()
@@ -30,7 +30,7 @@ export function Memories() {
const { data: projectSummary, isLoading: projectSummaryLoading } = useProjectSummary(repoId)
const { data: kvEntries } = useKvEntries(projectSummary?.projectId ?? undefined)
const { data: ralphData, isLoading: ralphLoading, error: ralphError, cancelMutation, pendingSessionId } = useRalphStatus(repoId, activeTab === 'ralph')
const { data: loopData, isLoading: loopLoading, error: loopError, cancelMutation, pendingSessionId } = useLoopStatus(repoId, activeTab === 'loops')
const projectId = projectSummary?.projectId ?? null
const stats = projectSummary?.stats ?? null
@@ -128,9 +128,9 @@ export function Memories() {
<Key className="w-4 h-4 mr-2" />
Key-Value
</TabsTrigger>
<TabsTrigger value="ralph">
<TabsTrigger value="loops">
<Bot className="w-4 h-4 mr-2" />
Ralph
Loops
</TabsTrigger>
</TabsList>
<TabsContent value="memories">
@@ -139,11 +139,11 @@ export function Memories() {
<TabsContent value="kv">
<KvList projectId={projectId ?? undefined} />
</TabsContent>
<TabsContent value="ralph">
<RepoRalphList
isLoading={ralphLoading}
data={ralphData?.loops}
error={ralphError}
<TabsContent value="loops">
<RepoLoopList
isLoading={loopLoading}
data={loopData?.loops}
error={loopError}
onCancel={(sessionId) => cancelMutation.mutate({ sessionId })}
pendingSessionId={pendingSessionId}
/>
+9 -9
View File
@@ -78,23 +78,23 @@ Ephemeral key-value storage for project state with automatic TTL-based expiratio
| `memory-kv-list` | List all active KV entries for the project. Optionally filter by key prefix. |
| `memory-kv-delete` | Delete a key-value pair by key |
### Ralph Loop Tools
### Loop Tools
Iterative development loops with automatic auditing. Runs in an isolated git worktree by default, or in the current directory with `inPlace`.
| Tool | Description |
|------|-------------|
| `ralph-cancel` | Cancel an active Ralph loop by worktree name |
| `ralph-status` | Check status of Ralph loops. Supports `restart` to resume inactive loops. |
| `memory-plan-ralph` | Execute an architect plan using a Ralph iterative loop. Supports `inPlace` parameter. |
| `memory-loop-cancel` | Cancel an active Ralph loop by worktree name |
| `memory-loop-status` | Check status of Ralph loops. Supports `restart` to resume inactive loops. |
| `memory-loop` | Execute an architect plan using a Ralph iterative loop. Supports `inPlace` parameter. |
## Slash Commands
| Command | Description | Agent |
|---------|-------------|-------|
| `/review` | Run a code review on current changes | auditor (subtask) |
| `/ralph-loop` | Start a Ralph loop (delegates to memory-plan-ralph) | code |
| `/cancel-ralph` | Cancel the active Ralph loop | code |
| `/loop` | Start a Ralph loop (delegates to memory-loop) | code |
| `/cancel-loop` | Cancel the active Ralph loop | code |
## CLI
@@ -259,7 +259,7 @@ You can edit this file to customize settings. The file is created only if it doe
},
"executionModel": "",
"auditorModel": "",
"ralph": {
"loop": {
"enabled": true,
"defaultMaxIterations": 15,
"cleanupWorktree": false,
@@ -351,14 +351,14 @@ After the architect presents a plan, the user approves via one of four execution
- **New session** — Creates a new Code session via `memory-plan-execute`
- **Execute here** — Executes the plan in the current session (code agent takes over immediately)
- **Ralph (worktree)** — Runs the plan in an isolated git worktree with iterative coding/auditing via `memory-plan-ralph`
- **Ralph (worktree)** — Runs the plan in an isolated git worktree with iterative coding/auditing via `memory-loop`
- **Ralph (in place)** — Same as Ralph worktree but runs in the current directory (no worktree isolation)
Set `executionModel` in your config to a fast model (e.g., Haiku) and use a smart model (e.g., Opus) for the architect session.
See the [full workflow guide](https://chriswritescode-dev.github.io/opencode-manager/features/memory/#architect--code) for setup details.
## Ralph Loop
## Loop
The Ralph loop is an iterative development system that alternates between coding and auditing phases:
+7 -7
View File
@@ -45,7 +45,7 @@ When referencing code, use the pattern \`file_path:line_number\` for easy naviga
## Constraints
You are in READ-ONLY mode. You must NOT edit files, run destructive commands, or make any changes. You may only read, search, and analyze. Formalize the plan and present it for the user for approval before proceeding. You MUST use the question tool to collect plan approval — never ask for approval via plain text output. Do NOT call memory-plan-execute or memory-plan-ralph until the user explicitly approves via the question tool.
You are in READ-ONLY mode. You must NOT edit files, run destructive commands, or make any changes. You may only read, search, and analyze. Formalize the plan and present it for the user for approval before proceeding. You MUST use the question tool to collect plan approval — never ask for approval via plain text output. Do NOT call memory-plan-execute or memory-loop until the user explicitly approves via the question tool.
## Memory Integration
@@ -91,9 +91,9 @@ KV entries are scoped to the current project and expire after 7 days. Use this f
4. **Approve** — After presenting the plan, you MUST call the question tool to get explicit approval. Do NOT ask for approval via plain text — always use the question tool with these options:
- "New session" — Create a new session and send the plan to the code agent
- "Execute here" — Execute the plan in the current session using the code agent (same session, no context switch)
- "Ralph (worktree)" — Execute using Ralph's iterative development loop in an isolated git worktree
- "Ralph (in place)" — Execute using Ralph's iterative development loop in the current directory
Only proceed to call memory-plan-execute or memory-plan-ralph after the user selects an option via the question tool.
- "Loop (worktree)" — Execute using iterative development loop in an isolated git worktree
- "Loop" — Execute using iterative development loop in the current directory
Only proceed to call memory-plan-execute or memory-loop after the user selects an option via the question tool.
## Plan Format
@@ -113,12 +113,12 @@ All execution modes require a **title** — a short descriptive label for the se
### Parameter Reference
| Option | Tool | inPlace | Plan Content |
| Option | Tool | worktree | Plan Content |
|---|---|---|---|
| New session | memory-plan-execute | false | Full self-contained plan |
| Execute here | memory-plan-execute | true | "Execute the implementation plan from this conversation. Review all phases above and implement each one." |
| Ralph (worktree) | memory-plan-ralph | false | Full self-contained plan |
| Ralph (in place) | memory-plan-ralph | true | Full self-contained plan |
| Loop (worktree) | memory-loop | true | Full self-contained plan |
| Loop | memory-loop | false | Full self-contained plan |
"Full self-contained" means the plan must include every file path, implementation detail, code pattern, phase dependency, verification step, and gotcha. The receiving agent starts with zero context. Do NOT summarize, abbreviate, or include <promise> tags.
`,
+1 -1
View File
@@ -9,7 +9,7 @@ export const auditorAgent: AgentDefinition = {
mode: 'subagent',
temperature: 0.0,
tools: {
exclude: ['memory-plan-execute', 'memory-plan-ralph', 'memory-health', 'memory-delete', 'memory-write', 'memory-edit'],
exclude: ['memory-plan-execute', 'memory-loop', 'memory-health', 'memory-delete', 'memory-write', 'memory-edit'],
},
systemPrompt: `You are a code auditor with access to project memory. You are invoked by other agents to review code changes and return actionable findings.
+1 -1
View File
@@ -9,7 +9,7 @@ export const librarianAgent: AgentDefinition = {
mode: 'subagent',
temperature: 0.0,
tools: {
exclude: ['memory-plan-execute', 'memory-plan-ralph', 'memory-health', 'memory-kv-set', 'memory-kv-get', 'memory-kv-list'],
exclude: ['memory-plan-execute', 'memory-loop', 'memory-health', 'memory-kv-set', 'memory-kv-get', 'memory-kv-list'],
},
systemPrompt: `You are a memory management agent. Your purpose is to capture, organize, and retrieve knowledge that persists across sessions.
+18 -16
View File
@@ -1,4 +1,4 @@
import type { RalphState } from '../../services/ralph'
import type { LoopState } from '../../services/loop'
import { openDatabase, confirm } from '../utils'
import { execSync, spawnSync } from 'child_process'
import { existsSync } from 'fs'
@@ -25,10 +25,10 @@ export async function run(argv: CancelArgs): Promise<void> {
if (projectId) {
query = 'SELECT project_id, key, data FROM project_kv WHERE project_id = ? AND key LIKE ? AND expires_at > ?'
params = [projectId, 'ralph:%', now]
params = [projectId, 'loop:%', now]
} else {
query = 'SELECT project_id, key, data FROM project_kv WHERE key LIKE ? AND expires_at > ?'
params = ['ralph:%', now]
params = ['loop:%', now]
}
let rows: Array<{ project_id: string; key: string; data: string }>
@@ -40,30 +40,32 @@ export async function run(argv: CancelArgs): Promise<void> {
if (rows.length === 0) {
console.log('')
console.log('No active Ralph loops.')
console.log('No active memory loops.')
console.log('')
return
}
const loops: Array<{ state: RalphState; row: { project_id: string; key: string; data: string } }> = []
const loops: Array<{ state: LoopState; row: { project_id: string; key: string; data: string } }> = []
for (const row of rows) {
try {
const state = JSON.parse(row.data) as RalphState
const state = JSON.parse(row.data) as LoopState
if (state.active) {
loops.push({ state, row })
}
} catch {}
} catch (err) {
console.error(`Failed to parse memory state for key ${row.key}:`, err)
}
}
if (loops.length === 0) {
console.log('')
console.log('No active Ralph loops.')
console.log('No active memory loops.')
console.log('')
return
}
let loopToCancel: { state: RalphState; row: { project_id: string; key: string; data: string } } | undefined
let loopToCancel: { state: LoopState; row: { project_id: string; key: string; data: string } } | undefined
if (argv.name) {
const { match, candidates } = findPartialMatch(argv.name, loops, (l) => [
@@ -81,7 +83,7 @@ export async function run(argv: CancelArgs): Promise<void> {
}
if (!match && candidates.length === 0) {
console.error(`Ralph loop not found: ${argv.name}`)
console.error(`Memory loop not found: ${argv.name}`)
console.error('')
console.error('Active loops:')
for (const l of loops) {
@@ -97,7 +99,7 @@ export async function run(argv: CancelArgs): Promise<void> {
loopToCancel = loops[0]
} else {
console.log('')
console.log('Multiple active Ralph loops. Please specify which one to cancel:')
console.log('Multiple active memory loops. Please specify which one to cancel:')
console.log('')
for (const l of loops) {
console.log(` - ${l.state.worktreeName}`)
@@ -117,7 +119,7 @@ export async function run(argv: CancelArgs): Promise<void> {
const { state } = loopToCancel
console.log('')
console.log(`Ralph Loop to Cancel:`)
console.log(`Memory Loop to Cancel:`)
console.log(` Worktree: ${state.worktreeName}`)
console.log(` Session: ${state.sessionId}`)
console.log(` Iteration: ${state.iteration}/${state.maxIterations}`)
@@ -127,7 +129,7 @@ export async function run(argv: CancelArgs): Promise<void> {
}
console.log('')
const shouldProceed = argv.force || await confirm(`Cancel Ralph loop '${state.worktreeName}'`)
const shouldProceed = argv.force || await confirm(`Cancel memory loop '${state.worktreeName}'`)
if (!shouldProceed) {
console.log('Cancelled.')
@@ -147,9 +149,9 @@ export async function run(argv: CancelArgs): Promise<void> {
loopToCancel.row.key,
)
console.log(`Cancelled Ralph loop: ${state.worktreeName}`)
console.log(`Cancelled memory loop: ${state.worktreeName}`)
if (argv.cleanup && state.worktreeDir && !state.inPlace) {
if (argv.cleanup && state.worktreeDir && state.worktree) {
if (existsSync(state.worktreeDir)) {
try {
const gitCommonDir = execSync('git rev-parse --git-common-dir', { cwd: state.worktreeDir, encoding: 'utf-8' }).trim()
@@ -174,7 +176,7 @@ export async function run(argv: CancelArgs): Promise<void> {
export function help(): void {
console.log(`
Cancel a Ralph loop
Cancel a memory loop
Usage:
ocm-mem cancel [name] [options]
+24 -23
View File
@@ -1,11 +1,11 @@
import type { RalphState } from '../../services/ralph'
import type { LoopState } from '../../services/loop'
import { openDatabase } from '../utils'
import { formatSessionOutput, formatAuditResult } from '../../utils/ralph-format'
import { formatSessionOutput, formatAuditResult } from '../../utils/loop-format'
import { createOpencodeClient } from '@opencode-ai/sdk/v2'
import { fetchSessionOutput } from '../../services/ralph'
import { fetchSessionOutput } from '../../services/loop'
import { findPartialMatch, filterByPartial } from '../../utils/partial-match'
interface RalphLoopInfo {
interface LoopInfo {
sessionId: string
worktreeName: string
worktreeBranch?: string
@@ -51,13 +51,14 @@ export async function run(argv: StatusArgs): Promise<void> {
try {
if (argv.listWorktrees) {
const rows = db.prepare('SELECT key, data FROM project_kv WHERE key LIKE ? AND expires_at > ?').all('ralph:%', Date.now()) as Array<{ key: string; data: string }>
const states: RalphState[] = []
const rows = db.prepare('SELECT key, data FROM project_kv WHERE key LIKE ? AND expires_at > ?').all('loop:%', Date.now()) as Array<{ key: string; data: string }>
const states: LoopState[] = []
for (const row of rows) {
try {
const state = JSON.parse(row.data) as RalphState
const state = JSON.parse(row.data) as LoopState
states.push(state)
} catch {
} catch (err) {
console.error(`Failed to parse memory state for key ${row.key}:`, err)
}
}
const filtered = filterByPartial(argv.listWorktreesFilter, states, (s) => [s.worktreeName, s.worktreeBranch])
@@ -76,10 +77,10 @@ export async function run(argv: StatusArgs): Promise<void> {
if (projectId) {
query = 'SELECT key, data FROM project_kv WHERE project_id = ? AND key LIKE ? AND expires_at > ?'
params = [projectId, 'ralph:%', now]
params = [projectId, 'loop:%', now]
} else {
query = 'SELECT key, data FROM project_kv WHERE key LIKE ? AND expires_at > ?'
params = ['ralph:%', now]
params = ['loop:%', now]
}
let rows: Array<{ key: string; data: string }>
@@ -89,12 +90,12 @@ export async function run(argv: StatusArgs): Promise<void> {
rows = []
}
const activeLoops: RalphLoopInfo[] = []
const recentLoops: Array<{ state: RalphState; row: { key: string; data: string } }> = []
const activeLoops: LoopInfo[] = []
const recentLoops: Array<{ state: LoopState; row: { key: string; data: string } }> = []
for (const row of rows) {
try {
const state = JSON.parse(row.data) as RalphState
const state = JSON.parse(row.data) as LoopState
if (state.active && state.sessionId && state.worktreeName && state.iteration != null && state.maxIterations != null && state.phase && state.startedAt) {
activeLoops.push({
sessionId: state.sessionId,
@@ -115,7 +116,7 @@ export async function run(argv: StatusArgs): Promise<void> {
const worktreeName = argv.name
if (worktreeName) {
type LoopUnion = { type: 'active'; loop: RalphLoopInfo } | { type: 'recent'; loop: typeof recentLoops[number] }
type LoopUnion = { type: 'active'; loop: LoopInfo } | { type: 'recent'; loop: typeof recentLoops[number] }
const allLoops: LoopUnion[] = [
...activeLoops.map((l) => ({ type: 'active' as const, loop: l })),
...recentLoops.map((l) => ({ type: 'recent' as const, loop: l })),
@@ -163,7 +164,7 @@ export async function run(argv: StatusArgs): Promise<void> {
if (matchedLoop.type === 'active') {
const row = rows.find((r) => {
try {
const state = JSON.parse(r.data) as RalphState
const state = JSON.parse(r.data) as LoopState
return state.worktreeName === resolvedWorktreeName
} catch {
return false
@@ -175,7 +176,7 @@ export async function run(argv: StatusArgs): Promise<void> {
process.exit(1)
}
const state = JSON.parse(row.data) as RalphState
const state = JSON.parse(row.data) as LoopState
const startedAt = state.startedAt!
const duration = Date.now() - new Date(startedAt).getTime()
const hours = Math.floor(duration / (1000 * 60 * 60))
@@ -183,14 +184,14 @@ export async function run(argv: StatusArgs): Promise<void> {
const seconds = Math.floor((duration % (1000 * 60)) / 1000)
console.log('')
console.log(`Ralph Loop: ${state.worktreeName}`)
console.log(`Memory Loop: ${state.worktreeName}`)
console.log(` Session ID: ${state.sessionId}`)
console.log(` Worktree: ${state.worktreeName}`)
if (state.worktreeBranch) {
console.log(` Branch: ${state.worktreeBranch}`)
}
console.log(` Worktree Dir: ${state.worktreeDir}`)
if (state.inPlace) {
if (!state.worktree) {
console.log(` Mode: in-place`)
}
console.log(` Phase: ${state.phase}`)
@@ -227,14 +228,14 @@ export async function run(argv: StatusArgs): Promise<void> {
const seconds = Math.floor((duration % (1000 * 60)) / 1000)
console.log('')
console.log(`Ralph Loop (Completed): ${state.worktreeName}`)
console.log(`Memory Loop (Completed): ${state.worktreeName}`)
console.log(` Session ID: ${state.sessionId}`)
console.log(` Worktree: ${state.worktreeName}`)
if (state.worktreeBranch) {
console.log(` Branch: ${state.worktreeBranch}`)
}
console.log(` Worktree Dir: ${state.worktreeDir}`)
if (state.inPlace) {
if (!state.worktree) {
console.log(` Mode: in-place (completed)`)
}
console.log(` Iteration: ${state.iteration}/${state.maxIterations}`)
@@ -260,7 +261,7 @@ export async function run(argv: StatusArgs): Promise<void> {
} else {
if (activeLoops.length > 0) {
console.log('')
console.log('Active Ralph Loops:')
console.log('Active Memory Loops:')
console.log('')
for (const loop of activeLoops) {
@@ -303,7 +304,7 @@ export async function run(argv: StatusArgs): Promise<void> {
if (activeLoops.length === 0 && recentLoops.length === 0) {
console.log('')
console.log('No Ralph loops found.')
console.log('No memory loops found.')
console.log('')
} else {
console.log("Run 'ocm-mem status <name>' for detailed information.")
@@ -317,7 +318,7 @@ export async function run(argv: StatusArgs): Promise<void> {
export function help(): void {
console.log(`
Show Ralph loop status
Show memory loop status
Usage:
ocm-mem status [options]
+6 -6
View File
@@ -17,17 +17,17 @@ const PLUGIN_COMMANDS: Record<string, { template: string; description: string; a
subtask: true,
template: 'Review the current code changes. $ARGUMENTS',
},
'ralph-loop': {
description: 'Start a Ralph iterative development loop in a worktree',
'memory-loop': {
description: 'Start a memory iterative development loop in a worktree',
agent: 'code',
subtask: false,
template: 'Use the memory-plan-ralph tool to start a Ralph loop. Use the following as the plan: $ARGUMENTS. Derive a short title from the plan.',
template: 'Use the memory-loop tool to start a loop. Use the following as the plan: $ARGUMENTS. Derive a short title from the plan.',
},
'cancel-ralph': {
description: 'Cancel the active Ralph loop',
'memory-loop-cancel': {
description: 'Cancel the active memory loop',
agent: 'code',
subtask: false,
template: 'Use the ralph-cancel tool to cancel the active Ralph loop. $ARGUMENTS',
template: 'Use the memory-loop-cancel tool to cancel the active memory loop. $ARGUMENTS',
},
}
+1 -1
View File
@@ -7,4 +7,4 @@ export {
extractCompactionSummary,
} from './compaction-utils'
export { createMemoryInjectionHook, type MemoryInjectionHook } from './memory-injection'
export { createRalphEventHandler, type RalphEventHandler } from './ralph'
export { createLoopEventHandler, type LoopEventHandler } from './loop'
@@ -1,13 +1,13 @@
import type { PluginInput } from '@opencode-ai/plugin'
import type { OpencodeClient } from '@opencode-ai/sdk/v2'
import type { RalphService, RalphState } from '../services/ralph'
import { MAX_RETRIES, MAX_CONSECUTIVE_STALLS } from '../services/ralph'
import type { Logger, PluginConfig } from '../types'
import type { LoopService, LoopState } from '../services/loop'
import { MAX_RETRIES, MAX_CONSECUTIVE_STALLS } from '../services/loop'
import type { Logger, PluginConfig, LoopConfig } from '../types'
import { parseModelString, retryWithModelFallback } from '../utils/model-fallback'
import { execSync, spawnSync } from 'child_process'
import { resolve } from 'path'
export interface RalphEventHandler {
export interface LoopEventHandler {
onEvent(input: { event: { type: string; properties?: Record<string, unknown> } }): Promise<void>
terminateAll(): void
clearAllRetryTimeouts(): void
@@ -16,22 +16,22 @@ export interface RalphEventHandler {
cancelBySessionId(sessionId: string): Promise<boolean>
}
export function createRalphEventHandler(
ralphService: RalphService,
export function createLoopEventHandler(
loopService: LoopService,
client: PluginInput['client'],
v2Client: OpencodeClient,
logger: Logger,
getConfig: () => PluginConfig,
): RalphEventHandler {
const minAudits = ralphService.getMinAudits()
): LoopEventHandler {
const minAudits = loopService.getMinAudits()
const retryTimeouts = new Map<string, NodeJS.Timeout>()
const lastActivityTime = new Map<string, number>()
const stallWatchdogs = new Map<string, NodeJS.Timeout>()
const consecutiveStalls = new Map<string, number>()
async function commitAndCleanupWorktree(state: RalphState): Promise<{ committed: boolean; cleaned: boolean }> {
if (state.inPlace) {
logger.log(`Ralph: in-place mode, skipping commit and cleanup`)
async function commitAndCleanupWorktree(state: LoopState): Promise<{ committed: boolean; cleaned: boolean }> {
if (!state.worktree) {
logger.log(`Loop: in-place mode, skipping commit and cleanup`)
return { committed: false, cleaned: false }
}
@@ -51,18 +51,18 @@ export function createRalphEventHandler(
const status = statusResult.stdout.trim()
if (status) {
const message = `ralph: ${state.worktreeName} completed after ${state.iteration} iterations`
const message = `loop: ${state.worktreeName} completed after ${state.iteration} iterations`
const commitResult = spawnSync('git', ['commit', '-m', message], { cwd: state.worktreeDir, encoding: 'utf-8' })
if (commitResult.status !== 0) {
throw new Error(commitResult.stderr || 'git commit failed')
}
committed = true
logger.log(`Ralph: committed changes on branch ${state.worktreeBranch}`)
logger.log(`Loop: committed changes on branch ${state.worktreeBranch}`)
} else {
logger.log(`Ralph: no uncommitted changes to commit on branch ${state.worktreeBranch}`)
logger.log(`Loop: no uncommitted changes to commit on branch ${state.worktreeBranch}`)
}
} catch (err) {
logger.error(`Ralph: failed to commit changes in worktree ${state.worktreeDir}`, err)
logger.error(`Loop: failed to commit changes in worktree ${state.worktreeDir}`, err)
}
if (state.worktreeDir && state.worktreeBranch) {
@@ -74,9 +74,9 @@ export function createRalphEventHandler(
throw new Error(removeResult.stderr || 'git worktree remove failed')
}
cleaned = true
logger.log(`Ralph: removed worktree ${state.worktreeDir}, branch ${state.worktreeBranch} preserved`)
logger.log(`Loop: removed worktree ${state.worktreeDir}, branch ${state.worktreeBranch} preserved`)
} catch (err) {
logger.error(`Ralph: failed to remove worktree ${state.worktreeDir}`, err)
logger.error(`Loop: failed to remove worktree ${state.worktreeDir}`, err)
}
}
@@ -98,7 +98,7 @@ export function createRalphEventHandler(
lastActivityTime.set(worktreeName, Date.now())
consecutiveStalls.set(worktreeName, 0)
const stallTimeout = ralphService.getStallTimeoutMs()
const stallTimeout = loopService.getStallTimeoutMs()
const interval = setInterval(async () => {
const lastActivity = lastActivityTime.get(worktreeName)
@@ -107,7 +107,7 @@ export function createRalphEventHandler(
const elapsed = Date.now() - lastActivity
if (elapsed < stallTimeout) return
const state = ralphService.getActiveState(worktreeName)
const state = loopService.getActiveState(worktreeName)
if (!state?.active) {
stopWatchdog(worktreeName)
return
@@ -167,7 +167,7 @@ export function createRalphEventHandler(
}
}
async function terminateLoop(worktreeName: string, state: RalphState, reason: string): Promise<void> {
async function terminateLoop(worktreeName: string, state: LoopState, reason: string): Promise<void> {
const sessionId = state.sessionId
stopWatchdog(worktreeName)
@@ -177,9 +177,9 @@ export function createRalphEventHandler(
retryTimeouts.delete(worktreeName)
}
ralphService.unregisterSession(sessionId)
loopService.unregisterSession(sessionId)
ralphService.setState(worktreeName, {
loopService.setState(worktreeName, {
...state,
active: false,
completedAt: new Date().toISOString(),
@@ -200,24 +200,24 @@ export function createRalphEventHandler(
}
}
async function handlePromptError(worktreeName: string, state: RalphState, context: string, err: unknown, retryFn?: () => Promise<void>): Promise<void> {
async function handlePromptError(worktreeName: string, state: LoopState, context: string, err: unknown, retryFn?: () => Promise<void>): Promise<void> {
const sessionId = state.sessionId
const currentState = ralphService.getActiveState(worktreeName)
const currentState = loopService.getActiveState(worktreeName)
if (!currentState?.active) {
logger.log(`Ralph: loop ${worktreeName} already terminated, ignoring error: ${context}`)
logger.log(`Loop: loop ${worktreeName} already terminated, ignoring error: ${context}`)
return
}
const nextErrorCount = (currentState.errorCount ?? 0) + 1
if (nextErrorCount < MAX_RETRIES) {
logger.error(`Ralph: ${context} (attempt ${nextErrorCount}/${MAX_RETRIES}), will retry`, err)
ralphService.setState(worktreeName, { ...currentState, errorCount: nextErrorCount })
logger.error(`Loop: ${context} (attempt ${nextErrorCount}/${MAX_RETRIES}), will retry`, err)
loopService.setState(worktreeName, { ...currentState, errorCount: nextErrorCount })
if (retryFn) {
const retryTimeout = setTimeout(async () => {
const freshState = ralphService.getActiveState(worktreeName)
const freshState = loopService.getActiveState(worktreeName)
if (!freshState?.active) {
logger.log(`Ralph: loop cancelled, skipping retry`)
logger.log(`Loop: loop cancelled, skipping retry`)
retryTimeouts.delete(worktreeName)
return
}
@@ -230,7 +230,7 @@ export function createRalphEventHandler(
retryTimeouts.set(worktreeName, retryTimeout)
}
} else {
logger.error(`Ralph: ${context} (attempt ${nextErrorCount}/${MAX_RETRIES}), giving up`, err)
logger.error(`Loop: ${context} (attempt ${nextErrorCount}/${MAX_RETRIES}), giving up`, err)
await terminateLoop(worktreeName, currentState, `error_max_retries: ${context}`)
}
}
@@ -261,12 +261,12 @@ export function createRalphEventHandler(
return { text, error }
} catch (err) {
logger.error(`Ralph: could not read session messages`, err)
logger.error(`Loop: could not read session messages`, err)
return { text: null, error: null }
}
}
async function rotateSession(worktreeName: string, state: RalphState): Promise<string> {
async function rotateSession(worktreeName: string, state: LoopState): Promise<string> {
const oldSessionId = state.sessionId
const createResult = await v2Client.session.create({
title: state.worktreeName,
@@ -285,29 +285,29 @@ export function createRalphEventHandler(
retryTimeouts.delete(worktreeName)
}
ralphService.unregisterSession(oldSessionId)
ralphService.registerSession(newSessionId, worktreeName)
loopService.unregisterSession(oldSessionId)
loopService.registerSession(newSessionId, worktreeName)
stopWatchdog(worktreeName)
startWatchdog(worktreeName)
v2Client.session.delete({ sessionID: oldSessionId, directory: state.worktreeDir }).catch((err) => {
logger.error(`Ralph: failed to delete old session ${oldSessionId}`, err)
logger.error(`Loop: failed to delete old session ${oldSessionId}`, err)
})
logger.log(`Ralph: rotated session ${oldSessionId} → ${newSessionId}`)
logger.log(`Loop: rotated session ${oldSessionId} → ${newSessionId}`)
return newSessionId
}
async function handleCodingPhase(worktreeName: string, state: RalphState): Promise<void> {
let currentState = ralphService.getActiveState(worktreeName)
async function handleCodingPhase(worktreeName: string, state: LoopState): Promise<void> {
let currentState = loopService.getActiveState(worktreeName)
if (!currentState?.active) {
logger.log(`Ralph: loop ${worktreeName} no longer active, skipping coding phase`)
logger.log(`Loop: loop ${worktreeName} no longer active, skipping coding phase`)
return
}
if (!currentState.worktreeDir) {
logger.error(`Ralph: loop ${worktreeName} missing worktreeDir in coding phase, terminating`)
logger.error(`Loop: loop ${worktreeName} missing worktreeDir in coding phase, terminating`)
await terminateLoop(worktreeName, currentState, 'missing_worktree_dir')
return
}
@@ -317,7 +317,7 @@ export function createRalphEventHandler(
const { text: textContent, error: assistantError } = await getLastAssistantInfo(currentState.sessionId, currentState.worktreeDir)
if (assistantError) {
assistantErrorDetected = true
logger.error(`Ralph: assistant error detected in coding phase: ${assistantError}`)
logger.error(`Loop: assistant error detected in coding phase: ${assistantError}`)
const isModelError = /provider|auth|model|api\s*error/i.test(assistantError)
if (isModelError) {
const nextErrorCount = (currentState.errorCount ?? 0) + 1
@@ -325,26 +325,26 @@ export function createRalphEventHandler(
await terminateLoop(worktreeName, currentState, `error_max_retries: assistant error: ${assistantError}`)
return
}
ralphService.setState(worktreeName, { ...currentState, modelFailed: true, errorCount: nextErrorCount })
logger.log(`Ralph: marking model as failed, will fall back to default model (error ${nextErrorCount}/${MAX_RETRIES})`)
currentState = ralphService.getActiveState(worktreeName)!
loopService.setState(worktreeName, { ...currentState, modelFailed: true, errorCount: nextErrorCount })
logger.log(`Loop: marking model as failed, will fall back to default model (error ${nextErrorCount}/${MAX_RETRIES})`)
currentState = loopService.getActiveState(worktreeName)!
}
}
if (textContent && currentState.completionPromise && ralphService.checkCompletionPromise(textContent, currentState.completionPromise)) {
if (textContent && currentState.completionPromise && loopService.checkCompletionPromise(textContent, currentState.completionPromise)) {
const currentAuditCount = currentState.auditCount ?? 0
if (!currentState.audit || currentAuditCount >= minAudits) {
await terminateLoop(worktreeName, currentState, 'completed')
logger.log(`Ralph loop completed: detected <promise>${currentState.completionPromise}</promise> at iteration ${currentState.iteration} (${currentAuditCount}/${minAudits} audits)`)
return
}
logger.log(`Ralph: completion promise detected but only ${currentAuditCount}/${minAudits} audits performed, continuing`)
logger.log(`Loop: completion promise detected but only ${currentAuditCount}/${minAudits} audits performed, continuing`)
}
}
if (!assistantErrorDetected && currentState.errorCount && currentState.errorCount > 0) {
ralphService.setState(worktreeName, { ...currentState, errorCount: 0 })
logger.log(`Ralph: resetting error count after successful retry in coding phase`)
currentState = ralphService.getActiveState(worktreeName)!
loopService.setState(worktreeName, { ...currentState, errorCount: 0 })
logger.log(`Loop: resetting error count after successful retry in coding phase`)
currentState = loopService.getActiveState(worktreeName)!
}
if ((currentState.maxIterations ?? 0) > 0 && (currentState.iteration ?? 0) >= (currentState.maxIterations ?? 0)) {
@@ -353,7 +353,7 @@ export function createRalphEventHandler(
}
if (currentState.audit) {
ralphService.setState(worktreeName, { ...currentState, phase: 'auditing', errorCount: 0 })
loopService.setState(worktreeName, { ...currentState, phase: 'auditing', errorCount: 0 })
logger.log(`Ralph iteration ${currentState.iteration ?? 0} complete, running auditor for session ${currentState.sessionId}`)
const auditPrompt = {
@@ -363,7 +363,7 @@ export function createRalphEventHandler(
type: 'subtask' as const,
agent: 'auditor',
description: `Post-iteration ${currentState.iteration} code review`,
prompt: ralphService.buildAuditPrompt(currentState),
prompt: loopService.buildAuditPrompt(currentState),
}],
}
@@ -392,32 +392,32 @@ export function createRalphEventHandler(
try {
activeSessionId = await rotateSession(worktreeName, currentState)
} catch (err) {
logger.error(`Ralph: session rotation failed, continuing with existing session`, err)
logger.error(`Loop: session rotation failed, continuing with existing session`, err)
}
const nextIteration = (currentState.iteration ?? 0) + 1
ralphService.setState(worktreeName, {
loopService.setState(worktreeName, {
...currentState,
sessionId: activeSessionId,
iteration: nextIteration,
errorCount: assistantErrorDetected ? currentState.errorCount : 0,
})
const continuationPrompt = ralphService.buildContinuationPrompt({ ...currentState, iteration: nextIteration })
const continuationPrompt = loopService.buildContinuationPrompt({ ...currentState, iteration: nextIteration })
logger.log(`Ralph iteration ${nextIteration} for session ${activeSessionId}`)
const currentConfig = getConfig()
const freshStateForModel = ralphService.getActiveState(worktreeName)
const ralphModel = freshStateForModel?.modelFailed
const freshStateForModel = loopService.getActiveState(worktreeName)
const loopModel = freshStateForModel?.modelFailed
? undefined
: (parseModelString(currentConfig.ralph?.model) ?? parseModelString(currentConfig.executionModel))
if (freshStateForModel?.modelFailed) {
logger.log(`Ralph: configured model previously failed, using default model`)
logger.log(`Loop: configured model previously failed, using default model`)
}
const sendContinuationPromptWithModel = async () => {
const freshState = ralphService.getActiveState(worktreeName)
const freshState = loopService.getActiveState(worktreeName)
if (!freshState?.active) {
throw new Error('loop_cancelled')
}
@@ -425,13 +425,13 @@ export function createRalphEventHandler(
sessionID: activeSessionId,
directory: freshState.worktreeDir,
parts: [{ type: 'text' as const, text: continuationPrompt }],
model: ralphModel,
model: loopModel,
})
return { data: result.data, error: result.error }
}
const sendContinuationPromptWithoutModel = async () => {
const freshState = ralphService.getActiveState(worktreeName)
const freshState = loopService.getActiveState(worktreeName)
if (!freshState?.active) {
throw new Error('loop_cancelled')
}
@@ -446,7 +446,7 @@ export function createRalphEventHandler(
const { result: promptResult, usedModel: actualModel } = await retryWithModelFallback(
sendContinuationPromptWithModel,
sendContinuationPromptWithoutModel,
ralphModel,
loopModel,
logger,
)
@@ -471,16 +471,16 @@ export function createRalphEventHandler(
consecutiveStalls.set(worktreeName, 0)
}
async function handleAuditingPhase(worktreeName: string, state: RalphState): Promise<void> {
async function handleAuditingPhase(worktreeName: string, state: LoopState): Promise<void> {
// Re-fetch and validate state to catch aborts that happened during idle event processing
let currentState = ralphService.getActiveState(worktreeName)
let currentState = loopService.getActiveState(worktreeName)
if (!currentState?.active) {
logger.log(`Ralph: loop ${worktreeName} no longer active, skipping auditing phase`)
logger.log(`Loop: loop ${worktreeName} no longer active, skipping auditing phase`)
return
}
if (!currentState.worktreeDir) {
logger.error(`Ralph: loop ${worktreeName} missing worktreeDir in auditing phase, terminating`)
logger.error(`Loop: loop ${worktreeName} missing worktreeDir in auditing phase, terminating`)
await terminateLoop(worktreeName, currentState, 'missing_worktree_dir')
return
}
@@ -490,7 +490,7 @@ export function createRalphEventHandler(
let assistantErrorDetected = false
if (assistantError) {
assistantErrorDetected = true
logger.error(`Ralph: assistant error detected in auditing phase: ${assistantError}`)
logger.error(`Loop: assistant error detected in auditing phase: ${assistantError}`)
const isModelError = /provider|auth|model|api\s*error/i.test(assistantError)
if (isModelError) {
const nextErrorCount = (currentState.errorCount ?? 0) + 1
@@ -498,16 +498,16 @@ export function createRalphEventHandler(
await terminateLoop(worktreeName, currentState, `error_max_retries: assistant error: ${assistantError}`)
return
}
ralphService.setState(worktreeName, { ...currentState, modelFailed: true, errorCount: nextErrorCount })
logger.log(`Ralph: marking model as failed, will fall back to default model (error ${nextErrorCount}/${MAX_RETRIES})`)
currentState = ralphService.getActiveState(worktreeName)!
loopService.setState(worktreeName, { ...currentState, modelFailed: true, errorCount: nextErrorCount })
logger.log(`Loop: marking model as failed, will fall back to default model (error ${nextErrorCount}/${MAX_RETRIES})`)
currentState = loopService.getActiveState(worktreeName)!
}
}
if (!assistantErrorDetected && currentState.errorCount && currentState.errorCount > 0) {
ralphService.setState(worktreeName, { ...currentState, errorCount: 0 })
logger.log(`Ralph: resetting error count after successful retry in auditing phase`)
currentState = ralphService.getActiveState(worktreeName)!
loopService.setState(worktreeName, { ...currentState, errorCount: 0 })
logger.log(`Loop: resetting error count after successful retry in auditing phase`)
currentState = loopService.getActiveState(worktreeName)!
}
const nextIteration = (currentState.iteration ?? 0) + 1
@@ -518,14 +518,14 @@ export function createRalphEventHandler(
const auditFindings = auditText ?? undefined
if (currentState.completionPromise && auditText) {
if (ralphService.checkCompletionPromise(auditText, currentState.completionPromise)) {
if (loopService.checkCompletionPromise(auditText, currentState.completionPromise)) {
// Check if minimum audits have been performed
if (!currentState.audit || newAuditCount >= minAudits) {
await terminateLoop(worktreeName, currentState, 'completed')
logger.log(`Ralph loop completed: detected <promise>${currentState.completionPromise}</promise> in audit at iteration ${currentState.iteration} (${newAuditCount}/${minAudits} audits)`)
return
}
logger.log(`Ralph: completion promise detected but only ${newAuditCount}/${minAudits} audits performed, continuing`)
logger.log(`Loop: completion promise detected but only ${newAuditCount}/${minAudits} audits performed, continuing`)
}
}
@@ -538,10 +538,10 @@ export function createRalphEventHandler(
try {
activeSessionId = await rotateSession(worktreeName, currentState)
} catch (err) {
logger.error(`Ralph: session rotation failed, continuing with existing session`, err)
logger.error(`Loop: session rotation failed, continuing with existing session`, err)
}
ralphService.setState(worktreeName, {
loopService.setState(worktreeName, {
...currentState,
sessionId: activeSessionId,
iteration: nextIteration,
@@ -551,24 +551,24 @@ export function createRalphEventHandler(
errorCount: assistantErrorDetected ? currentState.errorCount : 0,
})
const continuationPrompt = ralphService.buildContinuationPrompt(
const continuationPrompt = loopService.buildContinuationPrompt(
{ ...currentState, iteration: nextIteration },
auditFindings,
)
logger.log(`Ralph iteration ${nextIteration} for session ${activeSessionId}`)
const currentConfig = getConfig()
const freshStateForModel = ralphService.getActiveState(worktreeName)
const ralphModel = freshStateForModel?.modelFailed
const freshStateForModel = loopService.getActiveState(worktreeName)
const loopModel = freshStateForModel?.modelFailed
? undefined
: (parseModelString(currentConfig.ralph?.model) ?? parseModelString(currentConfig.executionModel))
if (freshStateForModel?.modelFailed) {
logger.log(`Ralph: configured model previously failed, using default model`)
logger.log(`Loop: configured model previously failed, using default model`)
}
const sendContinuationPromptWithModel = async () => {
const freshState = ralphService.getActiveState(worktreeName)
const freshState = loopService.getActiveState(worktreeName)
if (!freshState?.active) {
throw new Error('loop_cancelled')
}
@@ -576,13 +576,13 @@ export function createRalphEventHandler(
sessionID: activeSessionId,
directory: freshState.worktreeDir,
parts: [{ type: 'text' as const, text: continuationPrompt }],
model: ralphModel,
model: loopModel,
})
return { data: result.data, error: result.error }
}
const sendContinuationPromptWithoutModel = async () => {
const freshState = ralphService.getActiveState(worktreeName)
const freshState = loopService.getActiveState(worktreeName)
if (!freshState?.active) {
throw new Error('loop_cancelled')
}
@@ -597,13 +597,13 @@ export function createRalphEventHandler(
const { result: promptResult, usedModel: actualModel } = await retryWithModelFallback(
sendContinuationPromptWithModel,
sendContinuationPromptWithoutModel,
ralphModel,
loopModel,
logger,
)
if (promptResult.error) {
const retryFn = async () => {
const freshState = ralphService.getActiveState(worktreeName)
const freshState = loopService.getActiveState(worktreeName)
if (!freshState?.active) {
throw new Error('loop_cancelled')
}
@@ -632,10 +632,10 @@ export function createRalphEventHandler(
if (event.type === 'worktree.failed') {
const message = event.properties?.message as string
const directory = event.properties?.directory as string
logger.error(`Ralph: worktree failed: ${message}`)
logger.error(`Loop: worktree failed: ${message}`)
if (directory) {
const activeLoops = ralphService.listActive()
const activeLoops = loopService.listActive()
const affectedLoop = activeLoops.find((s) => s.worktreeDir === directory)
if (affectedLoop) {
await terminateLoop(affectedLoop.worktreeName, affectedLoop, `worktree_failed: ${message}`)
@@ -653,26 +653,26 @@ export function createRalphEventHandler(
if (!eventSessionId) return
if (isAbort) {
const worktreeName = ralphService.resolveWorktreeName(eventSessionId)
const worktreeName = loopService.resolveWorktreeName(eventSessionId)
if (!worktreeName) return
const state = ralphService.getActiveState(worktreeName)
const state = loopService.getActiveState(worktreeName)
if (state?.active) {
logger.log(`Ralph: session ${eventSessionId} aborted, terminating loop`)
logger.log(`Loop: session ${eventSessionId} aborted, terminating loop`)
await terminateLoop(worktreeName, state, 'user_aborted')
}
return
}
const worktreeName = ralphService.resolveWorktreeName(eventSessionId)
const worktreeName = loopService.resolveWorktreeName(eventSessionId)
if (!worktreeName) return
const state = ralphService.getActiveState(worktreeName)
const state = loopService.getActiveState(worktreeName)
if (state?.active) {
const errorMessage = errorProps?.error?.data?.message ?? errorName ?? 'unknown error'
logger.error(`Ralph: session error for ${eventSessionId}: ${errorMessage}`)
logger.error(`Loop: session error for ${eventSessionId}: ${errorMessage}`)
const isModelError = /provider|auth|model|api\s*error/i.test(errorMessage)
if (isModelError && !state.modelFailed) {
logger.log(`Ralph: marking model as failed, will fall back to default on next iteration`)
ralphService.setState(worktreeName, { ...state, modelFailed: true })
logger.log(`Loop: marking model as failed, will fall back to default on next iteration`)
loopService.setState(worktreeName, { ...state, modelFailed: true })
}
}
return
@@ -683,17 +683,17 @@ export function createRalphEventHandler(
const sessionId = event.properties?.sessionID as string
if (!sessionId) return
const worktreeName = ralphService.resolveWorktreeName(sessionId)
const worktreeName = loopService.resolveWorktreeName(sessionId)
if (!worktreeName) return
const state = ralphService.getActiveState(worktreeName)
const state = loopService.getActiveState(worktreeName)
if (!state || !state.active) return
try {
// Re-check state right before calling phase handler as extra safety
const freshState = ralphService.getActiveState(worktreeName)
const freshState = loopService.getActiveState(worktreeName)
if (!freshState?.active) {
logger.log(`Ralph: loop ${worktreeName} was terminated, skipping phase handler`)
logger.log(`Loop: loop ${worktreeName} was terminated, skipping phase handler`)
return
}
@@ -705,13 +705,13 @@ export function createRalphEventHandler(
await handleCodingPhase(worktreeName, freshState)
}
} catch (err) {
const freshState = ralphService.getActiveState(worktreeName)
const freshState = loopService.getActiveState(worktreeName)
await handlePromptError(worktreeName, freshState ?? state, `unhandled error in ${(freshState ?? state).phase} phase`, err)
}
}
function terminateAll(): void {
ralphService.terminateAll()
loopService.terminateAll()
}
function clearAllRetryTimeouts(): void {
@@ -725,13 +725,13 @@ export function createRalphEventHandler(
}
lastActivityTime.clear()
consecutiveStalls.clear()
logger.log('Ralph: cleared all retry timeouts')
logger.log('Loop: cleared all retry timeouts')
}
async function cancelBySessionId(sessionId: string): Promise<boolean> {
const worktreeName = ralphService.resolveWorktreeName(sessionId)
const worktreeName = loopService.resolveWorktreeName(sessionId)
if (!worktreeName) return false
const state = ralphService.getActiveState(worktreeName)
const state = loopService.getActiveState(worktreeName)
if (!state?.active) return false
await terminateLoop(worktreeName, state, 'cancelled')
return true
+138 -137
View File
@@ -4,7 +4,7 @@ import { createOpencodeClient as createV2Client } from '@opencode-ai/sdk/v2'
import { agents } from './agents'
import { createConfigHandler } from './config'
import { VERSION } from './version'
import { createSessionHooks, createMemoryInjectionHook, createRalphEventHandler } from './hooks'
import { createSessionHooks, createMemoryInjectionHook, createLoopEventHandler } from './hooks'
import { join, resolve } from 'path'
import { initializeDatabase, resolveDataDir, closeDatabase, createMetadataQuery } from './storage'
import type { MemoryService } from './services/memory'
@@ -13,21 +13,21 @@ import { createEmbeddingProvider, checkServerHealth, isServerRunning, killEmbedd
import { createMemoryService } from './services/memory'
import { createEmbeddingSyncService } from './services/embedding-sync'
import { createKvService } from './services/kv'
import { createRalphService, type RalphState, fetchSessionOutput, type RalphSessionOutput } from './services/ralph'
import { createLoopService, type LoopState, fetchSessionOutput, type LoopSessionOutput, migrateRalphKeys } from './services/loop'
import { findPartialMatch } from './utils/partial-match'
import { loadPluginConfig } from './setup'
import { resolveLogPath } from './storage'
import { createLogger, slugify } from './utils/logger'
import { stripPromiseTags } from './utils/strip-promise-tags'
import { truncate } from './cli/utils'
import { formatSessionOutput, formatAuditResult } from './utils/ralph-format'
import { formatSessionOutput, formatAuditResult } from './utils/loop-format'
import type { Database } from 'bun:sqlite'
import type { PluginConfig, CompactionConfig, HealthStatus, Logger } from './types'
import type { EmbeddingProvider } from './embedding'
import type { VecService } from './storage/vec-types'
import { createNoopVecService } from './storage/vec'
import { checkForUpdate, formatUpgradeCheck, performUpgrade } from './utils/upgrade'
import { MAX_RETRIES } from './services/ralph'
import { MAX_RETRIES } from './services/loop'
import { parseModelString, retryWithModelFallback } from './utils/model-fallback'
import { execSync, spawnSync } from 'child_process'
import { existsSync } from 'fs'
@@ -311,8 +311,9 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
const kvService = createKvService(db, logger, config.defaultKvTtlMs)
const ralphService = createRalphService(kvService, projectId, logger, config.ralph)
const ralphHandler = createRalphEventHandler(ralphService, client, v2, logger, () => config)
const loopService = createLoopService(kvService, projectId, logger, config.loop)
await migrateRalphKeys(kvService, projectId, logger)
const loopHandler = createLoopEventHandler(loopService, client, v2, logger, () => config)
const mismatchState: DimensionMismatchState = {
detected: false,
@@ -393,12 +394,12 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
cleaned = true
logger.log('Cleaning up plugin resources...')
// First, stop all active Ralph loops
ralphHandler.terminateAll()
logger.log('Ralph: all active loops terminated')
// First, stop all active memory loops
loopHandler.terminateAll()
logger.log('Memory loop: all active loops terminated')
// Clear all retry timeouts to prevent callbacks after cleanup
ralphHandler.clearAllRetryTimeouts()
loopHandler.clearAllRetryTimeouts()
// Then proceed with remaining cleanup
memoryInjection.destroy()
@@ -413,7 +414,7 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
const getCleanup = cleanup
interface RalphSetupOptions {
interface LoopSetupOptions {
prompt: string
sessionTitle: string
worktreeName?: string
@@ -422,31 +423,31 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
audit: boolean
agent?: string
model?: { providerID: string; modelID: string }
inPlace?: boolean
worktree?: boolean
onLoopStarted?: (worktreeName: string) => void
}
async function setupRalphLoop(options: RalphSetupOptions): Promise<string> {
const autoWorktreeName = options.worktreeName ?? `ralph-${slugify(options.sessionTitle.replace(/^Ralph:\s*/i, ''))}`
async function setupLoop(options: LoopSetupOptions): Promise<string> {
const autoWorktreeName = options.worktreeName ?? `loop-${slugify(options.sessionTitle.replace(/^Loop:\s*/i, ''))}`
const projectDir = directory
const maxIter = options.maxIterations ?? config.ralph?.defaultMaxIterations ?? 0
const maxIter = options.maxIterations ?? config.loop?.defaultMaxIterations ?? 0
interface LoopContext {
sessionId: string
directory: string
branch?: string
workspaceId?: string
inPlace: boolean
worktree: boolean
}
let loopContext: LoopContext
if (options.inPlace) {
if (!options.worktree) {
let currentBranch: string | undefined
try {
currentBranch = execSync('git rev-parse --abbrev-ref HEAD', { cwd: projectDir, encoding: 'utf-8' }).trim()
} catch (err) {
logger.log(`ralph: no git branch detected, running without branch info`)
logger.log(`loop: no git branch detected, running without branch info`)
}
const createResult = await v2.session.create({
@@ -455,7 +456,7 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
})
if (createResult.error || !createResult.data) {
logger.error(`ralph: failed to create session`, createResult.error)
logger.error(`loop: failed to create session`, createResult.error)
return 'Failed to create Ralph session.'
}
@@ -463,7 +464,7 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
sessionId: createResult.data.id,
directory: projectDir,
branch: currentBranch,
inPlace: true,
worktree: false,
}
} else {
const worktreeResult = await v2.worktree.create({
@@ -471,12 +472,12 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
})
if (worktreeResult.error || !worktreeResult.data) {
logger.error(`ralph: failed to create worktree`, worktreeResult.error)
logger.error(`loop: failed to create worktree`, worktreeResult.error)
return 'Failed to create worktree.'
}
const worktreeInfo = worktreeResult.data
logger.log(`ralph: worktree created at ${worktreeInfo.directory} (branch: ${worktreeInfo.branch})`)
logger.log(`loop: worktree created at ${worktreeInfo.directory} (branch: ${worktreeInfo.branch})`)
const createResult = await v2.session.create({
title: options.sessionTitle,
@@ -484,11 +485,11 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
})
if (createResult.error || !createResult.data) {
logger.error(`ralph: failed to create session`, createResult.error)
logger.error(`loop: failed to create session`, createResult.error)
try {
await v2.worktree.remove({ worktreeRemoveInput: { directory: worktreeInfo.directory } })
} catch (cleanupErr) {
logger.error(`ralph: failed to cleanup worktree`, cleanupErr)
logger.error(`loop: failed to cleanup worktree`, cleanupErr)
}
return 'Failed to create Ralph session.'
}
@@ -498,11 +499,11 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
directory: worktreeInfo.directory,
branch: worktreeInfo.branch,
workspaceId: `wrk-${autoWorktreeName}`,
inPlace: false,
worktree: true,
}
}
const state: RalphState = {
const state: LoopState = {
active: true,
sessionId: loopContext.sessionId,
worktreeName: autoWorktreeName,
@@ -518,12 +519,12 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
audit: options.audit,
errorCount: 0,
auditCount: 0,
inPlace: options.inPlace,
worktree: options.worktree,
}
ralphService.setState(autoWorktreeName, state)
ralphService.registerSession(loopContext.sessionId, autoWorktreeName)
logger.log(`ralph: state stored for worktree=${autoWorktreeName}`)
loopService.setState(autoWorktreeName, state)
loopService.registerSession(loopContext.sessionId, autoWorktreeName)
logger.log(`loop: state stored for worktree=${autoWorktreeName}`)
let promptText = options.prompt
if (options.completionPromise) {
@@ -549,16 +550,16 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
)
if (promptResult.error) {
logger.error(`ralph: failed to send prompt`, promptResult.error)
ralphService.deleteState(autoWorktreeName)
if (!options.inPlace && loopContext.workspaceId) {
logger.error(`loop: failed to send prompt`, promptResult.error)
loopService.deleteState(autoWorktreeName)
if (options.worktree && loopContext.workspaceId) {
try {
await v2.worktree.remove({ worktreeRemoveInput: { directory: loopContext.directory } })
} catch (cleanupErr) {
logger.error(`ralph: failed to cleanup worktree`, cleanupErr)
logger.error(`loop: failed to cleanup worktree`, cleanupErr)
}
}
return options.inPlace
return !options.worktree
? 'Ralph session created but failed to send prompt.'
: 'Ralph session created but failed to send prompt. Cleaned up.'
}
@@ -570,13 +571,13 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
const modelInfo = actualModel ? `${actualModel.providerID}/${actualModel.modelID}` : 'default'
const lines: string[] = [
options.inPlace ? 'Ralph loop activated! (in-place mode)' : 'Ralph loop activated!',
!options.worktree ? 'Memory loop activated! (in-place mode)' : 'Memory loop activated!',
'',
`Session: ${loopContext.sessionId}`,
`Title: ${options.sessionTitle}`,
]
if (options.inPlace) {
if (!options.worktree) {
lines.push(`Directory: ${loopContext.directory}`)
if (loopContext.branch) {
lines.push(`Branch: ${loopContext.branch} (in-place)`)
@@ -596,47 +597,47 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
'',
'The loop will automatically continue when the session goes idle.',
'Your job is done — just confirm to the user that the loop has been launched.',
'The user can run ralph-status or ralph-cancel later if needed.',
'The user can run memory-loop-status or memory-loop-cancel later if needed.',
)
return lines.join('\n')
}
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.',
const LOOP_BLOCKED_TOOLS: Record<string, string> = {
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.',
}
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>
The user selected "New session". You MUST now call memory-plan-execute in this response with:
- plan: The FULL self-contained implementation plan (the code agent starts with zero context)
- title: A short descriptive title for the session
- inPlace: false (or omit)
- worktree: true (or omit)
Do NOT output text without also making this tool call.
</system-reminder>`,
'Execute here': `<system-reminder>
The user selected "Execute here". You MUST now call memory-plan-execute in this response with:
- plan: "Execute the implementation plan from this conversation. Review all phases above and implement each one."
- title: A short descriptive title for the session
- inPlace: true
- worktree: false
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>`,
}
@@ -862,34 +863,34 @@ Do NOT output text without also making this tool call.
return `Implementation session created and plan sent.\n\nSession: ${newSessionId}\nTitle: ${sessionTitle}\nModel: ${modelInfo}\n\nSwitch to this session to begin. You can change the model from the session dropdown.`
},
}),
'memory-plan-ralph': tool({
description: 'Execute a plan using a Ralph iterative development loop. By default runs in an isolated git worktree. Set inPlace to true to run in the current directory instead.',
'memory-loop': tool({
description: 'Execute a plan using an iterative development loop. Default runs in current directory. Set worktree to true for isolated git worktree.',
args: {
plan: z.string().describe('The full implementation plan to send to the Code agent'),
title: z.string().describe('Short title for the session (shown in session list)'),
inPlace: z.boolean().optional().default(false).describe('Run in current directory instead of creating a worktree'),
worktree: z.boolean().optional().default(false).describe('Run in isolated git worktree instead of current directory'),
},
execute: async (args, context) => {
if (config.ralph?.enabled === false) {
if (config.loop?.enabled === false) {
return 'Ralph loops are disabled in plugin config. Use memory-plan-execute instead.'
}
logger.log(`memory-plan-ralph: creating worktree for plan="${args.title}"`)
logger.log(`memory-loop: creating worktree for plan="${args.title}"`)
const sessionTitle = args.title.length > 60 ? `${args.title.substring(0, 57)}...` : args.title
const ralphModel = parseModelString(config.ralph?.model) ?? parseModelString(config.executionModel)
const audit = config.ralph?.defaultAudit ?? true
const loopModel = parseModelString(config.loop?.model) ?? parseModelString(config.executionModel)
const audit = config.loop?.defaultAudit ?? true
return setupRalphLoop({
return setupLoop({
prompt: args.plan,
sessionTitle: `Ralph: ${sessionTitle}`,
sessionTitle: `Loop: ${sessionTitle}`,
completionPromise: DEFAULT_PLAN_COMPLETION_PROMISE,
maxIterations: config.ralph?.defaultMaxIterations ?? 0,
maxIterations: config.loop?.defaultMaxIterations ?? 0,
audit: audit,
agent: 'code',
model: ralphModel,
inPlace: args.inPlace,
onLoopStarted: (id) => ralphHandler.startWatchdog(id),
model: loopModel,
worktree: args.worktree,
onLoopStarted: (id) => loopHandler.startWatchdog(id),
})
},
}),
@@ -966,46 +967,46 @@ Do NOT output text without also making this tool call.
},
}),
'ralph-cancel': tool({
description: 'Cancel an active Ralph loop and optionally clean up the worktree.',
'memory-loop-cancel': tool({
description: 'Cancel an active memory loop and optionally clean up the worktree.',
args: {
name: z.string().optional().describe('Worktree name of the Ralph loop to cancel'),
name: z.string().optional().describe('Worktree name of the memory loop to cancel'),
},
execute: async (args) => {
let state: RalphState | null = null
let state: LoopState | null = null
if (args.name) {
const name = args.name
state = ralphService.findByWorktreeName(name)
state = loopService.findByWorktreeName(name)
if (!state) {
const candidates = ralphService.findCandidatesByPartialName(name)
const candidates = loopService.findCandidatesByPartialName(name)
if (candidates.length > 0) {
return `Multiple loops match "${name}":\n${candidates.map((s) => `- ${s.worktreeName}`).join('\n')}\n\nBe more specific.`
}
const recent = ralphService.listRecent()
const recent = loopService.listRecent()
const foundRecent = recent.find((s) => s.worktreeName === name || (s.worktreeBranch && s.worktreeBranch.toLowerCase().includes(name.toLowerCase())))
if (foundRecent) {
return `Ralph loop "${foundRecent.worktreeName}" has already completed.`
return `Memory loop "${foundRecent.worktreeName}" has already completed.`
}
return `No active Ralph loop found for worktree "${name}".`
return `No active memory loop found for worktree "${name}".`
}
if (!state.active) {
return `Ralph loop "${state.worktreeName}" has already completed.`
return `Memory loop "${state.worktreeName}" has already completed.`
}
} else {
const active = ralphService.listActive()
if (active.length === 0) return 'No active Ralph loops.'
const active = loopService.listActive()
if (active.length === 0) return 'No active memory loops.'
if (active.length === 1) {
state = active[0]
} else {
return `Multiple active Ralph loops. Specify a name:\n${active.map((s) => `- ${s.worktreeName} (iteration ${s.iteration})`).join('\n')}`
return `Multiple active memory loops. Specify a name:\n${active.map((s) => `- ${s.worktreeName} (iteration ${s.iteration})`).join('\n')}`
}
}
await ralphHandler.cancelBySessionId(state.sessionId)
logger.log(`ralph-cancel: cancelled loop for session=${state.sessionId} at iteration ${state.iteration}`)
await loopHandler.cancelBySessionId(state.sessionId)
logger.log(`memory-loop-cancel: cancelled loop for session=${state.sessionId} at iteration ${state.iteration}`)
if (config.ralph?.cleanupWorktree && !state.inPlace && state.worktreeDir) {
if (config.loop?.cleanupWorktree && state.worktree && state.worktreeDir) {
try {
const gitCommonDir = execSync('git rev-parse --git-common-dir', { cwd: state.worktreeDir, encoding: 'utf-8' }).trim()
const gitRoot = resolve(state.worktreeDir, gitCommonDir, '..')
@@ -1013,32 +1014,32 @@ Do NOT output text without also making this tool call.
if (removeResult.status !== 0) {
throw new Error(removeResult.stderr || 'git worktree remove failed')
}
logger.log(`ralph-cancel: removed worktree ${state.worktreeDir}`)
logger.log(`memory-loop-cancel: removed worktree ${state.worktreeDir}`)
} catch (err) {
logger.error(`ralph-cancel: failed to remove worktree`, err)
logger.error(`memory-loop-cancel: failed to remove worktree`, err)
}
}
const modeInfo = state.inPlace ? ' (in-place)' : ''
const modeInfo = !state.worktree ? ' (in-place)' : ''
const branchInfo = state.worktreeBranch ? `\nBranch: ${state.worktreeBranch}` : ''
return `Cancelled Ralph loop "${state.worktreeName}"${modeInfo} (was at iteration ${state.iteration}).\nDirectory: ${state.worktreeDir}${branchInfo}`
return `Cancelled memory loop "${state.worktreeName}"${modeInfo} (was at iteration ${state.iteration}).\nDirectory: ${state.worktreeDir}${branchInfo}`
},
}),
'ralph-status': tool({
description: 'Check the status of Ralph loops. With no arguments, lists all active loops for the current project. Pass a worktree name for detailed status of a specific loop. Use restart to resume an inactive loop.',
'memory-loop-status': tool({
description: 'Check the status of memory loops. With no arguments, lists all active loops for the current project. Pass a worktree name for detailed status of a specific loop. Use restart to resume an inactive loop.',
args: {
name: z.string().optional().describe('Worktree name to check for detailed status'),
restart: z.boolean().optional().describe('Restart an inactive loop by name'),
},
execute: async (args) => {
const active = ralphService.listActive()
const active = loopService.listActive()
if (args.restart) {
if (!args.name) {
return 'Specify a loop name to restart. Use ralph-status to see available loops.'
return 'Specify a loop name to restart. Use memory-loop-status to see available loops.'
}
const recent = ralphService.listRecent()
const recent = loopService.listRecent()
const allStates = [...active, ...recent]
const { match: stoppedState, candidates } = findPartialMatch(args.name, allStates, (s) => [s.worktreeName, s.worktreeBranch])
if (!stoppedState && candidates.length > 0) {
@@ -1046,7 +1047,7 @@ Do NOT output text without also making this tool call.
}
if (!stoppedState) {
const available = [...active, ...recent].map((s) => `- ${s.worktreeName}`).join('\n')
return `No Ralph loop found for "${args.name}".\n\nAvailable loops:\n${available}`
return `No memory loop found for "${args.name}".\n\nAvailable loops:\n${available}`
}
if (stoppedState.active) {
@@ -1057,7 +1058,7 @@ Do NOT output text without also making this tool call.
return `Loop "${stoppedState.worktreeName}" completed successfully and cannot be restarted.`
}
if (!stoppedState.inPlace && stoppedState.worktreeDir) {
if (!stoppedState.worktree && stoppedState.worktreeDir) {
if (!existsSync(stoppedState.worktreeDir)) {
return `Cannot restart "${stoppedState.worktreeName}": worktree directory no longer exists at ${stoppedState.worktreeDir}. The worktree may have been cleaned up.`
}
@@ -1069,15 +1070,15 @@ Do NOT output text without also making this tool call.
})
if (createResult.error || !createResult.data) {
logger.error(`ralph-restart: failed to create session`, createResult.error)
logger.error(`memory-loop-restart: failed to create session`, createResult.error)
return `Failed to create new session for restart.`
}
const newSessionId = createResult.data.id
ralphService.deleteState(stoppedState.worktreeName!)
loopService.deleteState(stoppedState.worktreeName!)
const newState: RalphState = {
const newState: LoopState = {
active: true,
sessionId: newSessionId,
worktreeName: stoppedState.worktreeName!,
@@ -1093,18 +1094,18 @@ Do NOT output text without also making this tool call.
audit: stoppedState.audit,
errorCount: 0,
auditCount: 0,
inPlace: stoppedState.inPlace,
worktree: stoppedState.worktree,
}
ralphService.setState(stoppedState.worktreeName!, newState)
ralphService.registerSession(newSessionId, stoppedState.worktreeName!)
loopService.setState(stoppedState.worktreeName!, newState)
loopService.registerSession(newSessionId, stoppedState.worktreeName!)
let promptText = stoppedState.prompt ?? ''
if (stoppedState.completionPromise) {
promptText += `\n\n---\n\n**IMPORTANT - Completion Signal:** When you have completed ALL phases of this plan successfully, you MUST output the following tag exactly: <promise>${stoppedState.completionPromise}</promise>\n\nDo NOT output this tag until every phase is truly complete. The loop will continue until this signal is detected.`
}
const ralphModel = parseModelString(config.ralph?.model) ?? parseModelString(config.executionModel)
const loopModel = parseModelString(config.loop?.model) ?? parseModelString(config.executionModel)
const { result: promptResult } = await retryWithModelFallback(
() => v2.session.promptAsync({
@@ -1112,7 +1113,7 @@ Do NOT output text without also making this tool call.
directory: stoppedState.worktreeDir!,
parts: [{ type: 'text' as const, text: promptText }],
agent: 'code',
model: ralphModel!,
model: loopModel!,
}),
() => v2.session.promptAsync({
sessionID: newSessionId,
@@ -1120,22 +1121,22 @@ Do NOT output text without also making this tool call.
parts: [{ type: 'text' as const, text: promptText }],
agent: 'code',
}),
ralphModel,
loopModel,
logger,
)
if (promptResult.error) {
logger.error(`ralph-restart: failed to send prompt`, promptResult.error)
ralphService.deleteState(stoppedState.worktreeName!)
logger.error(`memory-loop-restart: failed to send prompt`, promptResult.error)
loopService.deleteState(stoppedState.worktreeName!)
return `Restart failed: could not send prompt to new session.`
}
ralphHandler.startWatchdog(stoppedState.worktreeName!)
loopHandler.startWatchdog(stoppedState.worktreeName!)
const modeInfo = stoppedState.inPlace ? ' (in-place)' : ''
const modeInfo = stoppedState.worktree ? ' (in-place)' : ''
const branchInfo = stoppedState.worktreeBranch ? `\nBranch: ${stoppedState.worktreeBranch}` : ''
return [
`Restarted Ralph loop "${stoppedState.worktreeName}"${modeInfo}`,
`Restarted memory loop "${stoppedState.worktreeName}"${modeInfo}`,
'',
`New session: ${newSessionId}`,
`Continuing from iteration: ${stoppedState.iteration}`,
@@ -1146,12 +1147,12 @@ Do NOT output text without also making this tool call.
}
if (!args.name) {
const recent = ralphService.listRecent()
const recent = loopService.listRecent()
if (active.length === 0) {
if (recent.length === 0) return 'No Ralph loops found.'
if (recent.length === 0) return 'No memory loops found.'
const lines: string[] = ['Recently Completed Ralph Loops', '']
const lines: string[] = ['Recently Completed Memory Loops', '']
recent.forEach((s, i) => {
const duration = s.completedAt && s.startedAt
? Math.round((new Date(s.completedAt).getTime() - new Date(s.startedAt).getTime()) / 1000)
@@ -1163,7 +1164,7 @@ Do NOT output text without also making this tool call.
lines.push(` Reason: ${s.terminationReason ?? 'unknown'} | Iterations: ${s.iteration} | Duration: ${durationStr} | Completed: ${s.completedAt ?? 'unknown'}`)
lines.push('')
})
lines.push('Use ralph-status <name> for detailed info.')
lines.push('Use memory-loop-status <name> for detailed info.')
return lines.join('\n')
}
@@ -1174,7 +1175,7 @@ Do NOT output text without also making this tool call.
} catch {
}
const lines: string[] = [`Active Ralph Loops (${active.length})`, '']
const lines: string[] = [`Active Memory Loops (${active.length})`, '']
active.forEach((s, i) => {
const elapsed = s.startedAt ? Math.round((Date.now() - new Date(s.startedAt).getTime()) / 1000) : 0
const minutes = Math.floor(elapsed / 60)
@@ -1182,8 +1183,8 @@ Do NOT output text without also making this tool call.
const duration = minutes > 0 ? `${minutes}m ${seconds}s` : `${seconds}s`
const iterInfo = s.maxIterations && s.maxIterations > 0 ? `${s.iteration} / ${s.maxIterations}` : `${s.iteration} (unlimited)`
const sessionStatus = statuses[s.sessionId]?.type ?? 'unknown'
const modeIndicator = s.inPlace ? ' (in-place)' : ''
const stallInfo = ralphHandler.getStallInfo(s.worktreeName)
const modeIndicator = !s.worktree ? ' (in-place)' : ''
const stallInfo = loopHandler.getStallInfo(s.worktreeName)
const stallCount = stallInfo?.consecutiveStalls ?? 0
const stallSuffix = stallCount > 0 ? ` | Stalls: ${stallCount}` : ''
lines.push(`${i + 1}. ${s.worktreeName}${modeIndicator}`)
@@ -1207,18 +1208,18 @@ Do NOT output text without also making this tool call.
lines.push('')
})
if (recent.length > 10) {
lines.push(` ... and ${recent.length - 10} more. Use ralph-status <name> for details.`)
lines.push(` ... and ${recent.length - 10} more. Use memory-loop-status <name> for details.`)
lines.push('')
}
}
lines.push('Use ralph-status <name> for detailed info, or ralph-cancel <name> to stop a loop.')
lines.push('Use memory-loop-status <name> for detailed info, or memory-loop-cancel <name> to stop a loop.')
return lines.join('\n')
}
const state = ralphService.findByWorktreeName(args.name)
const state = loopService.findByWorktreeName(args.name)
if (!state) {
const candidates = ralphService.findCandidatesByPartialName(args.name)
const candidates = loopService.findCandidatesByPartialName(args.name)
if (candidates.length > 0) {
return `Multiple loops match "${args.name}":\n${candidates.map((s) => `- ${s.worktreeName}`).join('\n')}\n\nBe more specific.`
}
@@ -1240,7 +1241,7 @@ Do NOT output text without also making this tool call.
`Name: ${state.worktreeName}`,
`Session: ${state.sessionId}`,
]
if (state.inPlace) {
if (!state.worktree) {
statusLines.push(`Mode: in-place | Directory: ${state.worktreeDir}`)
} else {
statusLines.push(`Workspace: ${state.workspaceId}`)
@@ -1263,7 +1264,7 @@ Do NOT output text without also making this tool call.
statusLines.push(...formatAuditResult(state.lastAuditResult))
}
const sessionOutput = await fetchSessionOutput(v2, state.sessionId, state.worktreeDir!, logger)
const sessionOutput = state.worktreeDir ? await fetchSessionOutput(v2, state.sessionId, state.worktreeDir, logger) : null
if (sessionOutput) {
statusLines.push('')
statusLines.push('Session Output:')
@@ -1295,7 +1296,7 @@ Do NOT output text without also making this tool call.
const seconds = elapsed % 60
const duration = minutes > 0 ? `${minutes}m ${seconds}s` : `${seconds}s`
const stallInfo = ralphHandler.getStallInfo(state.worktreeName)
const stallInfo = loopHandler.getStallInfo(state.worktreeName)
const secondsSinceActivity = stallInfo
? Math.round((Date.now() - stallInfo.lastActivityTime) / 1000)
: null
@@ -1307,7 +1308,7 @@ Do NOT output text without also making this tool call.
`Name: ${state.worktreeName}`,
`Session: ${state.sessionId}`,
]
if (state.inPlace) {
if (!state.worktree) {
statusLines.push(`Mode: in-place | Directory: ${state.worktreeDir}`)
} else {
statusLines.push(`Workspace: ${state.workspaceId}`)
@@ -1328,7 +1329,7 @@ Do NOT output text without also making this tool call.
`Started: ${state.startedAt}`,
...(state.errorCount && state.errorCount > 0 ? [`Error count: ${state.errorCount} (retries before termination: ${MAX_RETRIES})`] : []),
`Audit count: ${state.auditCount ?? 0}`,
`Model: ${config.ralph?.model || config.executionModel || 'default'}`,
`Model: ${config.loop?.model || config.executionModel || 'default'}`,
`Auditor model: ${config.auditorModel || 'default'}`,
...(stallCount > 0 ? [`Stalls: ${stallCount}`] : []),
...(secondsSinceActivity !== null ? [`Last activity: ${secondsSinceActivity}s ago`] : []),
@@ -1340,7 +1341,7 @@ Do NOT output text without also making this tool call.
statusLines.push(...formatAuditResult(state.lastAuditResult))
}
const sessionOutput = await fetchSessionOutput(v2, state.sessionId, state.worktreeDir!, logger)
const sessionOutput = state.worktreeDir ? await fetchSessionOutput(v2, state.sessionId, state.worktreeDir, logger) : null
if (sessionOutput) {
statusLines.push('')
statusLines.push('Session Output:')
@@ -1365,22 +1366,22 @@ Do NOT output text without also making this tool call.
cleanup()
return
}
await ralphHandler.onEvent(eventInput)
await loopHandler.onEvent(eventInput)
await sessionHooks.onEvent(eventInput)
},
'tool.execute.before': async (
input: { tool: string; sessionID: string; callID: string },
output: { args: unknown }
) => {
const worktreeName = ralphService.resolveWorktreeName(input.sessionID)
const state = worktreeName ? ralphService.getActiveState(worktreeName) : null
const worktreeName = loopService.resolveWorktreeName(input.sessionID)
const state = worktreeName ? loopService.getActiveState(worktreeName) : null
if (!state?.active) return
if (!(input.tool in RALPH_BLOCKED_TOOLS)) return
if (!(input.tool in LOOP_BLOCKED_TOOLS)) return
logger.log(`Ralph: blocking ${input.tool} tool before execution in ${state.phase} phase for session ${input.sessionID}`)
throw new Error(RALPH_BLOCKED_TOOLS[input.tool]!)
throw new Error(LOOP_BLOCKED_TOOLS[input.tool]!)
},
'tool.execute.after': async (
input: { tool: string; sessionID: string; callID: string; args: unknown },
@@ -1396,7 +1397,7 @@ Do NOT output text without also making this tool call.
const metadata = output.metadata as { answers?: string[][] } | undefined
const answer = metadata?.answers?.[0]?.[0]?.trim() ?? output.output.trim()
const matchedLabel = PLAN_APPROVAL_LABELS.find((l) => answer === l || answer.startsWith(l))
const directive = matchedLabel ? PLAN_APPROVAL_DIRECTIVES[matchedLabel] : '<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 directive = matchedLabel ? PLAN_APPROVAL_DIRECTIVES[matchedLabel] : '<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>'
output.output = `${output.output}\n\n${directive}`
logger.log(`Plan approval: detected "${matchedLabel ?? 'cancel/custom'}" answer, injected directive`)
}
@@ -1404,21 +1405,21 @@ Do NOT output text without also making this tool call.
return
}
const worktreeName = ralphService.resolveWorktreeName(input.sessionID)
const state = worktreeName ? ralphService.getActiveState(worktreeName) : null
const worktreeName = loopService.resolveWorktreeName(input.sessionID)
const state = worktreeName ? loopService.getActiveState(worktreeName) : null
if (!state?.active) return
if (!(input.tool in RALPH_BLOCKED_TOOLS)) return
if (!(input.tool in LOOP_BLOCKED_TOOLS)) return
logger.log(`Ralph: blocked ${input.tool} tool in ${state.phase} phase for session ${input.sessionID}`)
output.title = 'Tool blocked'
output.output = RALPH_BLOCKED_TOOLS[input.tool]!
output.output = LOOP_BLOCKED_TOOLS[input.tool]!
},
'permission.ask': async (input, output) => {
const req = input as unknown as { sessionID: string; patterns: string[] }
const worktreeName = ralphService.resolveWorktreeName(req.sessionID)
const state = worktreeName ? ralphService.getActiveState(worktreeName) : null
const worktreeName = loopService.resolveWorktreeName(req.sessionID)
const state = worktreeName ? loopService.getActiveState(worktreeName) : null
if (!state?.active) return
if (req.patterns.some((p) => p.startsWith('git push'))) {
@@ -1492,7 +1493,7 @@ Do NOT output text without also making this tool call.
text: `<system-reminder>
Plan mode is active. You MUST NOT make any file edits, run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supersedes any other instructions you have received.
You may ONLY: observe, analyze, plan, and use memory tools (memory-read, memory-write, memory-edit, memory-delete, memory-kv-set, memory-kv-get, memory-kv-list), the question tool, memory-plan-execute, and memory-plan-ralph.
You may ONLY: observe, analyze, plan, and use memory tools (memory-read, memory-write, memory-edit, memory-delete, memory-kv-set, memory-kv-get, memory-kv-list), the question tool, memory-plan-execute, and memory-loop.
You MUST always present your plan to the user for explicit approval before proceeding. Never execute a plan without approval. Use the question tool to collect approval — never ask for approval via plain text output.
</system-reminder>`,
@@ -1,15 +1,43 @@
import type { KvService } from './kv'
import type { Logger, RalphConfig } from '../types'
import type { Logger, LoopConfig } from '../types'
import type { OpencodeClient } from '@opencode-ai/sdk/v2'
import { findPartialMatch } from '../utils/partial-match'
export async function migrateRalphKeys(kvService: KvService, projectId: string, logger: Logger): Promise<void> {
const oldEntries = await kvService.listByPrefix(projectId, 'ralph:')
if (oldEntries.length === 0) return
logger.log(`Migrating ${oldEntries.length} ralph: KV entries to loop: prefix`)
for (const entry of oldEntries) {
const newKey = entry.key.replace(/^ralph:/, 'loop:')
const data = typeof entry.data === 'string' ? JSON.parse(entry.data) : entry.data
if ('inPlace' in data) {
data.worktree = !data.inPlace
delete data.inPlace
}
await kvService.set(projectId, newKey, data)
await kvService.delete(projectId, entry.key)
}
const oldSessions = await kvService.listByPrefix(projectId, 'ralph-session:')
for (const entry of oldSessions) {
const newKey = entry.key.replace(/^ralph-session:/, 'loop-session:')
await kvService.set(projectId, newKey, entry.data)
await kvService.delete(projectId, entry.key)
}
if (oldSessions.length > 0) {
logger.log(`Migrated ${oldSessions.length} ralph-session: KV entries to loop-session: prefix`)
}
}
export const MAX_RETRIES = 3
export const STALL_TIMEOUT_MS = 60_000
export const MAX_CONSECUTIVE_STALLS = 5
export const DEFAULT_MIN_AUDITS = 1
export const RECENT_MESSAGES_COUNT = 5
export interface RalphState {
export interface LoopState {
active: boolean
sessionId: string
worktreeName: string
@@ -28,51 +56,51 @@ export interface RalphState {
auditCount: number
terminationReason?: string
completedAt?: string
inPlace?: boolean
worktree?: boolean
modelFailed?: boolean
}
export interface RalphService {
getActiveState(name: string): RalphState | null
getAnyState(name: string): RalphState | null
setState(name: string, state: RalphState): void
export interface LoopService {
getActiveState(name: string): LoopState | null
getAnyState(name: string): LoopState | null
setState(name: string, state: LoopState): void
deleteState(name: string): void
registerSession(sessionId: string, worktreeName: string): void
resolveWorktreeName(sessionId: string): string | null
unregisterSession(sessionId: string): void
checkCompletionPromise(text: string, promise: string): boolean
buildContinuationPrompt(state: RalphState, auditFindings?: string): string
buildAuditPrompt(state: RalphState): string
listActive(): RalphState[]
listRecent(): RalphState[]
findByWorktreeName(name: string): RalphState | null
findCandidatesByPartialName(name: string): RalphState[]
buildContinuationPrompt(state: LoopState, auditFindings?: string): string
buildAuditPrompt(state: LoopState): string
listActive(): LoopState[]
listRecent(): LoopState[]
findByWorktreeName(name: string): LoopState | null
findCandidatesByPartialName(name: string): LoopState[]
getStallTimeoutMs(): number
getMinAudits(): number
terminateAll(): void
}
export function createRalphService(
export function createLoopService(
kvService: KvService,
projectId: string,
logger: Logger,
ralphConfig?: RalphConfig,
): RalphService {
const stateKey = (name: string) => `ralph:${name}`
loopConfig?: LoopConfig,
): LoopService {
const stateKey = (name: string) => `loop:${name}`
function getAnyState(name: string): RalphState | null {
return kvService.get<RalphState>(projectId, stateKey(name))
function getAnyState(name: string): LoopState | null {
return kvService.get<LoopState>(projectId, stateKey(name))
}
function getActiveState(name: string): RalphState | null {
const state = kvService.get<RalphState>(projectId, stateKey(name))
function getActiveState(name: string): LoopState | null {
const state = kvService.get<LoopState>(projectId, stateKey(name))
if (!state || !state.active) {
return null
}
return state
}
function setState(name: string, state: RalphState): void {
function setState(name: string, state: LoopState): void {
kvService.set(projectId, stateKey(name), state)
}
@@ -81,15 +109,15 @@ export function createRalphService(
}
function registerSession(sessionId: string, worktreeName: string): void {
kvService.set(projectId, `ralph-session:${sessionId}`, worktreeName)
kvService.set(projectId, `loop-session:${sessionId}`, worktreeName)
}
function resolveWorktreeName(sessionId: string): string | null {
return kvService.get<string>(projectId, `ralph-session:${sessionId}`)
return kvService.get<string>(projectId, `loop-session:${sessionId}`)
}
function unregisterSession(sessionId: string): void {
kvService.delete(projectId, `ralph-session:${sessionId}`)
kvService.delete(projectId, `loop-session:${sessionId}`)
}
function checkCompletionPromise(text: string, promise: string): boolean {
@@ -101,8 +129,8 @@ export function createRalphService(
return extracted === promise
}
function buildContinuationPrompt(state: RalphState, auditFindings?: string): string {
let systemLine = `Ralph iteration ${state.iteration ?? 0}`
function buildContinuationPrompt(state: LoopState, auditFindings?: string): string {
let systemLine = `Loop iteration ${state.iteration ?? 0}`
if (state.completionPromise) {
systemLine += ` | To stop: output <promise>${state.completionPromise}</promise> (ONLY when all requirements are met)`
@@ -124,7 +152,7 @@ export function createRalphService(
return prompt
}
function buildAuditPrompt(state: RalphState): string {
function buildAuditPrompt(state: LoopState): string {
const taskSummary = (state.prompt?.length ?? 0) > 200
? `${state.prompt?.substring(0, 197)}...`
: (state.prompt ?? '')
@@ -145,21 +173,21 @@ export function createRalphService(
].join('\n')
}
function listActive(): RalphState[] {
const entries = kvService.listByPrefix(projectId, 'ralph:')
function listActive(): LoopState[] {
const entries = kvService.listByPrefix(projectId, 'loop:')
return entries
.map((entry) => entry.data as RalphState)
.filter((state): state is RalphState => state !== null && state.active)
.map((entry) => entry.data as LoopState)
.filter((state): state is LoopState => state !== null && state.active)
}
function listRecent(): RalphState[] {
const entries = kvService.listByPrefix(projectId, 'ralph:')
function listRecent(): LoopState[] {
const entries = kvService.listByPrefix(projectId, 'loop:')
return entries
.map((entry) => entry.data as RalphState)
.filter((state): state is RalphState => state !== null && !state.active)
.map((entry) => entry.data as LoopState)
.filter((state): state is LoopState => state !== null && !state.active)
}
function findByWorktreeName(name: string): RalphState | null {
function findByWorktreeName(name: string): LoopState | null {
const active = listActive()
const recent = listRecent()
const allStates = [...active, ...recent]
@@ -168,7 +196,7 @@ export function createRalphService(
return match
}
function findCandidatesByPartialName(name: string): RalphState[] {
function findCandidatesByPartialName(name: string): LoopState[] {
const active = listActive()
const recent = listRecent()
const allStates = [...active, ...recent]
@@ -178,17 +206,17 @@ export function createRalphService(
}
function getStallTimeoutMs(): number {
return ralphConfig?.stallTimeoutMs ?? STALL_TIMEOUT_MS
return loopConfig?.stallTimeoutMs ?? STALL_TIMEOUT_MS
}
function getMinAudits(): number {
return ralphConfig?.minAudits ?? DEFAULT_MIN_AUDITS
return loopConfig?.minAudits ?? DEFAULT_MIN_AUDITS
}
function terminateAll(): void {
const active = listActive()
for (const state of active) {
const updated: RalphState = {
const updated: LoopState = {
...state,
active: false,
completedAt: new Date().toISOString(),
@@ -196,7 +224,7 @@ export function createRalphService(
}
setState(state.worktreeName, updated)
}
logger.log(`Ralph: terminated ${active.length} active loop(s)`)
logger.log(`Loop: terminated ${active.length} active loop(s)`)
}
return {
@@ -220,7 +248,7 @@ export function createRalphService(
}
}
export interface RalphSessionOutput {
export interface LoopSessionOutput {
messages: Array<{ text: string; cost: number; tokens: { input: number; output: number; reasoning: number; cacheRead: number; cacheWrite: number } }>
totalCost: number
totalTokens: { input: number; output: number; reasoning: number; cacheRead: number; cacheWrite: number }
@@ -232,7 +260,12 @@ export async function fetchSessionOutput(
sessionId: string,
directory: string,
logger?: Logger,
): Promise<RalphSessionOutput | null> {
): Promise<LoopSessionOutput | null> {
if (!directory || !sessionId) {
logger?.debug('fetchSessionOutput: invalid directory or sessionId')
return null
}
try {
const messagesResult = await v2Client.session.messages({
sessionID: sessionId,
@@ -310,7 +343,7 @@ export async function fetchSessionOutput(
}
} catch (err) {
if (logger) {
logger.error(`Ralph: could not fetch session output for ${sessionId}`, err)
logger.error(`Loop: could not fetch session output for ${sessionId}`, err)
}
return null
}
+5 -1
View File
@@ -138,7 +138,11 @@ function normalizeConfig(config: PluginConfig): PluginConfig {
messagesTransform: config.messagesTransform,
executionModel: config.executionModel,
auditorModel: config.auditorModel,
ralph: config.ralph,
loop: config.loop ?? config.ralph,
}
if (config.ralph && !config.loop) {
console.warn('[memory] Config key "ralph" is deprecated, use "loop" instead')
}
if (normalized.embedding) {
+3 -2
View File
@@ -59,7 +59,7 @@ export interface Logger {
debug: (message: string, ...args: unknown[]) => void
}
export interface RalphConfig {
export interface LoopConfig {
enabled?: boolean
defaultMaxIterations?: number
cleanupWorktree?: boolean
@@ -79,7 +79,8 @@ export interface PluginConfig {
messagesTransform?: MessagesTransformConfig
executionModel?: string
auditorModel?: string
ralph?: RalphConfig
loop?: LoopConfig
ralph?: LoopConfig
defaultKvTtlMs?: number
}
@@ -1,11 +1,11 @@
import { truncate } from '../cli/utils'
import type { RalphSessionOutput } from '../services/ralph'
import type { LoopSessionOutput } from '../services/loop'
export function formatTokens(n: number): string {
return n >= 1000 ? `${(n / 1000).toFixed(1)}k` : `${n}`
}
export function formatSessionOutput(sessionOutput: RalphSessionOutput): string[] {
export function formatSessionOutput(sessionOutput: LoopSessionOutput): string[] {
const lines: string[] = []
const costStr = `$${sessionOutput.totalCost.toFixed(4)}`
const t = sessionOutput.totalTokens
+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')
})
+7 -6
View File
@@ -86,7 +86,7 @@ export const MessagesTransformConfigSchema = z.object({
})
export type MessagesTransformConfig = z.infer<typeof MessagesTransformConfigSchema>
export const RalphConfigSchema = z.object({
export const LoopConfigSchema = z.object({
enabled: z.boolean().optional(),
defaultMaxIterations: z.number().optional(),
cleanupWorktree: z.boolean().optional(),
@@ -95,7 +95,7 @@ export const RalphConfigSchema = z.object({
minAudits: z.number().optional(),
stallTimeoutMs: z.number().optional(),
})
export type RalphConfig = z.infer<typeof RalphConfigSchema>
export type LoopConfig = z.infer<typeof LoopConfigSchema>
export const PluginConfigSchema = z.object({
dataDir: z.string().optional(),
@@ -107,7 +107,8 @@ export const PluginConfigSchema = z.object({
messagesTransform: MessagesTransformConfigSchema.optional(),
executionModel: z.string().optional(),
auditorModel: z.string().optional(),
ralph: RalphConfigSchema.optional(),
loop: LoopConfigSchema.optional(),
ralph: LoopConfigSchema.optional(),
})
export type PluginConfig = z.infer<typeof PluginConfigSchema>
@@ -140,7 +141,7 @@ export const UpdateKvEntryRequestSchema = z.object({
})
export type UpdateKvEntryRequest = z.infer<typeof UpdateKvEntryRequestSchema>
export const RalphStateSchema = z.object({
export const LoopStateSchema = z.object({
active: z.boolean(),
sessionId: z.string(),
worktreeName: z.string(),
@@ -159,7 +160,7 @@ export const RalphStateSchema = z.object({
auditCount: z.number(),
terminationReason: z.string().optional(),
completedAt: z.string().optional(),
inPlace: z.boolean().optional(),
worktree: z.boolean().optional(),
modelFailed: z.boolean().optional(),
})
export type RalphState = z.infer<typeof RalphStateSchema>
export type LoopState = z.infer<typeof LoopStateSchema>
+2 -1
View File
@@ -98,7 +98,8 @@ export type {
KvListQuery,
CreateKvEntryRequest,
UpdateKvEntryRequest,
RalphState,
LoopState,
LoopConfig,
} from '../schemas/memory'
export type {