Refactor Ralph session tracking with KV-backed session mapping and configurable TTL (#172)

* Fix Ralph state type safety and null handling in status commands

* Refactor Ralph to use worktree-keyed session mapping instead of sessionId lookups

* Add configurable KV TTL with 7-day default and update agent prompts

* Add --limit flag to CLI status and improve null safety for RalphState fields

* Bump memory package version to 0.0.25
This commit is contained in:
Chris Scott authored and GitHub committed 2026-03-25 14:55:44 -04:00
1 parent 86613b1ea4
commit bcfb7223c0
15 files changed
+387 -273

No files matched your search

+21 -6
View File
@@ -576,10 +576,10 @@ export function createMemoryRoutes(db: Database): Hono {
app.post('/ralph/cancel', async (c) => {
try {
const body = await c.req.json()
const { repoId, sessionId } = body
const { repoId, worktreeName, sessionId } = body
if (!repoId || !sessionId) {
return c.json({ error: 'Missing repoId or sessionId' }, 400)
if (!repoId || (!worktreeName && !sessionId)) {
return c.json({ error: 'Missing repoId or identifier (worktreeName or sessionId)' }, 400)
}
const repo = getRepoById(db, parseInt(repoId, 10))
@@ -594,8 +594,23 @@ export function createMemoryRoutes(db: Database): Hono {
return c.json({ cancelled: false })
}
const kvEntry = pluginMemory.getKv(projectId, `ralph:${sessionId}`)
let worktreeNameToUse: string | undefined
if (worktreeName) {
worktreeNameToUse = worktreeName
} else if (sessionId) {
const sessionMappingEntry = pluginMemory.getKv(projectId, `ralph-session:${sessionId}`)
if (!sessionMappingEntry) {
return c.json({ cancelled: false })
}
worktreeNameToUse = sessionMappingEntry.data as string
}
if (!worktreeNameToUse) {
return c.json({ cancelled: false })
}
const kvEntry = pluginMemory.getKv(projectId, `ralph:${worktreeNameToUse}`)
if (!kvEntry) {
return c.json({ cancelled: false })
}
@@ -620,10 +635,10 @@ export function createMemoryRoutes(db: Database): Hono {
completedAt: new Date().toISOString(),
}
pluginMemory.setKv(projectId, `ralph:${sessionId}`, updatedState)
pluginMemory.setKv(projectId, `ralph:${worktreeNameToUse}`, updatedState)
try {
const abortUrl = new URL(`${OPENCODE_SERVER_URL}/session/${sessionId}/abort`)
const abortUrl = new URL(`${OPENCODE_SERVER_URL}/session/${state.sessionId}/abort`)
abortUrl.searchParams.set('directory', repo.fullPath)
await fetch(abortUrl.toString(), { method: 'POST' })
} catch {
+18 -6
View File
@@ -147,7 +147,7 @@ describe('Memory Routes - Ralph Status', () => {
mockResolveProjectId.mockResolvedValue('test-project-id')
mockListKv.mockReturnValue([
{
key: 'ralph:session-123',
key: 'ralph:test-worktree',
data: {
active: true,
sessionId: 'session-123',
@@ -194,28 +194,40 @@ describe('Memory Routes - Ralph Status', () => {
mockResolveProjectId.mockResolvedValue('test-project-id')
mockListKv.mockReturnValue([
{
key: 'ralph:session-123',
data: { active: true, sessionId: 'session-123' },
key: 'ralph:test-worktree-1',
data: {
active: true,
sessionId: 'session-123',
worktreeName: 'test-worktree-1',
worktreeDir: '/tmp/test-worktree-1',
iteration: 1,
maxIterations: 10,
startedAt: new Date().toISOString(),
phase: 'coding',
errorCount: 0,
auditCount: 0,
completionPromise: null,
},
createdAt: Date.now(),
updatedAt: Date.now(),
expiresAt: Date.now() + 86400000,
},
{
key: 'ralph:session-456',
key: 'ralph:test-worktree-2',
data: null,
createdAt: Date.now(),
updatedAt: Date.now(),
expiresAt: Date.now() + 86400000,
},
{
key: 'ralph:session-789',
key: 'ralph:test-worktree-3',
data: 'string-data',
createdAt: Date.now(),
updatedAt: Date.now(),
expiresAt: Date.now() + 86400000,
},
{
key: 'ralph:session-abc',
key: 'ralph:test-worktree-4',
data: { sessionId: 'session-abc' },
createdAt: Date.now(),
updatedAt: Date.now(),
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@opencode-manager/memory",
"version": "0.0.24",
"version": "0.0.25",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
+2 -2
View File
@@ -59,12 +59,12 @@ ${getInjectedMemory('architect')}
## Project KV Store
You have access to a project-scoped key-value store with 24-hour TTL for ephemeral state:
You have access to a project-scoped key-value store with 7-day TTL for ephemeral state:
- \`memory-kv-set\`: Store planning progress, research findings, or any project state
- \`memory-kv-get\`: Retrieve previously stored state
- \`memory-kv-list\`: See all active entries for the project
KV entries are scoped to the current project and expire after 24 hours. Use this for state that needs to survive compaction but isn't permanent enough for memory-write.
KV entries are scoped to the current project and expire after 7 days. Use this for state that needs to survive compaction but isn't permanent enough for memory-write.
## Workflow
+3 -3
View File
@@ -149,9 +149,9 @@ Example:
The KV store upserts by key, so storing a finding for the same file:line automatically updates the previous entry. No dedup checks needed.
When the calling agent reports that a finding has been fixed, update the finding by calling \`memory-kv-set\` with the same key and the status changed to "resolved" with a resolution date added.
When a previously open finding has been addressed by the current changes, **delete it** using \`memory-kv-delete\` with the same key. Do not re-store resolved findings — removing them keeps the KV store clean and avoids extending the TTL on stale data.
Findings expire after 24 hours automatically. If an issue persists, the next review will re-discover it.
Findings expire after 7 days automatically. If an issue persists, the next review will re-discover it.
## Retrieving Past Findings
@@ -159,7 +159,7 @@ At the start of every review, before analyzing the diff:
1. Call \`memory-kv-list\` to get all active KV entries for the project
2. Filter entries with keys starting with \`review-finding:\` that match files in the current diff
3. If open findings exist for files being changed, include them under a "### Previously Identified Issues" heading before new findings
4. Check if any previously open findings have been addressed by the current changes — if so, update their status to "resolved" via \`memory-kv-set\` with the same key
4. Check if any previously open findings have been addressed by the current changes — if so, delete them via \`memory-kv-delete\` with the same key
${getInjectedMemory('auditor')}
`,
+2 -2
View File
@@ -79,11 +79,11 @@ 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:
You have access to a project-scoped key-value store with 7-day TTL for ephemeral state:
- \`memory-kv-set\`: Store ephemeral findings, planning progress, or session state
- \`memory-kv-get\`: Retrieve previously stored state
- \`memory-kv-list\`: See all active entries for the project
KV entries are scoped to the current project and expire after 24 hours. Use this for state that needs to survive compaction but isn't permanent enough for memory-write.
KV entries are scoped to the current project and expire after 7 days. Use this for state that needs to survive compaction but isn't permanent enough for memory-write.
`,
}
+24 -11
View File
@@ -23,6 +23,7 @@ export interface StatusArgs {
server?: string
listWorktrees?: boolean
listWorktreesFilter?: string
limit?: number
}
export async function run(argv: StatusArgs): Promise<void> {
@@ -83,7 +84,7 @@ export async function run(argv: StatusArgs): Promise<void> {
for (const row of rows) {
try {
const state = JSON.parse(row.data) as RalphState
if (state.active) {
if (state.active && state.sessionId && state.worktreeName && state.iteration != null && state.maxIterations != null && state.phase && state.startedAt) {
activeLoops.push({
sessionId: state.sessionId,
worktreeName: state.worktreeName,
@@ -92,7 +93,7 @@ export async function run(argv: StatusArgs): Promise<void> {
maxIterations: state.maxIterations,
phase: state.phase,
startedAt: state.startedAt,
audit: state.audit,
audit: state.audit ?? false,
})
} else if (state.completedAt) {
recentLoops.push({ state, row })
@@ -164,7 +165,8 @@ export async function run(argv: StatusArgs): Promise<void> {
}
const state = JSON.parse(row.data) as RalphState
const duration = Date.now() - new Date(state.startedAt).getTime()
const startedAt = state.startedAt!
const duration = Date.now() - new Date(startedAt).getTime()
const hours = Math.floor(duration / (1000 * 60 * 60))
const minutes = Math.floor((duration % (1000 * 60 * 60)) / (1000 * 60))
const seconds = Math.floor((duration % (1000 * 60)) / 1000)
@@ -184,9 +186,9 @@ export async function run(argv: StatusArgs): Promise<void> {
console.log(` Iteration: ${state.iteration}/${state.maxIterations}`)
console.log(` Duration: ${hours}h ${minutes}m ${seconds}s`)
console.log(` Audit: ${state.audit ? 'Yes' : 'No'}`)
console.log(` Error Count: ${state.errorCount}`)
console.log(` Audit Count: ${state.auditCount}`)
console.log(` Started: ${new Date(state.startedAt).toISOString()}`)
console.log(` Error Count: ${state.errorCount ?? 0}`)
console.log(` Audit Count: ${state.auditCount ?? 0}`)
console.log(` Started: ${new Date(startedAt).toISOString()}`)
if (state.completionPromise) {
console.log(` Completion: ${state.completionPromise}`)
}
@@ -196,7 +198,7 @@ export async function run(argv: StatusArgs): Promise<void> {
}
}
const sessionOutput = await tryFetchSessionOutput(argv.server ?? 'http://localhost:5551', state.sessionId, state.worktreeDir)
const sessionOutput = await tryFetchSessionOutput(argv.server ?? 'http://localhost:5551', state.sessionId, state.worktreeDir!)
if (sessionOutput) {
console.log('Session Output:')
for (const line of formatSessionOutput(sessionOutput)) {
@@ -207,7 +209,8 @@ export async function run(argv: StatusArgs): Promise<void> {
} else {
const state = matchedLoop.loop.state
const completedAt = state.completedAt!
const duration = new Date(completedAt).getTime() - new Date(state.startedAt).getTime()
const startedAt = state.startedAt!
const duration = new Date(completedAt).getTime() - new Date(startedAt).getTime()
const hours = Math.floor(duration / (1000 * 60 * 60))
const minutes = Math.floor((duration % (1000 * 60 * 60)) / (1000 * 60))
const seconds = Math.floor((duration % (1000 * 60)) / 1000)
@@ -226,7 +229,7 @@ export async function run(argv: StatusArgs): Promise<void> {
console.log(` Iteration: ${state.iteration}/${state.maxIterations}`)
console.log(` Duration: ${hours}h ${minutes}m ${seconds}s`)
console.log(` Reason: ${state.terminationReason ?? 'unknown'}`)
console.log(` Started: ${new Date(state.startedAt).toISOString()}`)
console.log(` Started: ${new Date(startedAt).toISOString()}`)
console.log(` Completed: ${new Date(completedAt).toISOString()}`)
if (state.lastAuditResult) {
for (const line of formatAuditResult(state.lastAuditResult)) {
@@ -234,7 +237,7 @@ export async function run(argv: StatusArgs): Promise<void> {
}
}
const sessionOutput = await tryFetchSessionOutput(argv.server ?? 'http://localhost:5551', state.sessionId, state.worktreeDir)
const sessionOutput = await tryFetchSessionOutput(argv.server ?? 'http://localhost:5551', state.sessionId, state.worktreeDir!)
if (sessionOutput) {
console.log('Session Output:')
for (const line of formatSessionOutput(sessionOutput)) {
@@ -270,7 +273,9 @@ export async function run(argv: StatusArgs): Promise<void> {
console.log('Recently Completed:')
console.log('')
for (const loop of recentLoops) {
const limit = argv.limit ?? 10
const displayedLoops = recentLoops.slice(0, limit)
for (const loop of displayedLoops) {
const reason = loop.state.terminationReason ?? 'unknown'
const completed = new Date(loop.state.completedAt!).toLocaleString()
@@ -278,6 +283,11 @@ export async function run(argv: StatusArgs): Promise<void> {
console.log(` Iterations: ${loop.state.iteration} Reason: ${reason} Completed: ${completed}`)
console.log('')
}
if (recentLoops.length > limit) {
console.log(` ... and ${recentLoops.length - limit} more. Use 'ocm-mem status <name>' for details.`)
console.log('')
}
}
if (activeLoops.length === 0 && recentLoops.length === 0) {
@@ -309,6 +319,7 @@ Options:
--server <url> OpenCode server URL (default: http://localhost:5551)
--list-worktrees List all worktree names (for shell completion)
Optionally provide a filter: --list-worktrees <filter>
--limit <n> Limit recent loops shown (default: 10)
--project, -p <id> Project ID (auto-detected from git if not provided)
--db-path <path> Path to memory database
--help, -h Show this help message
@@ -332,6 +343,8 @@ export async function cli(args: string[], globalOpts: { dbPath?: string; resolve
if (i + 1 < args.length && !args[i + 1].startsWith('-')) {
argv.listWorktreesFilter = args[++i]
}
} else if (arg === '--limit') {
argv.limit = parseInt(args[++i], 10)
} else if (arg === '--help' || arg === '-h') {
help()
process.exit(0)
+138 -121
View File
@@ -11,8 +11,8 @@ export interface RalphEventHandler {
onEvent(input: { event: { type: string; properties?: Record<string, unknown> } }): Promise<void>
terminateAll(): void
clearAllRetryTimeouts(): void
startWatchdog(sessionId: string): void
getStallInfo(sessionId: string): { consecutiveStalls: number; lastActivityTime: number } | null
startWatchdog(worktreeName: string): void
getStallInfo(worktreeName: string): { consecutiveStalls: number; lastActivityTime: number } | null
cancelBySessionId(sessionId: string): Promise<boolean>
}
@@ -28,6 +28,7 @@ export function createRalphEventHandler(
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`)
@@ -82,36 +83,37 @@ export function createRalphEventHandler(
return { committed, cleaned }
}
function stopWatchdog(sessionId: string): void {
const interval = stallWatchdogs.get(sessionId)
function stopWatchdog(worktreeName: string): void {
const interval = stallWatchdogs.get(worktreeName)
if (interval) {
clearInterval(interval)
stallWatchdogs.delete(sessionId)
stallWatchdogs.delete(worktreeName)
}
lastActivityTime.delete(sessionId)
consecutiveStalls.delete(sessionId)
lastActivityTime.delete(worktreeName)
consecutiveStalls.delete(worktreeName)
}
function startWatchdog(sessionId: string): void {
stopWatchdog(sessionId)
lastActivityTime.set(sessionId, Date.now())
consecutiveStalls.set(sessionId, 0)
function startWatchdog(worktreeName: string): void {
stopWatchdog(worktreeName)
lastActivityTime.set(worktreeName, Date.now())
consecutiveStalls.set(worktreeName, 0)
const stallTimeout = ralphService.getStallTimeoutMs()
const interval = setInterval(async () => {
const lastActivity = lastActivityTime.get(sessionId)
const lastActivity = lastActivityTime.get(worktreeName)
if (!lastActivity) return
const elapsed = Date.now() - lastActivity
if (elapsed < stallTimeout) return
const state = ralphService.getActiveState(sessionId)
const state = ralphService.getActiveState(worktreeName)
if (!state?.active) {
stopWatchdog(sessionId)
stopWatchdog(worktreeName)
return
}
const sessionId = state.sessionId
try {
const statusResult = await v2Client.session.status()
const statuses = (statusResult.data ?? {}) as Record<string, { type: string }>
@@ -120,8 +122,8 @@ export function createRalphEventHandler(
const hasActiveWork = status === 'busy' || status === 'retry' || status === 'compact'
if (hasActiveWork) {
lastActivityTime.set(sessionId, Date.now())
logger.log(`Ralph watchdog: session ${sessionId} has active work, resetting timer`)
lastActivityTime.set(worktreeName, Date.now())
logger.log(`Ralph watchdog: worktree ${worktreeName} has active work, resetting timer`)
return
}
} catch (err) {
@@ -129,52 +131,55 @@ export function createRalphEventHandler(
return
}
const stallCount = (consecutiveStalls.get(sessionId) ?? 0) + 1
consecutiveStalls.set(sessionId, stallCount)
lastActivityTime.set(sessionId, Date.now())
const stallCount = (consecutiveStalls.get(worktreeName) ?? 0) + 1
consecutiveStalls.set(worktreeName, stallCount)
lastActivityTime.set(worktreeName, Date.now())
if (stallCount >= MAX_CONSECUTIVE_STALLS) {
logger.error(`Ralph watchdog: session ${sessionId} exceeded max consecutive stalls (${MAX_CONSECUTIVE_STALLS}), terminating`)
await terminateLoop(sessionId, state, 'stall_timeout')
logger.error(`Ralph watchdog: worktree ${worktreeName} exceeded max consecutive stalls (${MAX_CONSECUTIVE_STALLS}), terminating`)
await terminateLoop(worktreeName, state, 'stall_timeout')
return
}
logger.log(`Ralph watchdog: stall detected for session ${sessionId} (${stallCount}/${MAX_CONSECUTIVE_STALLS}), re-triggering ${state.phase} phase`)
logger.log(`Ralph watchdog: stall detected for worktree ${worktreeName} (${stallCount}/${MAX_CONSECUTIVE_STALLS}), re-triggering ${state.phase} phase`)
try {
if (state.phase === 'auditing') {
await handleAuditingPhase(sessionId, state)
await handleAuditingPhase(worktreeName, state)
} else {
await handleCodingPhase(sessionId, state)
await handleCodingPhase(worktreeName, state)
}
} catch (err) {
await handlePromptError(sessionId, state, `watchdog recovery in ${state.phase} phase`, err)
await handlePromptError(worktreeName, state, `watchdog recovery in ${state.phase} phase`, err)
}
}, stallTimeout)
stallWatchdogs.set(sessionId, interval)
logger.log(`Ralph watchdog: started for session ${sessionId} (timeout: ${stallTimeout}ms)`)
stallWatchdogs.set(worktreeName, interval)
logger.log(`Ralph watchdog: started for worktree ${worktreeName} (timeout: ${stallTimeout}ms)`)
}
function getStallInfo(sessionId: string): { consecutiveStalls: number; lastActivityTime: number } | null {
const lastActivity = lastActivityTime.get(sessionId)
function getStallInfo(worktreeName: string): { consecutiveStalls: number; lastActivityTime: number } | null {
const lastActivity = lastActivityTime.get(worktreeName)
if (lastActivity === undefined) return null
return {
consecutiveStalls: consecutiveStalls.get(sessionId) ?? 0,
consecutiveStalls: consecutiveStalls.get(worktreeName) ?? 0,
lastActivityTime: lastActivity,
}
}
async function terminateLoop(sessionId: string, state: RalphState, reason: string): Promise<void> {
stopWatchdog(sessionId)
async function terminateLoop(worktreeName: string, state: RalphState, reason: string): Promise<void> {
const sessionId = state.sessionId
stopWatchdog(worktreeName)
const retryTimeout = retryTimeouts.get(sessionId)
const retryTimeout = retryTimeouts.get(worktreeName)
if (retryTimeout) {
clearTimeout(retryTimeout)
retryTimeouts.delete(sessionId)
retryTimeouts.delete(worktreeName)
}
ralphService.setState(sessionId, {
ralphService.unregisterSession(sessionId)
ralphService.setState(worktreeName, {
...state,
active: false,
completedAt: new Date().toISOString(),
@@ -195,10 +200,11 @@ export function createRalphEventHandler(
}
}
async function handlePromptError(sessionId: string, state: RalphState, context: string, err: unknown, retryFn?: () => Promise<void>): Promise<void> {
const currentState = ralphService.getActiveState(sessionId)
async function handlePromptError(worktreeName: string, state: RalphState, context: string, err: unknown, retryFn?: () => Promise<void>): Promise<void> {
const sessionId = state.sessionId
const currentState = ralphService.getActiveState(worktreeName)
if (!currentState?.active) {
logger.log(`Ralph: loop ${sessionId} already terminated, ignoring error: ${context}`)
logger.log(`Ralph: loop ${worktreeName} already terminated, ignoring error: ${context}`)
return
}
@@ -206,26 +212,26 @@ export function createRalphEventHandler(
if (nextErrorCount < MAX_RETRIES) {
logger.error(`Ralph: ${context} (attempt ${nextErrorCount}/${MAX_RETRIES}), will retry`, err)
ralphService.setState(sessionId, { ...currentState, errorCount: nextErrorCount })
ralphService.setState(worktreeName, { ...currentState, errorCount: nextErrorCount })
if (retryFn) {
const retryTimeout = setTimeout(async () => {
const freshState = ralphService.getActiveState(sessionId)
const freshState = ralphService.getActiveState(worktreeName)
if (!freshState?.active) {
logger.log(`Ralph: loop cancelled, skipping retry`)
retryTimeouts.delete(sessionId)
retryTimeouts.delete(worktreeName)
return
}
try {
await retryFn()
} catch (retryErr) {
await handlePromptError(sessionId, freshState, context, retryErr, retryFn)
await handlePromptError(worktreeName, freshState, context, retryErr, retryFn)
}
}, 2000)
retryTimeouts.set(sessionId, retryTimeout)
retryTimeouts.set(worktreeName, retryTimeout)
}
} else {
logger.error(`Ralph: ${context} (attempt ${nextErrorCount}/${MAX_RETRIES}), giving up`, err)
await terminateLoop(sessionId, currentState, `error_max_retries: ${context}`)
await terminateLoop(worktreeName, currentState, `error_max_retries: ${context}`)
}
}
@@ -260,7 +266,8 @@ export function createRalphEventHandler(
}
}
async function rotateSession(oldSessionId: string, state: RalphState): Promise<string> {
async function rotateSession(worktreeName: string, state: RalphState): Promise<string> {
const oldSessionId = state.sessionId
const createResult = await v2Client.session.create({
title: state.worktreeName,
directory: state.worktreeDir,
@@ -272,16 +279,17 @@ export function createRalphEventHandler(
const newSessionId = createResult.data.id
const oldRetryTimeout = retryTimeouts.get(oldSessionId)
const oldRetryTimeout = retryTimeouts.get(worktreeName)
if (oldRetryTimeout) {
clearTimeout(oldRetryTimeout)
retryTimeouts.delete(oldSessionId)
retryTimeouts.delete(worktreeName)
}
ralphService.deleteState(oldSessionId)
ralphService.unregisterSession(oldSessionId)
ralphService.registerSession(newSessionId, worktreeName)
stopWatchdog(oldSessionId)
startWatchdog(newSessionId)
stopWatchdog(worktreeName)
startWatchdog(worktreeName)
v2Client.session.delete({ sessionID: oldSessionId, directory: state.worktreeDir }).catch((err) => {
logger.error(`Ralph: failed to delete old session ${oldSessionId}`, err)
@@ -291,22 +299,22 @@ export function createRalphEventHandler(
return newSessionId
}
async function handleCodingPhase(sessionId: string, state: RalphState): Promise<void> {
let currentState = ralphService.getActiveState(sessionId)
async function handleCodingPhase(worktreeName: string, state: RalphState): Promise<void> {
let currentState = ralphService.getActiveState(worktreeName)
if (!currentState?.active) {
logger.log(`Ralph: loop ${sessionId} no longer active, skipping coding phase`)
logger.log(`Ralph: loop ${worktreeName} no longer active, skipping coding phase`)
return
}
if (!currentState.worktreeDir) {
logger.error(`Ralph: loop ${sessionId} missing worktreeDir in coding phase, terminating`)
await terminateLoop(sessionId, currentState, 'missing_worktree_dir')
logger.error(`Ralph: loop ${worktreeName} missing worktreeDir in coding phase, terminating`)
await terminateLoop(worktreeName, currentState, 'missing_worktree_dir')
return
}
let assistantErrorDetected = false
if (currentState.completionPromise) {
const { text: textContent, error: assistantError } = await getLastAssistantInfo(sessionId, currentState.worktreeDir)
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}`)
@@ -314,18 +322,18 @@ export function createRalphEventHandler(
if (isModelError) {
const nextErrorCount = (currentState.errorCount ?? 0) + 1
if (nextErrorCount >= MAX_RETRIES) {
await terminateLoop(sessionId, currentState, `error_max_retries: assistant error: ${assistantError}`)
await terminateLoop(worktreeName, currentState, `error_max_retries: assistant error: ${assistantError}`)
return
}
ralphService.setState(sessionId, { ...currentState, modelFailed: true, errorCount: nextErrorCount })
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(sessionId)!
currentState = ralphService.getActiveState(worktreeName)!
}
}
if (textContent && currentState.completionPromise && ralphService.checkCompletionPromise(textContent, currentState.completionPromise)) {
const currentAuditCount = currentState.auditCount ?? 0
if (!currentState.audit || currentAuditCount >= minAudits) {
await terminateLoop(sessionId, currentState, 'completed')
await terminateLoop(worktreeName, currentState, 'completed')
logger.log(`Ralph loop completed: detected <promise>${currentState.completionPromise}</promise> at iteration ${currentState.iteration} (${currentAuditCount}/${minAudits} audits)`)
return
}
@@ -334,22 +342,22 @@ export function createRalphEventHandler(
}
if (!assistantErrorDetected && currentState.errorCount && currentState.errorCount > 0) {
ralphService.setState(sessionId, { ...currentState, errorCount: 0 })
ralphService.setState(worktreeName, { ...currentState, errorCount: 0 })
logger.log(`Ralph: resetting error count after successful retry in coding phase`)
currentState = ralphService.getActiveState(sessionId)!
currentState = ralphService.getActiveState(worktreeName)!
}
if ((currentState.maxIterations ?? 0) > 0 && (currentState.iteration ?? 0) >= (currentState.maxIterations ?? 0)) {
await terminateLoop(sessionId, currentState, 'max_iterations')
await terminateLoop(worktreeName, currentState, 'max_iterations')
return
}
if (currentState.audit) {
ralphService.setState(sessionId, { ...currentState, phase: 'auditing', errorCount: 0 })
logger.log(`Ralph iteration ${currentState.iteration ?? 0} complete, running auditor for session ${sessionId}`)
ralphService.setState(worktreeName, { ...currentState, phase: 'auditing', errorCount: 0 })
logger.log(`Ralph iteration ${currentState.iteration ?? 0} complete, running auditor for session ${currentState.sessionId}`)
const auditPrompt = {
sessionID: sessionId,
sessionID: currentState.sessionId,
directory: currentState.worktreeDir,
parts: [{
type: 'subtask' as const,
@@ -368,7 +376,7 @@ export function createRalphEventHandler(
throw result.error
}
}
await handlePromptError(sessionId, { ...currentState, phase: 'coding' }, 'failed to send audit prompt', promptResult.error, retryFn)
await handlePromptError(worktreeName, { ...currentState, phase: 'coding' }, 'failed to send audit prompt', promptResult.error, retryFn)
return
}
@@ -376,19 +384,19 @@ export function createRalphEventHandler(
const configuredModel = currentConfig.auditorModel ?? currentConfig.ralph?.model ?? currentConfig.executionModel
logger.log(`auditor using agent-configured model: ${configuredModel ?? 'default'}`)
consecutiveStalls.set(sessionId, 0)
consecutiveStalls.set(worktreeName, 0)
return
}
let activeSessionId = sessionId
let activeSessionId = currentState.sessionId
try {
activeSessionId = await rotateSession(sessionId, currentState)
activeSessionId = await rotateSession(worktreeName, currentState)
} catch (err) {
logger.error(`Ralph: session rotation failed, continuing with existing session`, err)
}
const nextIteration = (currentState.iteration ?? 0) + 1
ralphService.setState(activeSessionId, {
ralphService.setState(worktreeName, {
...currentState,
sessionId: activeSessionId,
iteration: nextIteration,
@@ -399,7 +407,7 @@ export function createRalphEventHandler(
logger.log(`Ralph iteration ${nextIteration} for session ${activeSessionId}`)
const currentConfig = getConfig()
const freshStateForModel = ralphService.getActiveState(activeSessionId)
const freshStateForModel = ralphService.getActiveState(worktreeName)
const ralphModel = freshStateForModel?.modelFailed
? undefined
: (parseModelString(currentConfig.ralph?.model) ?? parseModelString(currentConfig.executionModel))
@@ -409,7 +417,7 @@ export function createRalphEventHandler(
}
const sendContinuationPromptWithModel = async () => {
const freshState = ralphService.getActiveState(activeSessionId)
const freshState = ralphService.getActiveState(worktreeName)
if (!freshState?.active) {
throw new Error('loop_cancelled')
}
@@ -423,7 +431,7 @@ export function createRalphEventHandler(
}
const sendContinuationPromptWithoutModel = async () => {
const freshState = ralphService.getActiveState(activeSessionId)
const freshState = ralphService.getActiveState(worktreeName)
if (!freshState?.active) {
throw new Error('loop_cancelled')
}
@@ -446,11 +454,11 @@ export function createRalphEventHandler(
const retryFn = async () => {
const result = await sendContinuationPromptWithoutModel()
if (result.error) {
await handlePromptError(activeSessionId, currentState, 'retry failed', result.error)
await handlePromptError(worktreeName, currentState, 'retry failed', result.error)
return
}
}
await handlePromptError(activeSessionId, currentState, 'failed to send continuation prompt', promptResult.error, retryFn)
await handlePromptError(worktreeName, currentState, 'failed to send continuation prompt', promptResult.error, retryFn)
return
}
@@ -460,24 +468,24 @@ export function createRalphEventHandler(
logger.log(`coding phase using default model (fallback)`)
}
consecutiveStalls.set(activeSessionId, 0)
consecutiveStalls.set(worktreeName, 0)
}
async function handleAuditingPhase(sessionId: string, state: RalphState): Promise<void> {
async function handleAuditingPhase(worktreeName: string, state: RalphState): Promise<void> {
// Re-fetch and validate state to catch aborts that happened during idle event processing
let currentState = ralphService.getActiveState(sessionId)
let currentState = ralphService.getActiveState(worktreeName)
if (!currentState?.active) {
logger.log(`Ralph: loop ${sessionId} no longer active, skipping auditing phase`)
logger.log(`Ralph: loop ${worktreeName} no longer active, skipping auditing phase`)
return
}
if (!currentState.worktreeDir) {
logger.error(`Ralph: loop ${sessionId} missing worktreeDir in auditing phase, terminating`)
await terminateLoop(sessionId, currentState, 'missing_worktree_dir')
logger.error(`Ralph: loop ${worktreeName} missing worktreeDir in auditing phase, terminating`)
await terminateLoop(worktreeName, currentState, 'missing_worktree_dir')
return
}
const { text: auditText, error: assistantError } = await getLastAssistantInfo(sessionId, currentState.worktreeDir)
const { text: auditText, error: assistantError } = await getLastAssistantInfo(currentState.sessionId, currentState.worktreeDir)
let assistantErrorDetected = false
if (assistantError) {
@@ -487,19 +495,19 @@ export function createRalphEventHandler(
if (isModelError) {
const nextErrorCount = (currentState.errorCount ?? 0) + 1
if (nextErrorCount >= MAX_RETRIES) {
await terminateLoop(sessionId, currentState, `error_max_retries: assistant error: ${assistantError}`)
await terminateLoop(worktreeName, currentState, `error_max_retries: assistant error: ${assistantError}`)
return
}
ralphService.setState(sessionId, { ...currentState, modelFailed: true, errorCount: nextErrorCount })
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(sessionId)!
currentState = ralphService.getActiveState(worktreeName)!
}
}
if (!assistantErrorDetected && currentState.errorCount && currentState.errorCount > 0) {
ralphService.setState(sessionId, { ...currentState, errorCount: 0 })
ralphService.setState(worktreeName, { ...currentState, errorCount: 0 })
logger.log(`Ralph: resetting error count after successful retry in auditing phase`)
currentState = ralphService.getActiveState(sessionId)!
currentState = ralphService.getActiveState(worktreeName)!
}
const nextIteration = (currentState.iteration ?? 0) + 1
@@ -513,7 +521,7 @@ export function createRalphEventHandler(
if (ralphService.checkCompletionPromise(auditText, currentState.completionPromise)) {
// Check if minimum audits have been performed
if (!currentState.audit || newAuditCount >= minAudits) {
await terminateLoop(sessionId, currentState, 'completed')
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
}
@@ -522,18 +530,18 @@ export function createRalphEventHandler(
}
if ((currentState.maxIterations ?? 0) > 0 && nextIteration > (currentState.maxIterations ?? 0)) {
await terminateLoop(sessionId, currentState, 'max_iterations')
await terminateLoop(worktreeName, currentState, 'max_iterations')
return
}
let activeSessionId = sessionId
let activeSessionId = currentState.sessionId
try {
activeSessionId = await rotateSession(sessionId, currentState)
activeSessionId = await rotateSession(worktreeName, currentState)
} catch (err) {
logger.error(`Ralph: session rotation failed, continuing with existing session`, err)
}
ralphService.setState(activeSessionId, {
ralphService.setState(worktreeName, {
...currentState,
sessionId: activeSessionId,
iteration: nextIteration,
@@ -550,7 +558,7 @@ export function createRalphEventHandler(
logger.log(`Ralph iteration ${nextIteration} for session ${activeSessionId}`)
const currentConfig = getConfig()
const freshStateForModel = ralphService.getActiveState(activeSessionId)
const freshStateForModel = ralphService.getActiveState(worktreeName)
const ralphModel = freshStateForModel?.modelFailed
? undefined
: (parseModelString(currentConfig.ralph?.model) ?? parseModelString(currentConfig.executionModel))
@@ -560,7 +568,7 @@ export function createRalphEventHandler(
}
const sendContinuationPromptWithModel = async () => {
const freshState = ralphService.getActiveState(activeSessionId)
const freshState = ralphService.getActiveState(worktreeName)
if (!freshState?.active) {
throw new Error('loop_cancelled')
}
@@ -574,7 +582,7 @@ export function createRalphEventHandler(
}
const sendContinuationPromptWithoutModel = async () => {
const freshState = ralphService.getActiveState(activeSessionId)
const freshState = ralphService.getActiveState(worktreeName)
if (!freshState?.active) {
throw new Error('loop_cancelled')
}
@@ -595,17 +603,17 @@ export function createRalphEventHandler(
if (promptResult.error) {
const retryFn = async () => {
const freshState = ralphService.getActiveState(activeSessionId)
const freshState = ralphService.getActiveState(worktreeName)
if (!freshState?.active) {
throw new Error('loop_cancelled')
}
const result = await sendContinuationPromptWithoutModel()
if (result.error) {
await handlePromptError(activeSessionId, currentState, 'retry failed after audit', result.error)
await handlePromptError(worktreeName, currentState, 'retry failed after audit', result.error)
return
}
}
await handlePromptError(activeSessionId, currentState, 'failed to send continuation prompt after audit', promptResult.error, retryFn)
await handlePromptError(worktreeName, currentState, 'failed to send continuation prompt after audit', promptResult.error, retryFn)
return
}
@@ -615,7 +623,7 @@ export function createRalphEventHandler(
logger.log(`coding continuation using default model (fallback)`)
}
consecutiveStalls.set(activeSessionId, 0)
consecutiveStalls.set(worktreeName, 0)
}
async function onEvent(input: { event: { type: string; properties?: Record<string, unknown> } }): Promise<void> {
@@ -630,7 +638,7 @@ export function createRalphEventHandler(
const activeLoops = ralphService.listActive()
const affectedLoop = activeLoops.find((s) => s.worktreeDir === directory)
if (affectedLoop) {
await terminateLoop(affectedLoop.sessionId, affectedLoop, `worktree_failed: ${message}`)
await terminateLoop(affectedLoop.worktreeName, affectedLoop, `worktree_failed: ${message}`)
}
}
return
@@ -645,22 +653,26 @@ export function createRalphEventHandler(
if (!eventSessionId) return
if (isAbort) {
const state = ralphService.getActiveState(eventSessionId)
const worktreeName = ralphService.resolveWorktreeName(eventSessionId)
if (!worktreeName) return
const state = ralphService.getActiveState(worktreeName)
if (state?.active) {
logger.log(`Ralph: session ${eventSessionId} aborted, terminating loop`)
await terminateLoop(eventSessionId, state, 'user_aborted')
await terminateLoop(worktreeName, state, 'user_aborted')
}
return
}
const state = ralphService.getActiveState(eventSessionId)
const worktreeName = ralphService.resolveWorktreeName(eventSessionId)
if (!worktreeName) return
const state = ralphService.getActiveState(worktreeName)
if (state?.active) {
const errorMessage = errorProps?.error?.data?.message ?? errorName ?? 'unknown error'
logger.error(`Ralph: 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(eventSessionId, { ...state, modelFailed: true })
ralphService.setState(worktreeName, { ...state, modelFailed: true })
}
}
return
@@ -671,25 +683,30 @@ export function createRalphEventHandler(
const sessionId = event.properties?.sessionID as string
if (!sessionId) return
const state = ralphService.getActiveState(sessionId)
const worktreeName = ralphService.resolveWorktreeName(sessionId)
if (!worktreeName) return
const state = ralphService.getActiveState(worktreeName)
if (!state || !state.active) return
try {
// Re-check state right before calling phase handler as extra safety
const freshState = ralphService.getActiveState(sessionId)
const freshState = ralphService.getActiveState(worktreeName)
if (!freshState?.active) {
logger.log(`Ralph: loop ${sessionId} was terminated, skipping phase handler`)
logger.log(`Ralph: loop ${worktreeName} was terminated, skipping phase handler`)
return
}
startWatchdog(worktreeName)
if (freshState.phase === 'auditing') {
await handleAuditingPhase(sessionId, freshState)
await handleAuditingPhase(worktreeName, freshState)
} else {
await handleCodingPhase(sessionId, freshState)
await handleCodingPhase(worktreeName, freshState)
}
} catch (err) {
const freshState = ralphService.getActiveState(sessionId)
await handlePromptError(sessionId, freshState ?? state, `unhandled error in ${(freshState ?? state).phase} phase`, err)
const freshState = ralphService.getActiveState(worktreeName)
await handlePromptError(worktreeName, freshState ?? state, `unhandled error in ${(freshState ?? state).phase} phase`, err)
}
}
@@ -698,13 +715,13 @@ export function createRalphEventHandler(
}
function clearAllRetryTimeouts(): void {
for (const [sessionId, timeout] of retryTimeouts.entries()) {
for (const [worktreeName, timeout] of retryTimeouts.entries()) {
clearTimeout(timeout)
retryTimeouts.delete(sessionId)
retryTimeouts.delete(worktreeName)
}
for (const [sessionId, interval] of stallWatchdogs.entries()) {
for (const [worktreeName, interval] of stallWatchdogs.entries()) {
clearInterval(interval)
stallWatchdogs.delete(sessionId)
stallWatchdogs.delete(worktreeName)
}
lastActivityTime.clear()
consecutiveStalls.clear()
@@ -712,11 +729,11 @@ export function createRalphEventHandler(
}
async function cancelBySessionId(sessionId: string): Promise<boolean> {
const state = ralphService.getActiveState(sessionId)
if (!state?.active) {
return false
}
await terminateLoop(sessionId, state, 'cancelled')
const worktreeName = ralphService.resolveWorktreeName(sessionId)
if (!worktreeName) return false
const state = ralphService.getActiveState(worktreeName)
if (!state?.active) return false
await terminateLoop(worktreeName, state, 'cancelled')
return true
}
+73 -48
View File
@@ -298,7 +298,7 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
memoryService.setDedupThreshold(config.dedupThreshold)
}
const kvService = createKvService(db, logger)
const kvService = createKvService(db, logger, config.defaultKvTtlMs)
const ralphService = createRalphService(kvService, projectId, logger, config.ralph)
const ralphHandler = createRalphEventHandler(ralphService, client, v2, logger, () => config)
@@ -412,7 +412,7 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
agent?: string
model?: { providerID: string; modelID: string }
inPlace?: boolean
onLoopStarted?: (sessionId: string) => void
onLoopStarted?: (worktreeName: string) => void
}
async function setupRalphLoop(options: RalphSetupOptions): Promise<string> {
@@ -510,8 +510,9 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
inPlace: options.inPlace,
}
ralphService.setState(loopContext.sessionId, state)
logger.log(`ralph: state stored for session=${loopContext.sessionId}`)
ralphService.setState(autoWorktreeName, state)
ralphService.registerSession(loopContext.sessionId, autoWorktreeName)
logger.log(`ralph: state stored for worktree=${autoWorktreeName}`)
let promptText = options.prompt
if (options.completionPromise) {
@@ -538,7 +539,7 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
if (promptResult.error) {
logger.error(`ralph: failed to send prompt`, promptResult.error)
ralphService.deleteState(loopContext.sessionId)
ralphService.deleteState(autoWorktreeName)
if (!options.inPlace && loopContext.workspaceId) {
try {
await v2.worktree.remove({ worktreeRemoveInput: { directory: loopContext.directory } })
@@ -551,7 +552,7 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
: 'Ralph session created but failed to send prompt. Cleaned up.'
}
options.onLoopStarted?.(loopContext.sessionId)
options.onLoopStarted?.(autoWorktreeName)
const maxInfo = maxIter > 0 ? maxIter.toString() : 'unlimited'
const auditInfo = options.audit ? 'enabled' : 'disabled'
@@ -882,11 +883,11 @@ Do NOT output text without also making this tool call.
},
}),
'memory-kv-set': tool({
description: 'Store a key-value pair for the current project. Values expire after 24 hours by default. Use for ephemeral project state like planning progress, code review patterns, or session context.',
description: 'Store a key-value pair for the current project. Values expire after 7 days by default. Use for ephemeral project state like planning progress, code review patterns, or session context.',
args: {
key: z.string().describe('The key to store the value under'),
value: z.string().describe('The value to store (JSON string)'),
ttlMs: z.number().optional().describe('Time-to-live in milliseconds (default: 24 hours)'),
ttlMs: z.number().optional().describe('Time-to-live in milliseconds (default: 7 days)'),
},
execute: async (args) => {
logger.log(`memory-kv-set: key="${args.key}"`)
@@ -897,7 +898,7 @@ Do NOT output text without also making this tool call.
parsed = args.value
}
kvService.set(projectId, args.key, parsed, args.ttlMs)
const expiresAt = new Date(Date.now() + (args.ttlMs ?? 24 * 60 * 60 * 1000))
const expiresAt = new Date(Date.now() + (args.ttlMs ?? 7 * 24 * 60 * 60 * 1000))
logger.log(`memory-kv-set: stored key="${args.key}", expires=${expiresAt.toISOString()}`)
return `Stored key "${args.key}" (expires ${expiresAt.toISOString()})`
},
@@ -920,10 +921,14 @@ Do NOT output text without also making this tool call.
}),
'memory-kv-list': tool({
description: 'List all active key-value pairs for the current project.',
args: {},
execute: async () => {
logger.log('memory-kv-list')
const entries = kvService.list(projectId)
args: {
prefix: z.string().optional().describe('Filter entries by key prefix (e.g. "review-finding:")'),
},
execute: async (args) => {
logger.log(`memory-kv-list: prefix="${args.prefix ?? 'none'}"`)
const entries = args.prefix
? kvService.listByPrefix(projectId, args.prefix)
: kvService.list(projectId)
if (entries.length === 0) {
logger.log('memory-kv-list: no entries')
return 'No active KV entries for this project.'
@@ -938,6 +943,17 @@ Do NOT output text without also making this tool call.
return `${entries.length} active KV entries:\n\n${formatted.join('\n')}`
},
}),
'memory-kv-delete': tool({
description: 'Delete a key-value pair for the current project.',
args: {
key: z.string().describe('The key to delete'),
},
execute: async (args) => {
logger.log(`memory-kv-delete: key="${args.key}"`)
kvService.delete(projectId, args.key)
return `Deleted key "${args.key}"`
},
}),
'ralph-cancel': tool({
description: 'Cancel an active Ralph loop and optionally clean up the worktree.',
@@ -978,7 +994,7 @@ Do NOT output text without also making this tool call.
await ralphHandler.cancelBySessionId(state.sessionId)
logger.log(`ralph-cancel: cancelled loop for session=${state.sessionId} at iteration ${state.iteration}`)
if (config.ralph?.cleanupWorktree && !state.inPlace) {
if (config.ralph?.cleanupWorktree && !state.inPlace && 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, '..')
@@ -1030,15 +1046,15 @@ Do NOT output text without also making this tool call.
return `Loop "${stoppedState.worktreeName}" completed successfully and cannot be restarted.`
}
if (!stoppedState.inPlace) {
if (!stoppedState.inPlace && 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.`
}
}
const createResult = await v2.session.create({
title: stoppedState.worktreeName,
directory: stoppedState.worktreeDir,
title: stoppedState.worktreeName!,
directory: stoppedState.worktreeDir!,
})
if (createResult.error || !createResult.data) {
@@ -1048,17 +1064,17 @@ Do NOT output text without also making this tool call.
const newSessionId = createResult.data.id
ralphService.deleteState(stoppedState.sessionId)
ralphService.deleteState(stoppedState.worktreeName!)
const newState: RalphState = {
active: true,
sessionId: newSessionId,
worktreeName: stoppedState.worktreeName,
worktreeDir: stoppedState.worktreeDir,
worktreeName: stoppedState.worktreeName!,
worktreeDir: stoppedState.worktreeDir!,
worktreeBranch: stoppedState.worktreeBranch,
workspaceId: stoppedState.workspaceId,
iteration: stoppedState.iteration,
maxIterations: stoppedState.maxIterations,
iteration: stoppedState.iteration!,
maxIterations: stoppedState.maxIterations!,
completionPromise: stoppedState.completionPromise,
startedAt: new Date().toISOString(),
prompt: stoppedState.prompt,
@@ -1069,9 +1085,10 @@ Do NOT output text without also making this tool call.
inPlace: stoppedState.inPlace,
}
ralphService.setState(newSessionId, newState)
ralphService.setState(stoppedState.worktreeName!, newState)
ralphService.registerSession(newSessionId, stoppedState.worktreeName!)
let promptText = stoppedState.prompt
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.`
}
@@ -1081,14 +1098,14 @@ Do NOT output text without also making this tool call.
const { result: promptResult } = await retryWithModelFallback(
() => v2.session.promptAsync({
sessionID: newSessionId,
directory: stoppedState.worktreeDir,
directory: stoppedState.worktreeDir!,
parts: [{ type: 'text' as const, text: promptText }],
agent: 'code',
model: ralphModel!,
}),
() => v2.session.promptAsync({
sessionID: newSessionId,
directory: stoppedState.worktreeDir,
directory: stoppedState.worktreeDir!,
parts: [{ type: 'text' as const, text: promptText }],
agent: 'code',
}),
@@ -1098,11 +1115,11 @@ Do NOT output text without also making this tool call.
if (promptResult.error) {
logger.error(`ralph-restart: failed to send prompt`, promptResult.error)
ralphService.deleteState(newSessionId)
ralphService.deleteState(stoppedState.worktreeName!)
return `Restart failed: could not send prompt to new session.`
}
ralphHandler.startWatchdog(newSessionId)
ralphHandler.startWatchdog(stoppedState.worktreeName!)
const modeInfo = stoppedState.inPlace ? ' (in-place)' : ''
const branchInfo = stoppedState.worktreeBranch ? `\nBranch: ${stoppedState.worktreeBranch}` : ''
@@ -1125,14 +1142,14 @@ Do NOT output text without also making this tool call.
const lines: string[] = ['Recently Completed Ralph Loops', '']
recent.forEach((s, i) => {
const duration = s.completedAt
const duration = s.completedAt && s.startedAt
? Math.round((new Date(s.completedAt).getTime() - new Date(s.startedAt).getTime()) / 1000)
: 0
const minutes = Math.floor(duration / 60)
const seconds = duration % 60
const durationStr = minutes > 0 ? `${minutes}m ${seconds}s` : `${seconds}s`
lines.push(`${i + 1}. ${s.worktreeName}`)
lines.push(` Reason: ${s.terminationReason ?? 'unknown'} | Iterations: ${s.iteration} | Duration: ${durationStr} | Completed: ${s.completedAt}`)
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.')
@@ -1148,14 +1165,14 @@ Do NOT output text without also making this tool call.
const lines: string[] = [`Active Ralph Loops (${active.length})`, '']
active.forEach((s, i) => {
const elapsed = Math.round((Date.now() - new Date(s.startedAt).getTime()) / 1000)
const elapsed = s.startedAt ? Math.round((Date.now() - new Date(s.startedAt).getTime()) / 1000) : 0
const minutes = Math.floor(elapsed / 60)
const seconds = elapsed % 60
const duration = minutes > 0 ? `${minutes}m ${seconds}s` : `${seconds}s`
const iterInfo = s.maxIterations > 0 ? `${s.iteration} / ${s.maxIterations}` : `${s.iteration} (unlimited)`
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.sessionId)
const stallInfo = ralphHandler.getStallInfo(s.worktreeName)
const stallCount = stallInfo?.consecutiveStalls ?? 0
const stallSuffix = stallCount > 0 ? ` | Stalls: ${stallCount}` : ''
lines.push(`${i + 1}. ${s.worktreeName}${modeIndicator}`)
@@ -1166,17 +1183,22 @@ Do NOT output text without also making this tool call.
if (recent.length > 0) {
lines.push('Recently Completed:')
lines.push('')
recent.forEach((s, i) => {
const duration = s.completedAt
const limitedRecent = recent.slice(0, 10)
limitedRecent.forEach((s, i) => {
const duration = s.completedAt && s.startedAt
? Math.round((new Date(s.completedAt).getTime() - new Date(s.startedAt).getTime()) / 1000)
: 0
const minutes = Math.floor(duration / 60)
const seconds = duration % 60
const durationStr = minutes > 0 ? `${minutes}m ${seconds}s` : `${seconds}s`
lines.push(`${i + 1}. ${s.worktreeName}`)
lines.push(` Reason: ${s.terminationReason ?? 'unknown'} | Iterations: ${s.iteration} | Duration: ${durationStr} | Completed: ${s.completedAt}`)
lines.push(` Reason: ${s.terminationReason ?? 'unknown'} | Iterations: ${s.iteration} | Duration: ${durationStr} | Completed: ${s.completedAt ?? 'unknown'}`)
lines.push('')
})
if (recent.length > 10) {
lines.push(` ... and ${recent.length - 10} more. Use ralph-status <name> for details.`)
lines.push('')
}
}
lines.push('Use ralph-status <name> for detailed info, or ralph-cancel <name> to stop a loop.')
@@ -1193,8 +1215,8 @@ Do NOT output text without also making this tool call.
}
if (!state.active) {
const maxInfo = state.maxIterations > 0 ? `${state.iteration} / ${state.maxIterations}` : `${state.iteration} (unlimited)`
const duration = state.completedAt
const maxInfo = state.maxIterations && state.maxIterations > 0 ? `${state.iteration} / ${state.maxIterations}` : `${state.iteration} (unlimited)`
const duration = state.completedAt && state.startedAt
? Math.round((new Date(state.completedAt).getTime() - new Date(state.startedAt).getTime()) / 1000)
: 0
const minutes = Math.floor(duration / 60)
@@ -1230,7 +1252,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 = await fetchSessionOutput(v2, state.sessionId, state.worktreeDir!, logger)
if (sessionOutput) {
statusLines.push('')
statusLines.push('Session Output:')
@@ -1240,8 +1262,8 @@ Do NOT output text without also making this tool call.
return statusLines.join('\n')
}
const maxInfo = state.maxIterations > 0 ? `${state.iteration} / ${state.maxIterations}` : `${state.iteration} (unlimited)`
const promptPreview = state.prompt.length > 100 ? `${state.prompt.substring(0, 97)}...` : state.prompt
const maxInfo = state.maxIterations && state.maxIterations > 0 ? `${state.iteration} / ${state.maxIterations}` : `${state.iteration} (unlimited)`
const promptPreview = state.prompt && state.prompt.length > 100 ? `${state.prompt.substring(0, 97)}...` : (state.prompt ?? '')
let sessionStatus = 'unknown'
try {
@@ -1257,12 +1279,12 @@ Do NOT output text without also making this tool call.
sessionStatus = 'unavailable'
}
const elapsed = Math.round((Date.now() - new Date(state.startedAt).getTime()) / 1000)
const elapsed = state.startedAt ? Math.round((Date.now() - new Date(state.startedAt).getTime()) / 1000) : 0
const minutes = Math.floor(elapsed / 60)
const seconds = elapsed % 60
const duration = minutes > 0 ? `${minutes}m ${seconds}s` : `${seconds}s`
const stallInfo = ralphHandler.getStallInfo(state.sessionId)
const stallInfo = ralphHandler.getStallInfo(state.worktreeName)
const secondsSinceActivity = stallInfo
? Math.round((Date.now() - stallInfo.lastActivityTime) / 1000)
: null
@@ -1293,7 +1315,7 @@ Do NOT output text without also making this tool call.
statusLines.push(
`Completion promise: ${state.completionPromise ?? 'none'}`,
`Started: ${state.startedAt}`,
...(state.errorCount > 0 ? [`Error count: ${state.errorCount} (retries before termination: ${MAX_RETRIES})`] : []),
...(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'}`,
`Auditor model: ${config.auditorModel || 'default'}`,
@@ -1307,7 +1329,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 = await fetchSessionOutput(v2, state.sessionId, state.worktreeDir!, logger)
if (sessionOutput) {
statusLines.push('')
statusLines.push('Session Output:')
@@ -1339,7 +1361,8 @@ Do NOT output text without also making this tool call.
input: { tool: string; sessionID: string; callID: string },
output: { args: unknown }
) => {
const state = ralphService.getActiveState(input.sessionID)
const worktreeName = ralphService.resolveWorktreeName(input.sessionID)
const state = worktreeName ? ralphService.getActiveState(worktreeName) : null
if (!state?.active) return
if (!(input.tool in RALPH_BLOCKED_TOOLS)) return
@@ -1370,7 +1393,8 @@ Do NOT output text without also making this tool call.
return
}
const state = ralphService.getActiveState(input.sessionID)
const worktreeName = ralphService.resolveWorktreeName(input.sessionID)
const state = worktreeName ? ralphService.getActiveState(worktreeName) : null
if (!state?.active) return
if (!(input.tool in RALPH_BLOCKED_TOOLS)) return
@@ -1382,7 +1406,8 @@ Do NOT output text without also making this tool call.
},
'permission.ask': async (input, output) => {
const req = input as unknown as { sessionID: string; patterns: string[] }
const state = ralphService.getActiveState(req.sessionID)
const worktreeName = ralphService.resolveWorktreeName(req.sessionID)
const state = worktreeName ? ralphService.getActiveState(worktreeName) : null
if (!state?.active) return
if (req.patterns.some((p) => p.startsWith('git push'))) {
+3 -3
View File
@@ -2,7 +2,7 @@ import type { Database } from 'bun:sqlite'
import { createKvQuery } from '../storage/kv-queries'
import type { Logger } from '../types'
const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000
const DEFAULT_TTL_MS = 7 * 24 * 60 * 60 * 1000
export interface KvEntry {
key: string
@@ -19,7 +19,7 @@ export interface KvService {
listByPrefix(projectId: string, prefix: string): KvEntry[]
}
export function createKvService(db: Database, logger?: Logger): KvService {
export function createKvService(db: Database, logger?: Logger, defaultTtlMs?: number): KvService {
const queries = createKvQuery(db)
return {
@@ -34,7 +34,7 @@ export function createKvService(db: Database, logger?: Logger): KvService {
},
set<T = unknown>(projectId: string, key: string, data: T, ttlMs?: number): void {
const expiresAt = Date.now() + (ttlMs ?? DEFAULT_TTL_MS)
const expiresAt = Date.now() + (ttlMs ?? defaultTtlMs ?? DEFAULT_TTL_MS)
const jsonData = JSON.stringify(data)
queries.set(projectId, key, jsonData, expiresAt)
},
+40 -22
View File
@@ -12,20 +12,20 @@ export const RECENT_MESSAGES_COUNT = 5
export interface RalphState {
active: boolean
sessionId: string
worktreeName?: string
worktreeDir?: string
worktreeName: string
worktreeDir: string
worktreeBranch?: string
workspaceId?: string
iteration?: number
maxIterations?: number
iteration: number
maxIterations: number
completionPromise: string | null
startedAt?: string
startedAt: string
prompt?: string
phase?: 'coding' | 'auditing'
phase: 'coding' | 'auditing'
audit?: boolean
lastAuditResult?: string
errorCount?: number
auditCount?: number
errorCount: number
auditCount: number
terminationReason?: string
completedAt?: string
inPlace?: boolean
@@ -33,10 +33,13 @@ export interface RalphState {
}
export interface RalphService {
getActiveState(sessionId: string): RalphState | null
getAnyState(sessionId: string): RalphState | null
setState(sessionId: string, state: RalphState): void
deleteState(sessionId: string): void
getActiveState(name: string): RalphState | null
getAnyState(name: string): RalphState | null
setState(name: string, state: RalphState): 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
@@ -55,26 +58,38 @@ export function createRalphService(
logger: Logger,
ralphConfig?: RalphConfig,
): RalphService {
const stateKey = (sessionId: string) => `ralph:${sessionId}`
const stateKey = (name: string) => `ralph:${name}`
function getAnyState(sessionId: string): RalphState | null {
return kvService.get<RalphState>(projectId, stateKey(sessionId))
function getAnyState(name: string): RalphState | null {
return kvService.get<RalphState>(projectId, stateKey(name))
}
function getActiveState(sessionId: string): RalphState | null {
const state = kvService.get<RalphState>(projectId, stateKey(sessionId))
function getActiveState(name: string): RalphState | null {
const state = kvService.get<RalphState>(projectId, stateKey(name))
if (!state || !state.active) {
return null
}
return state
}
function setState(sessionId: string, state: RalphState): void {
kvService.set(projectId, stateKey(sessionId), state)
function setState(name: string, state: RalphState): void {
kvService.set(projectId, stateKey(name), state)
}
function deleteState(sessionId: string): void {
kvService.delete(projectId, stateKey(sessionId))
function deleteState(name: string): void {
kvService.delete(projectId, stateKey(name))
}
function registerSession(sessionId: string, worktreeName: string): void {
kvService.set(projectId, `ralph-session:${sessionId}`, worktreeName)
}
function resolveWorktreeName(sessionId: string): string | null {
return kvService.get<string>(projectId, `ralph-session:${sessionId}`)
}
function unregisterSession(sessionId: string): void {
kvService.delete(projectId, `ralph-session:${sessionId}`)
}
function checkCompletionPromise(text: string, promise: string): boolean {
@@ -177,7 +192,7 @@ export function createRalphService(
completedAt: new Date().toISOString(),
terminationReason: 'shutdown',
}
setState(state.sessionId, updated)
setState(state.worktreeName, updated)
}
logger.log(`Ralph: terminated ${active.length} active loop(s)`)
}
@@ -187,6 +202,9 @@ export function createRalphService(
getAnyState,
setState,
deleteState,
registerSession,
resolveWorktreeName,
unregisterSession,
checkCompletionPromise,
buildContinuationPrompt,
buildAuditPrompt,
+1
View File
@@ -80,6 +80,7 @@ export interface PluginConfig {
executionModel?: string
auditorModel?: string
ralph?: RalphConfig
defaultKvTtlMs?: number
}
export interface ListMemoriesFilter {
+1 -1
View File
@@ -1 +1 @@
export const VERSION = '0.0.24'
export const VERSION = '0.0.25'
+52 -39
View File
@@ -657,7 +657,7 @@ describe('Stall Detection', () => {
const mockGetConfig = () => ({ ralph: {}, executionModel: undefined, auditorModel: undefined })
const handler = createRalphEventHandler(ralphService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const info = handler.getStallInfo('test-session')
const info = handler.getStallInfo('test')
expect(info).toBeNull()
})
@@ -695,10 +695,11 @@ describe('Stall Detection', () => {
const handler = createRalphEventHandler(ralphService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const sessionId = 'test-session'
ralphService.setState(sessionId, {
const worktreeName = 'test'
ralphService.setState(worktreeName, {
active: true,
sessionId,
worktreeName: 'test',
worktreeName,
worktreeDir: '/tmp/test',
worktreeBranch: 'main',
workspaceId: '',
@@ -713,9 +714,9 @@ describe('Stall Detection', () => {
auditCount: 0,
})
handler.startWatchdog(sessionId)
handler.startWatchdog(worktreeName)
const info = handler.getStallInfo(sessionId)
const info = handler.getStallInfo(worktreeName)
expect(info).not.toBeNull()
expect(info?.consecutiveStalls).toBe(0)
expect(info?.lastActivityTime).toBeDefined()
@@ -757,8 +758,9 @@ describe('Stall Detection', () => {
const parentId = 'parent-session'
const childId = 'child-session'
const worktreeName = 'test'
ralphService.setState(parentId, {
ralphService.setState(worktreeName, {
active: true,
sessionId: parentId,
worktreeName: 'test',
@@ -776,8 +778,8 @@ describe('Stall Detection', () => {
auditCount: 0,
})
handler.startWatchdog(parentId)
const initialInfo = handler.getStallInfo(parentId)
handler.startWatchdog(worktreeName)
const initialInfo = handler.getStallInfo(worktreeName)
const initialTime = initialInfo?.lastActivityTime
await handler.onEvent({
@@ -792,7 +794,7 @@ describe('Stall Detection', () => {
},
})
const updatedInfo = handler.getStallInfo(parentId)
const updatedInfo = handler.getStallInfo(worktreeName)
expect(updatedInfo?.lastActivityTime).toBeGreaterThanOrEqual(initialTime!)
})
@@ -830,7 +832,8 @@ describe('Stall Detection', () => {
const handler = createRalphEventHandler(ralphService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const sessionId = 'test-session'
ralphService.setState(sessionId, {
const worktreeName = 'test'
ralphService.setState(worktreeName, {
active: true,
sessionId,
worktreeName: 'test',
@@ -848,8 +851,8 @@ describe('Stall Detection', () => {
auditCount: 0,
})
handler.startWatchdog(sessionId)
const initialInfo = handler.getStallInfo(sessionId)
handler.startWatchdog(worktreeName)
const initialInfo = handler.getStallInfo(worktreeName)
const initialTime = initialInfo?.lastActivityTime
await new Promise(resolve => setTimeout(resolve, 10))
@@ -863,7 +866,7 @@ describe('Stall Detection', () => {
},
})
const updatedInfo = handler.getStallInfo(sessionId)
const updatedInfo = handler.getStallInfo(worktreeName)
expect(updatedInfo?.lastActivityTime).toBeGreaterThanOrEqual(initialTime!)
})
@@ -901,7 +904,8 @@ describe('Stall Detection', () => {
const handler = createRalphEventHandler(ralphService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const sessionId = 'test-session'
ralphService.setState(sessionId, {
const worktreeName = 'test'
ralphService.setState(worktreeName, {
active: true,
sessionId,
worktreeName: 'test',
@@ -919,11 +923,11 @@ describe('Stall Detection', () => {
auditCount: 0,
})
handler.startWatchdog(sessionId)
expect(handler.getStallInfo(sessionId)).not.toBeNull()
handler.startWatchdog(worktreeName)
expect(handler.getStallInfo(worktreeName)).not.toBeNull()
handler.clearAllRetryTimeouts()
expect(handler.getStallInfo(sessionId)).toBeNull()
expect(handler.getStallInfo(worktreeName)).toBeNull()
})
})
@@ -1003,7 +1007,8 @@ describe('session rotation', () => {
auditCount: 0,
}
ralphService.setState(oldSessionId, state)
ralphService.setState('test-worktree', state)
ralphService.registerSession(oldSessionId, 'test-worktree')
await handler.onEvent({
event: {
@@ -1012,10 +1017,11 @@ describe('session rotation', () => {
},
})
const oldState = ralphService.getActiveState(oldSessionId)
expect(oldState).toBeNull()
const oldState = ralphService.getActiveState('test-worktree')
expect(oldState).not.toBeNull()
expect(oldState?.sessionId).toBe(newSessionId)
const newState = ralphService.getActiveState(newSessionId)
const newState = ralphService.getActiveState('test-worktree')
expect(newState).not.toBeNull()
expect(newState?.iteration).toBe(2)
expect(newState?.sessionId).toBe(newSessionId)
@@ -1086,7 +1092,8 @@ describe('session rotation', () => {
auditCount: 0,
}
ralphService.setState(oldSessionId, state)
ralphService.setState('test-worktree', state)
ralphService.registerSession(oldSessionId, 'test-worktree')
await handler.onEvent({
event: {
@@ -1095,7 +1102,7 @@ describe('session rotation', () => {
},
})
const newState = ralphService.getActiveState(newSessionId)
const newState = ralphService.getActiveState('test-worktree')
expect(newState).not.toBeNull()
expect(newState?.phase).toBe('coding')
expect(newState?.iteration).toBe(2)
@@ -1152,7 +1159,8 @@ describe('session rotation', () => {
auditCount: 0,
}
ralphService.setState(sessionId, state)
ralphService.setState('test-worktree', state)
ralphService.registerSession(sessionId, 'test-worktree')
await handler.onEvent({
event: {
@@ -1161,7 +1169,7 @@ describe('session rotation', () => {
},
})
const existingState = ralphService.getActiveState(sessionId)
const existingState = ralphService.getActiveState('test-worktree')
expect(existingState).not.toBeNull()
expect(existingState?.iteration).toBe(2)
expect(existingState?.sessionId).toBe(sessionId)
@@ -1244,7 +1252,8 @@ describe('Assistant Error Detection', () => {
auditCount: 0,
}
ralphService.setState(sessionId, state)
ralphService.setState('test-worktree', state)
ralphService.registerSession(sessionId, 'test-worktree')
await handler.onEvent({
event: {
@@ -1253,7 +1262,7 @@ describe('Assistant Error Detection', () => {
},
})
const updatedState = ralphService.getActiveState(sessionId)
const updatedState = ralphService.getActiveState('test-worktree')
expect(updatedState?.errorCount).toBe(1)
expect(updatedState?.modelFailed).toBe(true)
})
@@ -1318,7 +1327,8 @@ describe('Assistant Error Detection', () => {
auditCount: 0,
}
ralphService.setState(sessionId, state)
ralphService.setState('test-worktree', state)
ralphService.registerSession(sessionId, 'test-worktree')
await handler.onEvent({
event: {
@@ -1327,7 +1337,7 @@ describe('Assistant Error Detection', () => {
},
})
const updatedState = ralphService.getActiveState(sessionId)
const updatedState = ralphService.getActiveState('test-worktree')
expect(updatedState?.errorCount).toBe(1)
expect(updatedState?.modelFailed).toBe(true)
})
@@ -1382,7 +1392,8 @@ describe('Assistant Error Detection', () => {
auditCount: 0,
}
ralphService.setState(sessionId, state)
ralphService.setState('test-worktree', state)
ralphService.registerSession(sessionId, 'test-worktree')
await handler.onEvent({
event: {
@@ -1397,7 +1408,7 @@ describe('Assistant Error Detection', () => {
},
})
const updatedState = ralphService.getActiveState(sessionId)
const updatedState = ralphService.getActiveState('test-worktree')
expect(updatedState?.modelFailed).toBe(true)
})
@@ -1451,7 +1462,8 @@ describe('Assistant Error Detection', () => {
auditCount: 0,
}
ralphService.setState(sessionId, state)
ralphService.setState('test-worktree', state)
ralphService.registerSession(sessionId, 'test-worktree')
await handler.onEvent({
event: {
@@ -1465,7 +1477,7 @@ describe('Assistant Error Detection', () => {
},
})
const updatedState = ralphService.getActiveState(sessionId)
const updatedState = ralphService.getActiveState('test-worktree')
expect(updatedState).toBeNull()
})
@@ -1529,7 +1541,7 @@ describe('Assistant Error Detection', () => {
modelFailed: true,
}
ralphService.setState(sessionId, state)
ralphService.setState('test-worktree', state)
await handler.onEvent({
event: {
@@ -1601,7 +1613,8 @@ describe('Assistant Error Detection', () => {
auditCount: 0,
}
ralphService.setState(sessionId, state)
ralphService.setState('test-worktree', state)
ralphService.registerSession(sessionId, 'test-worktree')
await handler.onEvent({
event: {
@@ -1610,7 +1623,7 @@ describe('Assistant Error Detection', () => {
},
})
let stateAfterSecondError = ralphService.getActiveState(sessionId)
let stateAfterSecondError = ralphService.getActiveState('test-worktree')
expect(stateAfterSecondError?.errorCount).toBe(1)
await handler.onEvent({
@@ -1620,7 +1633,7 @@ describe('Assistant Error Detection', () => {
},
})
let stateAfterThirdError = ralphService.getActiveState(sessionId)
let stateAfterThirdError = ralphService.getActiveState('test-worktree')
expect(stateAfterThirdError?.errorCount).toBe(2)
await handler.onEvent({
@@ -1630,10 +1643,10 @@ describe('Assistant Error Detection', () => {
},
})
const finalState = ralphService.getActiveState(sessionId)
const finalState = ralphService.getActiveState('test-worktree')
expect(finalState).toBeNull()
const terminatedState = ralphService.getAnyState(sessionId)
const terminatedState = ralphService.getAnyState('test-worktree')
expect(terminatedState?.active).toBe(false)
expect(terminatedState?.terminationReason).toContain('error_max_retries')
})
+8 -8
View File
@@ -143,20 +143,20 @@ export type UpdateKvEntryRequest = z.infer<typeof UpdateKvEntryRequestSchema>
export const RalphStateSchema = z.object({
active: z.boolean(),
sessionId: z.string(),
worktreeName: z.string().optional(),
worktreeDir: z.string().optional(),
worktreeName: z.string(),
worktreeDir: z.string(),
worktreeBranch: z.string().optional(),
workspaceId: z.string().optional(),
iteration: z.number().optional(),
maxIterations: z.number().optional(),
iteration: z.number(),
maxIterations: z.number(),
completionPromise: z.string().nullable().optional(),
startedAt: z.string().optional(),
startedAt: z.string(),
prompt: z.string().optional(),
phase: z.enum(['coding', 'auditing']).optional(),
phase: z.enum(['coding', 'auditing']),
audit: z.boolean().optional(),
lastAuditResult: z.string().optional(),
errorCount: z.number().optional(),
auditCount: z.number().optional(),
errorCount: z.number(),
auditCount: z.number(),
terminationReason: z.string().optional(),
completedAt: z.string().optional(),
inPlace: z.boolean().optional(),