diff --git a/packages/memory/package.json b/packages/memory/package.json index 867e7802..bf3e87e7 100644 --- a/packages/memory/package.json +++ b/packages/memory/package.json @@ -1,6 +1,6 @@ { "name": "@opencode-manager/memory", - "version": "0.0.22", + "version": "0.0.23", "type": "module", "main": "./dist/index.js", "types": "./dist/index.d.ts", diff --git a/packages/memory/src/agents/auditor.ts b/packages/memory/src/agents/auditor.ts index 1c3f2c0e..7207e133 100644 --- a/packages/memory/src/agents/auditor.ts +++ b/packages/memory/src/agents/auditor.ts @@ -109,6 +109,15 @@ If only suggestions were found or no issues at all: If no issues are found, say so clearly and briefly. +## Verification + +Before finalizing your review, run the project's type check to catch type errors the diff review may miss. + +1. Determine the type check command — look at package.json scripts, Makefile, pyproject.toml, or other build config for a typecheck/type-check/check-types target. If none exists, look for a tsconfig.json and run \`tsc --noEmit\`, or skip if the project has no static type checking. +2. Run the type check command. +3. If there are type errors in files touched by the diff, report each as a **bug** severity finding with the file path and error message. +4. If type errors exist only in files NOT touched by the diff, mention them under **Observations** but do not block the review. + ## Constraints You are read-only on source code. Do not edit files, run destructive commands, or make any changes. Only read, search, analyze, and report findings. diff --git a/packages/memory/src/index.ts b/packages/memory/src/index.ts index 40197ec8..7cbb6752 100644 --- a/packages/memory/src/index.ts +++ b/packages/memory/src/index.ts @@ -13,11 +13,14 @@ 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 } from './services/ralph' +import { createRalphService, type RalphState, fetchSessionOutput, type RalphSessionOutput } from './services/ralph' +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 type { Database } from 'bun:sqlite' import type { PluginConfig, CompactionConfig, HealthStatus, Logger } from './types' import type { EmbeddingProvider } from './embedding' @@ -420,7 +423,7 @@ export function createMemoryPlugin(config: PluginConfig): Plugin { interface LoopContext { sessionId: string directory: string - branch: string + branch?: string workspaceId?: string inPlace: boolean } @@ -428,12 +431,11 @@ export function createMemoryPlugin(config: PluginConfig): Plugin { let loopContext: LoopContext if (options.inPlace) { - let currentBranch: string + let currentBranch: string | undefined try { currentBranch = execSync('git rev-parse --abbrev-ref HEAD', { cwd: projectDir, encoding: 'utf-8' }).trim() } catch (err) { - logger.error(`ralph: failed to get current branch`, err) - return 'Failed to determine current git branch.' + logger.log(`ralph: no git branch detected, running without branch info`) } const createResult = await v2.session.create({ @@ -564,7 +566,9 @@ export function createMemoryPlugin(config: PluginConfig): Plugin { if (options.inPlace) { lines.push(`Directory: ${loopContext.directory}`) - lines.push(`Branch: ${loopContext.branch} (in-place)`) + if (loopContext.branch) { + lines.push(`Branch: ${loopContext.branch} (in-place)`) + } } else { lines.push(`Workspace: ${loopContext.workspaceId}`) lines.push(`Worktree name: ${autoWorktreeName}`) @@ -942,9 +946,22 @@ Do NOT output text without also making this tool call. let state: RalphState | null = null if (args.name) { - state = ralphService.findByWorktreeName(args.name) + const name = args.name + state = ralphService.findByWorktreeName(name) if (!state) { - return `No active Ralph loop found for worktree "${args.name}".` + const candidates = ralphService.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 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 `No active Ralph loop found for worktree "${name}".` + } + if (!state.active) { + return `Ralph loop "${state.worktreeName}" has already completed.` } } else { const active = ralphService.listActive() @@ -974,7 +991,8 @@ Do NOT output text without also making this tool call. } const modeInfo = state.inPlace ? ' (in-place)' : '' - return `Cancelled Ralph loop "${state.worktreeName}"${modeInfo} (was at iteration ${state.iteration}).\nDirectory: ${state.worktreeDir}\nBranch: ${state.worktreeBranch}` + const branchInfo = state.worktreeBranch ? `\nBranch: ${state.worktreeBranch}` : '' + return `Cancelled Ralph loop "${state.worktreeName}"${modeInfo} (was at iteration ${state.iteration}).\nDirectory: ${state.worktreeDir}${branchInfo}` }, }), 'ralph-status': tool({ @@ -992,7 +1010,11 @@ Do NOT output text without also making this tool call. } const recent = ralphService.listRecent() - const stoppedState = [...active, ...recent].find((s) => s.worktreeName === args.name) + const allStates = [...active, ...recent] + const { match: stoppedState, candidates } = findPartialMatch(args.name, allStates, (s) => [s.worktreeName, s.worktreeBranch]) + if (!stoppedState && candidates.length > 0) { + return `Multiple loops match "${args.name}":\n${candidates.map((s) => `- ${s.worktreeName}`).join('\n')}\n\nBe more specific.` + } 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}` @@ -1081,14 +1103,14 @@ Do NOT output text without also making this tool call. ralphHandler.startWatchdog(newSessionId) const modeInfo = stoppedState.inPlace ? ' (in-place)' : '' + const branchInfo = stoppedState.worktreeBranch ? `\nBranch: ${stoppedState.worktreeBranch}` : '' return [ `Restarted Ralph loop "${stoppedState.worktreeName}"${modeInfo}`, '', `New session: ${newSessionId}`, `Continuing from iteration: ${stoppedState.iteration}`, `Previous termination: ${stoppedState.terminationReason}`, - `Directory: ${stoppedState.worktreeDir}`, - `Branch: ${stoppedState.worktreeBranch}`, + `Directory: ${stoppedState.worktreeDir}${branchInfo}`, `Audit: ${stoppedState.audit ? 'enabled' : 'disabled'}`, ].join('\n') } @@ -1161,42 +1183,61 @@ Do NOT output text without also making this tool call. const state = ralphService.findByWorktreeName(args.name) if (!state) { - const recent = ralphService.listRecent() - const foundRecent = recent.find((s) => s.worktreeName === args.name) - if (foundRecent) { - const maxInfo = foundRecent.maxIterations > 0 ? `${foundRecent.iteration} / ${foundRecent.maxIterations}` : `${foundRecent.iteration} (unlimited)` - const duration = foundRecent.completedAt - ? Math.round((new Date(foundRecent.completedAt).getTime() - new Date(foundRecent.startedAt).getTime()) / 1000) - : 0 - const minutes = Math.floor(duration / 60) - const seconds = duration % 60 - const durationStr = minutes > 0 ? `${minutes}m ${seconds}s` : `${seconds}s` - - const completedLines: string[] = [ - 'Ralph Loop Status (Completed)', - '', - `Name: ${foundRecent.worktreeName}`, - `Session: ${foundRecent.sessionId}`, - ] - if (foundRecent.inPlace) { - completedLines.push(`Mode: in-place (completed) | Directory: ${foundRecent.worktreeDir}`) - } else { - completedLines.push(`Workspace: ${foundRecent.workspaceId}`) - completedLines.push(`Worktree: ${foundRecent.worktreeDir}`) - } - completedLines.push( - `Iteration: ${maxInfo}`, - `Duration: ${durationStr}`, - `Reason: ${foundRecent.terminationReason ?? 'unknown'}`, - `Branch: ${foundRecent.worktreeBranch}`, - `Started: ${foundRecent.startedAt}`, - `Completed: ${foundRecent.completedAt}`, - ) - return completedLines.join('\n') + const candidates = ralphService.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.` } return `No Ralph loop found for worktree "${args.name}".` } + if (!state.active) { + const maxInfo = state.maxIterations > 0 ? `${state.iteration} / ${state.maxIterations}` : `${state.iteration} (unlimited)` + const duration = state.completedAt + ? Math.round((new Date(state.completedAt).getTime() - new Date(state.startedAt).getTime()) / 1000) + : 0 + const minutes = Math.floor(duration / 60) + const seconds = duration % 60 + const durationStr = minutes > 0 ? `${minutes}m ${seconds}s` : `${seconds}s` + + const statusLines: string[] = [ + 'Ralph Loop Status (Inactive)', + '', + `Name: ${state.worktreeName}`, + `Session: ${state.sessionId}`, + ] + if (state.inPlace) { + statusLines.push(`Mode: in-place | Directory: ${state.worktreeDir}`) + } else { + statusLines.push(`Workspace: ${state.workspaceId}`) + statusLines.push(`Worktree: ${state.worktreeDir}`) + } + statusLines.push( + `Iteration: ${maxInfo}`, + `Duration: ${durationStr}`, + `Reason: ${state.terminationReason ?? 'unknown'}`, + ) + if (state.worktreeBranch) { + statusLines.push(`Branch: ${state.worktreeBranch}`) + } + statusLines.push( + `Started: ${state.startedAt}`, + ...(state.completedAt ? [`Completed: ${state.completedAt}`] : []), + ) + + if (state.lastAuditResult) { + statusLines.push(...formatAuditResult(state.lastAuditResult)) + } + + const sessionOutput = await fetchSessionOutput(v2, state.sessionId, state.worktreeDir, logger) + if (sessionOutput) { + statusLines.push('') + statusLines.push('Session Output:') + statusLines.push(...formatSessionOutput(sessionOutput)) + } + + 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 @@ -1243,7 +1284,11 @@ Do NOT output text without also making this tool call. `Iteration: ${maxInfo}`, `Duration: ${duration}`, `Audit: ${state.audit ? 'enabled' : 'disabled'}`, - `Branch: ${state.worktreeBranch}`, + ) + if (state.worktreeBranch) { + statusLines.push(`Branch: ${state.worktreeBranch}`) + } + statusLines.push( `Completion promise: ${state.completionPromise ?? 'none'}`, `Started: ${state.startedAt}`, ...(state.errorCount > 0 ? [`Error count: ${state.errorCount} (retries before termination: ${MAX_RETRIES})`] : []), @@ -1255,6 +1300,18 @@ Do NOT output text without also making this tool call. '', `Prompt: ${promptPreview}`, ) + + if (state.lastAuditResult) { + statusLines.push(...formatAuditResult(state.lastAuditResult)) + } + + const sessionOutput = await fetchSessionOutput(v2, state.sessionId, state.worktreeDir, logger) + if (sessionOutput) { + statusLines.push('') + statusLines.push('Session Output:') + statusLines.push(...formatSessionOutput(sessionOutput)) + } + return statusLines.join('\n') }, }), diff --git a/packages/memory/src/services/ralph.ts b/packages/memory/src/services/ralph.ts index b3e27d6a..86821ee9 100644 --- a/packages/memory/src/services/ralph.ts +++ b/packages/memory/src/services/ralph.ts @@ -1,17 +1,20 @@ import type { KvService } from './kv' import type { Logger, RalphConfig } from '../types' +import type { OpencodeClient } from '@opencode-ai/sdk/v2' +import { findPartialMatch } from '../utils/partial-match' 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 { active: boolean sessionId: string worktreeName: string worktreeDir: string - worktreeBranch: string + worktreeBranch?: string workspaceId: string iteration: number maxIterations: number @@ -39,6 +42,7 @@ export interface RalphService { listActive(): RalphState[] listRecent(): RalphState[] findByWorktreeName(name: string): RalphState | null + findCandidatesByPartialName(name: string): RalphState[] getStallTimeoutMs(): number getMinAudits(): number terminateAll(): void @@ -109,8 +113,9 @@ export function createRalphService( ? `${state.prompt.substring(0, 197)}...` : state.prompt + const branchInfo = state.worktreeBranch ? ` (branch: ${state.worktreeBranch})` : '' return [ - `Post-iteration ${state.iteration} code review (branch: ${state.worktreeBranch}).`, + `Post-iteration ${state.iteration} code review${branchInfo}.`, '', `Task context: ${taskSummary}`, '', @@ -138,7 +143,20 @@ export function createRalphService( function findByWorktreeName(name: string): RalphState | null { const active = listActive() - return active.find((s) => s.worktreeName === name) ?? null + const recent = listRecent() + const allStates = [...active, ...recent] + + const { match } = findPartialMatch(name, allStates, (s) => [s.worktreeName, s.worktreeBranch]) + return match + } + + function findCandidatesByPartialName(name: string): RalphState[] { + const active = listActive() + const recent = listRecent() + const allStates = [...active, ...recent] + + const { candidates } = findPartialMatch(name, allStates, (s) => [s.worktreeName, s.worktreeBranch]) + return candidates } function getStallTimeoutMs(): number { @@ -174,8 +192,105 @@ export function createRalphService( listActive, listRecent, findByWorktreeName, + findCandidatesByPartialName, getStallTimeoutMs, getMinAudits, terminateAll, } } + +export interface RalphSessionOutput { + 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 } + fileChanges: { additions: number; deletions: number; files: number } | null +} + +export async function fetchSessionOutput( + v2Client: OpencodeClient, + sessionId: string, + directory: string, + logger?: Logger, +): Promise { + try { + const messagesResult = await v2Client.session.messages({ + sessionID: sessionId, + directory, + }) + + const messages = (messagesResult.data ?? []) as Array<{ + info: { role: string; cost?: number; tokens?: { input: number; output: number; reasoning: number; cache: { read: number; write: number } } } + parts: Array<{ type: string; text?: string }> + }> + + const assistantMessages = messages.filter((m) => m.info.role === 'assistant') + const lastThree = assistantMessages.slice(-RECENT_MESSAGES_COUNT) + + const extractedMessages = lastThree.map((msg) => { + const text = msg.parts + .filter((p) => p.type === 'text' && typeof p.text === 'string') + .map((p) => p.text as string) + .join('\n') + const cost = msg.info.cost ?? 0 + const tokens = msg.info.tokens ?? { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } } + return { + text, + cost, + tokens: { + input: tokens.input, + output: tokens.output, + reasoning: tokens.reasoning, + cacheRead: tokens.cache?.read ?? 0, + cacheWrite: tokens.cache?.write ?? 0, + }, + } + }) + + let totalCost = 0 + let totalInputTokens = 0 + let totalOutputTokens = 0 + let totalReasoningTokens = 0 + let totalCacheRead = 0 + let totalCacheWrite = 0 + + for (const msg of assistantMessages) { + totalCost += msg.info.cost ?? 0 + const tokens = msg.info.tokens + if (tokens) { + totalInputTokens += tokens.input ?? 0 + totalOutputTokens += tokens.output ?? 0 + totalReasoningTokens += tokens.reasoning ?? 0 + totalCacheRead += tokens.cache?.read ?? 0 + totalCacheWrite += tokens.cache?.write ?? 0 + } + } + + const sessionResult = await v2Client.session.get({ sessionID: sessionId, directory }) + const session = sessionResult.data as { summary?: { additions: number; deletions: number; files: number } } | undefined + const fileChanges = session?.summary + ? { + additions: session.summary.additions, + deletions: session.summary.deletions, + files: session.summary.files, + } + : null + + return { + messages: extractedMessages, + totalCost, + totalTokens: { + input: totalInputTokens, + output: totalOutputTokens, + reasoning: totalReasoningTokens, + cacheRead: totalCacheRead, + cacheWrite: totalCacheWrite, + }, + fileChanges, + } + } catch (err) { + if (logger) { + logger.error(`Ralph: could not fetch session output for ${sessionId}`, err) + } + return null + } +} diff --git a/packages/memory/src/version.ts b/packages/memory/src/version.ts index 8b2d8c13..21926c8d 100644 --- a/packages/memory/src/version.ts +++ b/packages/memory/src/version.ts @@ -1 +1 @@ -export const VERSION = '0.0.22' +export const VERSION = '0.0.23'