Refactor Ralph session rotation with watchdog and stall detection (#170)

* Improve scroll-to-bottom UI and session status handling

* Enhance Ralph service with session rotation and watchdog

* Add tests for Ralph session rotation and cleanup

* Add Kasm Docker build workflow
This commit is contained in:
Chris Scott authored and GitHub committed 2026-03-24 17:36:35 -04:00
1 parent 4ad6c5fd25
commit 27352ea5cf
11 files changed
+502 -25

No files matched your search

+1 -1
View File
@@ -99,7 +99,7 @@ All execution modes require a **title** — a short descriptive label for the se
| Option | Tool | inPlace | Plan Content |
|---|---|---|---|
| New session | memory-plan-execute | false | Full self-contained plan |
| Execute here | memory-plan-execute | true | "See plan above" |
| 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 |
+10
View File
@@ -67,6 +67,16 @@ ${getInjectedMemory('code')}
Never generate or guess URLs unless they are programming-related.
## Plan Execution
When you receive a message indicating that an architect agent has created a plan for you to execute (e.g., referencing "the plan above" or "implementation plan"), you MUST:
1. Review the plan from the conversation history
2. Create a todo list from the plan phases
3. Execute each phase by actually editing files, running commands, and making changes
4. Do NOT just describe or summarize what you would do — implement it
You are the execution agent. Your job is to write code, not describe code.
## Project KV Store
You have access to a project-scoped key-value store with 24-hour TTL for ephemeral state:
+68 -17
View File
@@ -254,6 +254,37 @@ export function createRalphEventHandler(
}
}
async function rotateSession(oldSessionId: string, state: RalphState): Promise<string> {
const createResult = await v2Client.session.create({
title: state.worktreeName,
directory: state.worktreeDir,
})
if (createResult.error || !createResult.data) {
throw new Error(`Failed to create new session: ${createResult.error}`)
}
const newSessionId = createResult.data.id
const oldRetryTimeout = retryTimeouts.get(oldSessionId)
if (oldRetryTimeout) {
clearTimeout(oldRetryTimeout)
retryTimeouts.delete(oldSessionId)
}
ralphService.deleteState(oldSessionId)
stopWatchdog(oldSessionId)
startWatchdog(newSessionId)
v2Client.session.delete({ sessionID: oldSessionId, directory: state.worktreeDir }).catch((err) => {
logger.error(`Ralph: failed to delete old session ${oldSessionId}`, err)
})
logger.log(`Ralph: rotated session ${oldSessionId} → ${newSessionId}`)
return newSessionId
}
async function handleCodingPhase(sessionId: string, state: RalphState): Promise<void> {
let currentState = ralphService.getActiveState(sessionId)
if (!currentState?.active) {
@@ -315,22 +346,34 @@ export function createRalphEventHandler(
return
}
let activeSessionId = sessionId
try {
activeSessionId = await rotateSession(sessionId, currentState)
} catch (err) {
logger.error(`Ralph: session rotation failed, continuing with existing session`, err)
}
const nextIteration = currentState.iteration + 1
ralphService.setState(sessionId, { ...currentState, iteration: nextIteration, errorCount: 0 })
ralphService.setState(activeSessionId, {
...currentState,
sessionId: activeSessionId,
iteration: nextIteration,
errorCount: 0,
})
const continuationPrompt = ralphService.buildContinuationPrompt({ ...currentState, iteration: nextIteration })
logger.log(`Ralph iteration ${nextIteration} for session ${sessionId}`)
logger.log(`Ralph iteration ${nextIteration} for session ${activeSessionId}`)
const currentConfig = getConfig()
const ralphModel = parseModelString(currentConfig.ralph?.model) ?? parseModelString(currentConfig.executionModel)
const sendContinuationPromptWithModel = async () => {
const freshState = ralphService.getActiveState(sessionId)
const freshState = ralphService.getActiveState(activeSessionId)
if (!freshState?.active) {
throw new Error('loop_cancelled')
}
const result = await v2Client.session.promptAsync({
sessionID: sessionId,
sessionID: activeSessionId,
directory: freshState.worktreeDir,
parts: [{ type: 'text' as const, text: continuationPrompt }],
model: ralphModel!,
@@ -339,12 +382,12 @@ export function createRalphEventHandler(
}
const sendContinuationPromptWithoutModel = async () => {
const freshState = ralphService.getActiveState(sessionId)
const freshState = ralphService.getActiveState(activeSessionId)
if (!freshState?.active) {
throw new Error('loop_cancelled')
}
const result = await v2Client.session.promptAsync({
sessionID: sessionId,
sessionID: activeSessionId,
directory: freshState.worktreeDir,
parts: [{ type: 'text' as const, text: continuationPrompt }],
})
@@ -365,7 +408,7 @@ export function createRalphEventHandler(
throw result.error
}
}
await handlePromptError(sessionId, currentState, 'failed to send continuation prompt', promptResult.error, retryFn)
await handlePromptError(activeSessionId, currentState, 'failed to send continuation prompt', promptResult.error, retryFn)
return
}
@@ -375,7 +418,7 @@ export function createRalphEventHandler(
logger.log(`coding phase using default model (fallback)`)
}
consecutiveStalls.set(sessionId, 0)
consecutiveStalls.set(activeSessionId, 0)
}
async function handleAuditingPhase(sessionId: string, state: RalphState): Promise<void> {
@@ -412,8 +455,16 @@ export function createRalphEventHandler(
return
}
ralphService.setState(sessionId, {
let activeSessionId = sessionId
try {
activeSessionId = await rotateSession(sessionId, currentState)
} catch (err) {
logger.error(`Ralph: session rotation failed, continuing with existing session`, err)
}
ralphService.setState(activeSessionId, {
...currentState,
sessionId: activeSessionId,
iteration: nextIteration,
phase: 'coding',
lastAuditResult: auditFindings,
@@ -425,18 +476,18 @@ export function createRalphEventHandler(
{ ...currentState, iteration: nextIteration },
auditFindings,
)
logger.log(`Ralph iteration ${nextIteration} for session ${sessionId}`)
logger.log(`Ralph iteration ${nextIteration} for session ${activeSessionId}`)
const currentConfig = getConfig()
const ralphModel = parseModelString(currentConfig.ralph?.model) ?? parseModelString(currentConfig.executionModel)
const sendContinuationPromptWithModel = async () => {
const freshState = ralphService.getActiveState(sessionId)
const freshState = ralphService.getActiveState(activeSessionId)
if (!freshState?.active) {
throw new Error('loop_cancelled')
}
const result = await v2Client.session.promptAsync({
sessionID: sessionId,
sessionID: activeSessionId,
directory: freshState.worktreeDir,
parts: [{ type: 'text' as const, text: continuationPrompt }],
model: ralphModel!,
@@ -445,12 +496,12 @@ export function createRalphEventHandler(
}
const sendContinuationPromptWithoutModel = async () => {
const freshState = ralphService.getActiveState(sessionId)
const freshState = ralphService.getActiveState(activeSessionId)
if (!freshState?.active) {
throw new Error('loop_cancelled')
}
const result = await v2Client.session.promptAsync({
sessionID: sessionId,
sessionID: activeSessionId,
directory: freshState.worktreeDir,
parts: [{ type: 'text' as const, text: continuationPrompt }],
})
@@ -466,7 +517,7 @@ export function createRalphEventHandler(
if (promptResult.error) {
const retryFn = async () => {
const freshState = ralphService.getActiveState(sessionId)
const freshState = ralphService.getActiveState(activeSessionId)
if (!freshState?.active) {
throw new Error('loop_cancelled')
}
@@ -475,7 +526,7 @@ export function createRalphEventHandler(
throw result.error
}
}
await handlePromptError(sessionId, currentState, 'failed to send continuation prompt after audit', promptResult.error, retryFn)
await handlePromptError(activeSessionId, currentState, 'failed to send continuation prompt after audit', promptResult.error, retryFn)
return
}
@@ -485,7 +536,7 @@ export function createRalphEventHandler(
logger.log(`coding continuation using default model (fallback)`)
}
consecutiveStalls.set(sessionId, 0)
consecutiveStalls.set(activeSessionId, 0)
}
async function onEvent(input: { event: { type: string; properties?: Record<string, unknown> } }): Promise<void> {
+5 -3
View File
@@ -608,7 +608,7 @@ 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: "See plan above" (the code agent continues this session and already has context)
- 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
Do NOT output text without also making this tool call.
@@ -774,19 +774,21 @@ Do NOT output text without also making this tool call.
const executionModel = parseModelString(config.executionModel)
if (args.inPlace) {
const inPlacePrompt = `The architect agent has created an implementation plan in this conversation above. You are now the code agent taking over this session. Your job is to execute the plan — edit files, run commands, create tests, and implement every phase. Do NOT just describe or summarize the changes. Actually make them.\n\nPlan reference: ${args.plan}`
const { result: promptResult, usedModel: actualModel } = await retryWithModelFallback(
() => v2.session.promptAsync({
sessionID: context.sessionID,
directory,
agent: 'code',
parts: [{ type: 'text' as const, text: args.plan }],
parts: [{ type: 'text' as const, text: inPlacePrompt }],
...(executionModel ? { model: executionModel } : {}),
}),
() => v2.session.promptAsync({
sessionID: context.sessionID,
directory,
agent: 'code',
parts: [{ type: 'text' as const, text: args.plan }],
parts: [{ type: 'text' as const, text: inPlacePrompt }],
}),
executionModel,
logger,
+1 -1
View File
@@ -1 +1 @@
export const VERSION = '0.0.23'
export const VERSION = '0.0.24'