mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
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:
1 parent
00489d9901
commit
2c4a9c9257
31 files changed
+789
-745
No files matched your search
@@ -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.
|
||||
`,
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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',
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -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
@@ -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
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -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
|
||||
Reference in new issue
Block a user