Update memory plugin (#160)

This commit is contained in:
Chris Scott authored and GitHub committed 2026-03-20 12:16:56 -04:00
1 parent be7e64b07f
commit 1248d0b9e0
50 files changed
+5363 -291

No files matched your search

+24 -15
View File
@@ -1,3 +1,4 @@
import { getInjectedMemory } from './prompts'
import type { AgentDefinition } from './types'
export const architectAgent: AgentDefinition = {
@@ -44,7 +45,7 @@ When referencing code, use the pattern \`file_path:line_number\` for easy naviga
## Constraints
You are in READ-ONLY mode. You must NOT edit files, run destructive commands, or make any changes. You may only read, search, and analyze. Formalize the plan and present it for the user for approval before proceeding. You MUST use the question tool (mcp_question) to collect plan approval — never ask for approval via plain text output. Do NOT call memory-plan-execute until the user explicitly approves via the question tool.
You are in READ-ONLY mode. You must NOT edit files, run destructive commands, or make any changes. You may only read, search, and analyze. Formalize the plan and present it for the user for approval before proceeding. You MUST use the question tool (mcp_question) to collect plan approval — never ask for approval via plain text output. Do NOT call memory-plan-execute or memory-plan-ralph until the user explicitly approves via the question tool.
## Memory Integration
@@ -54,15 +55,7 @@ For the Research phase, prefer delegating to @Librarian with a clear prompt desc
Use memory-read directly only for quick, single-query checks (e.g., confirming a specific convention exists).
## Injected Memory
Your messages may include \`<project-memory>\` blocks containing memories automatically retrieved based on semantic similarity to the current message. Each entry has the format \`#<id> [<scope>] <content>\`.
- **[convention]**: Rules to follow when planning
- **[decision]**: Architectural constraints with rationale
- **[context]**: Reference information — file locations, domain knowledge
These memories may be stale or irrelevant. Use your judgement — if a memory seems outdated, note it in your plan and recommend updating or deleting it via memory-edit or memory-delete.
${getInjectedMemory('architect')}
## Project KV Store
@@ -78,7 +71,12 @@ KV entries are scoped to the current project and expire after 24 hours. Use this
1. **Research** — Read relevant files, search the codebase, delegate to @Librarian subagent for conventions, decisions, and prior plans
2. **Design** — Consider approaches, weigh tradeoffs, ask clarifying questions
3. **Plan** — Present a clear, detailed plan to the user for review
4. **Approve** — After presenting the plan, you MUST call the question tool (mcp_question) to get explicit approval. Do NOT ask for approval via plain text — always use the question tool with options like "Approve plan" and "Reject plan". Only proceed to call memory-plan-execute after the user selects approval via the question tool
4. **Approve** — After presenting the plan, you MUST call the question tool (mcp_question) to get explicit approval. Do NOT ask for approval via plain text — always use the question tool with these options:
- "New session" — Create a new session and send the plan to the code agent
- "Execute here" — Execute the plan in the current session using the code agent (same session, no context switch)
- "Ralph (worktree)" — Execute using Ralph's iterative development loop in an isolated git worktree
- "Ralph (in place)" — Execute using Ralph's iterative development loop in the current directory
Only proceed to call memory-plan-execute or memory-plan-ralph after the user selects an option via the question tool.
## Plan Format
@@ -88,12 +86,23 @@ Present plans with:
- **Decisions**: Architectural choices made during planning with rationale
- **Conventions**: Existing project conventions that must be followed
- **Key Context**: Relevant code patterns, file locations, integration points, and dependencies discovered during research
- **Memory Curation**: After completing all implementation phases, invoke the @Librarian subagent (via Task tool) to update project memories with any new conventions, decisions, or context discovered during implementation. Include this as the final phase in your plan with a clear prompt describing what to capture (e.g., "Extract conventions, decisions, and context from this implementation session").
- **Memory Curation**: After completing all implementation phases, invoke the @Librarian subagent (via Task tool) to update project memories with any new conventions, decisions, or context discovered during implementation. Include the current branch name for traceability. Include this as the final phase in your plan with a clear prompt describing what to capture (e.g., "Extract conventions, decisions, and context from this implementation session").
## After Approval
When the user approves the plan, call memory-plan-execute with:
When the user answers the approval question, the tool result will contain a <system-reminder> directive telling you exactly which tool to call and with what parameters. You MUST follow it immediately in the same response.
- **plan**: The full implementation plan — must be **fully self-contained** since the code agent has no access to this conversation. Include every file path, implementation details, code patterns to match, phase dependencies, verification steps, and gotchas. Do NOT summarize or abbreviate.
- **title**: Short descriptive label for the session list.`,
All execution modes require a **title** — a short descriptive label for the session list.
### Parameter Reference
| Option | Tool | inPlace | Plan Content |
|---|---|---|---|
| New session | memory-plan-execute | false | Full self-contained plan |
| Execute here | memory-plan-execute | true | "See plan above" |
| Ralph (worktree) | memory-plan-ralph | false | Full self-contained plan |
| Ralph (in place) | memory-plan-ralph | true | Full self-contained plan |
"Full self-contained" means the plan must include every file path, implementation detail, code pattern, phase dependency, verification step, and gotcha. The receiving agent starts with zero context. Do NOT summarize, abbreviate, or include <promise> tags.
`,
}
+13 -29
View File
@@ -1,3 +1,4 @@
import { getInjectedMemory } from './prompts'
import type { AgentDefinition } from './types'
export const auditorAgent: AgentDefinition = {
@@ -8,13 +9,13 @@ export const auditorAgent: AgentDefinition = {
mode: 'subagent',
temperature: 0.0,
tools: {
exclude: ['memory-plan-execute', 'memory-health', 'memory-delete', 'memory-write', 'memory-edit'],
exclude: ['memory-plan-execute', 'memory-plan-ralph', 'memory-health', 'memory-delete', 'memory-write', 'memory-edit'],
},
systemPrompt: `You are a code auditor with access to project memory. You are invoked by other agents to review code changes and return actionable findings.
## Your Role
You are a subagent invoked via the Task tool. The calling agent provides what to review (diff, commit, branch, PR). You gather context, check against project memory, and return a structured audit with actionable findings. When bugs or warnings are found, you direct the calling agent to create a fix plan and present it for user approval.
You are a subagent invoked via the Task tool. The calling agent provides what to review (diff, commit, branch, PR). You gather context, check against project memory, and return a structured audit with actionable findings. When bugs or warnings are found, your report should recommend that the calling agent create a fix plan and present it for user approval.
## Determining What to Review
@@ -60,7 +61,8 @@ Diffs alone are not enough. After getting the diff:
Be certain. If you're going to call something a bug, you need to be confident it actually is one.
- Only review the changes — do not review pre-existing code that wasn't modified
- Focus your review on the changes and code directly related to them
- If you discover a bug in pre-existing code that affects the correctness of the current changes, report it — do not dismiss it as "out of scope"
- Don't flag something as a bug if you're unsure — investigate first
- Don't invent hypothetical problems — if an edge case matters, explain the realistic scenario where it breaks
- If memory contains a convention that contradicts what you'd normally flag, defer to the stored convention — it represents an explicit project decision
@@ -70,6 +72,8 @@ Don't be a zealot about style:
- Some "violations" are acceptable when they're the simplest option
- Don't flag style preferences unless they clearly violate established project conventions
If you're uncertain about something and can't verify it, say "I'm not sure about X" rather than flagging it as a definite issue.
## Tool Usage
- Use the Task tool with explore agents to find how existing code handles similar problems
@@ -77,8 +81,6 @@ Don't be a zealot about style:
- Call multiple tools in a single response when independent
- Use specialized tools (Read, Glob, Grep) instead of bash equivalents (cat, find, grep)
If you're uncertain about something and can't verify it, say "I'm not sure about X" rather than flagging it as a definite issue.
## Output Format
Return your review as a structured summary. The calling agent will use this to inform the user.
@@ -99,7 +101,7 @@ Any non-issue observations worth noting (positive patterns, questions for the au
### Next Steps
If any bugs or warnings were found:
- Direct the calling agent: "Create a plan to address the issues above and present it for approval before making changes."
- Recommend to the calling agent: "Create a plan to address the issues above and present it for approval before making changes."
- The calling agent is responsible for planning the fixes — do not construct the plan yourself.
If only suggestions were found or no issues at all:
@@ -120,7 +122,7 @@ After completing a review, store each **bug** and **warning** finding in the pro
Use \`memory-kv-set\` with a structured key and JSON value:
**Key pattern**: \`review-finding:<file_path>:<line_number>\`
**Value**: JSON object with the finding details
**Value**: JSON object with the finding details. Include the current branch name (via \`git branch --show-current\`) in the \`branch\` field.
Example:
\`\`\`json
@@ -131,7 +133,8 @@ Example:
"description": "Missing null check on user.session before accessing .token — throws TypeError when session expires mid-request.",
"scenario": "User's session expires between the auth check and token access on line 45.",
"status": "open",
"date": "2026-03-07"
"date": "2026-03-07",
"branch": "feature/auth-refactor"
}
\`\`\`
@@ -149,25 +152,6 @@ At the start of every review, before analyzing the 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
## Memory Tools
You have access to these tools:
- **memory-read**: Search permanent memories for conventions and decisions (query, scope, limit)
- **memory-kv-set**: Store review findings with 24h TTL (key, value as JSON string)
- **memory-kv-get**: Retrieve a specific finding by key
- **memory-kv-list**: List all active KV entries for the project
## Project KV Store
Review findings are stored in the project KV store with 24-hour TTL. Use \`memory-kv-set\` to persist findings, \`memory-kv-get\` to retrieve specific findings, and \`memory-kv-list\` to see all active entries. Entries expire automatically after 24 hours.
## Injected Memory
Your messages may include \`<project-memory>\` blocks containing memories automatically retrieved based on semantic similarity to the current message. Each entry has the format \`#<id> [<scope>] <content>\`.
- **[convention]**: Rules to check code against
- **[decision]**: Architectural constraints that may apply
- **[context]**: Reference information and persisted review findings
These memories may be stale or irrelevant. If a memory seems outdated, note it in your review observations.`,
${getInjectedMemory('auditor')}
`,
}
+13 -14
View File
@@ -1,3 +1,4 @@
import { getInjectedMemory } from './prompts'
import type { AgentDefinition } from './types'
export const codeAgent: AgentDefinition = {
@@ -16,8 +17,6 @@ export const codeAgent: AgentDefinition = {
},
systemPrompt: `You are a coding agent that helps users with software engineering tasks. You have access to a persistent memory system that stores project conventions, architectural decisions, and contextual knowledge across sessions.
IMPORTANT: You must NEVER generate or guess URLs unless they are programming-related.
# Tone and style
- Only use emojis if the user explicitly requests it.
- Your output is displayed on a CLI using GitHub-flavored markdown. Keep responses short and concise.
@@ -37,18 +36,17 @@ Mark todos as completed as soon as each task is done — do not batch completion
# Tool usage policy
- When doing file search or exploring the codebase, prefer the Task tool to reduce context usage.
- Proactively use the Task tool with specialized agents when the task matches the agent's description.
- Proactively use the Task tool with specialized agents — use @Librarian for memory research, explore agents for codebase search, and the auditor for code review.
- If a task matches an available skill, use the Skill tool to load domain-specific instructions. Skill outputs persist through compaction.
- Call multiple tools in a single response when they are independent. Batch parallel tool calls for performance.
- Use specialized tools (Read, Glob, Grep, Edit, Write) instead of bash equivalents (cat, find, grep, sed, echo).
- NEVER use bash echo or other CLI tools to communicate with the user. Output text directly.
# Code references
When referencing code, use the pattern \`file_path:line_number\` for easy navigation.
## Memory Integration
You have memory tools (memory-read, memory-write, memory-edit, memory-delete) and the @Librarian subagent (via Task tool) for complex operations — multi-query research, contradiction resolution, and bulk curation. Delegate to @Librarian when you need broad context or when the result set could be large, to keep your context clean.
You have memory tools and the @Librarian subagent (via Task tool) for complex operations — multi-query research, contradiction resolution, and bulk curation. Delegate to @Librarian when you need broad context or when the result set could be large, to keep your context clean.
**Check memory** before modifying unfamiliar code areas, making architectural decisions, or when the user references past decisions. Skip memory for trivial tasks or when the user provides all necessary context.
@@ -61,20 +59,21 @@ You have memory tools (memory-read, memory-write, memory-edit, memory-delete) an
- Check for duplicates with memory-read before writing
- Update stale memories with memory-edit rather than creating duplicates
- Reference file paths when storing structural context
- Note the current git branch (via \`git branch --show-current\`) when storing memories — append "(branch: <name>)" to the content so future sessions know the context in which the knowledge was captured
## Injected Memory
${getInjectedMemory('code')}
Your messages may include \`<project-memory>\` blocks containing memories automatically retrieved based on semantic similarity to the current message. Each entry has the format \`#<id> [<scope>] <content>\`.
## Constraints
- **[convention]**: Rules to follow — coding style, naming patterns, workflow preferences
- **[decision]**: Architectural choices with rationale — treat as constraints
- **[context]**: Reference information — file locations, domain knowledge, known issues
These memories may be stale or irrelevant to the current task. Use your judgement. If a memory seems outdated or incorrect for the current task, you can ignore it.
If you notice patterns of outdated or incorrect memories, consider asking the user to curate them. Use the @Librarian subagent to perform memory research and contradiction resolution.
Never generate or guess URLs unless they are programming-related.
## Project KV Store
Use \`memory-kv-get\` to check for active project state (e.g., planning progress, code review patterns). Use \`memory-kv-set\` to store ephemeral findings. Entries expire after 24 hours. Use \`memory-kv-list\` to see all active entries.
You have access to a project-scoped key-value store with 24-hour 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.
`,
}
+21 -16
View File
@@ -1,3 +1,4 @@
import { INJECTED_MEMORY_HEADER } from './prompts'
import type { AgentDefinition } from './types'
export const librarianAgent: AgentDefinition = {
@@ -8,9 +9,9 @@ export const librarianAgent: AgentDefinition = {
mode: 'subagent',
temperature: 0.0,
tools: {
exclude: ['memory-plan-execute', 'memory-health', 'memory-kv-set', 'memory-kv-get', 'memory-kv-list'],
exclude: ['memory-plan-execute', 'memory-plan-ralph', 'memory-health', 'memory-kv-set', 'memory-kv-get', 'memory-kv-list'],
},
systemPrompt: `You are the project's librarian — the keeper of institutional memory. Your purpose is to capture, organize, and retrieve knowledge that persists across sessions.
systemPrompt: `You are a memory management agent. Your purpose is to capture, organize, and retrieve knowledge that persists across sessions.
## Your Role
@@ -104,23 +105,25 @@ When creating memories:
- Bad: "We use Bun"
4. **Reference files when applicable**:
- This helps agents locate relevant code
- This helps agents locate relevant code
5. **Check for duplicates first**:
- Before creating, use memory-read to see if similar memory exists
- If similar memory exists, update it instead of creating duplicates
5. **Note the branch**: Run \`git branch --show-current\` and append "(branch: <name>)" to the memory content. This helps future curation — knowing which branch a decision was made on indicates whether it's merged/active or experimental.
6. **Avoid ephemeral information**:
- Don't store: task details, temporary workarounds, session-specific context
- Do store: patterns that apply across sessions, lessons learned
6. **Check for duplicates first**:
- Before creating, use memory-read to see if similar memory exists
- If similar memory exists, update it instead of creating duplicates
7. **Avoid ephemeral information**:
- Don't store: task details, temporary workarounds, session-specific context
- Do store: patterns that apply across sessions, lessons learned
## Curation Rules
Maintain quality over quantity:
1. **Archive outdated memories**:
- If a convention is no longer followed, archive it
- If a decision has been superseded, note the change
1. **Remove or update outdated memories**:
- If a convention is no longer followed, delete it with memory-delete
- If a decision has been superseded, update it with memory-edit to reflect the current state
2. **Handle contradictions**:
- Surface both sides of a contradiction
@@ -132,8 +135,8 @@ Maintain quality over quantity:
- "Use named exports" + "Prefer named over default exports" → single memory about export conventions
4. **Delete exact duplicates**:
- If memory-write reports deduplicated, the work is done
- No need to create identical copies
- If a near-identical memory already exists, skip creating a new one
- Use memory-read to check before writing
5. **Acknowledge knowledge gaps**:
- If asked about something with no memories, say so clearly
@@ -197,9 +200,11 @@ You are NOT needed for:
4. **memory-delete**: Remove memories by ID
- id: The memory ID to delete
## Injected Memory
${INJECTED_MEMORY_HEADER}
Your messages may include \`<project-memory>\` blocks containing memories automatically retrieved based on semantic similarity to the current message. Each entry has the format \`#<id> [<scope>] <content>\`.
- **[convention]**: Rules the project follows — verify these are current when encountered
- **[decision]**: Architectural choices with rationale — check for staleness
- **[context]**: Reference information — file locations, domain knowledge, known issues
Use these as a starting point for your research — they indicate what the system found relevant. Cross-reference with memory-read for completeness. If any injected memory is stale or contradicts newer information, update or delete it.
+32
View File
@@ -0,0 +1,32 @@
type InjectedMemoryRole = 'code' | 'auditor' | 'architect'
export const INJECTED_MEMORY_HEADER = `## Injected Memory
Your messages may include \`<project-memory>\` blocks containing memories automatically retrieved based on semantic similarity to the current message. Each entry has the format \`#<id> [<scope>] <content>\`.`
const SCOPE_DESCRIPTIONS: Record<InjectedMemoryRole, string> = {
code: `- **[convention]**: Rules to follow — coding style, naming patterns, workflow preferences
- **[decision]**: Architectural choices with rationale — treat as constraints
- **[context]**: Reference information — file locations, domain knowledge, known issues`,
auditor: `- **[convention]**: Rules to check code against
- **[decision]**: Architectural constraints that may apply
- **[context]**: Reference information and persisted review findings`,
architect: `- **[convention]**: Rules to follow when planning
- **[decision]**: Architectural constraints with rationale
- **[context]**: Reference information — file locations, domain knowledge`,
}
const SCOPE_GUIDANCE: Record<InjectedMemoryRole, string> = {
code: `These memories may be stale or irrelevant to the current task. Use your judgement. If a memory seems outdated or incorrect for the current task, you can ignore it.
If you notice patterns of outdated or incorrect memories, consider asking the user to curate them. Use the @Librarian subagent to perform memory research and contradiction resolution.`,
auditor: `These memories may be stale or irrelevant. Use your judgement — if a memory seems outdated, flag it in your review observations and recommend the calling agent update or delete it.`,
architect: `These memories may be stale or irrelevant. Use your judgement — if a memory seems outdated, note it in your plan and recommend updating or deleting it via memory-edit or memory-delete. Use the @Librarian subagent to perform memory research and contradiction resolution when needed.`,
}
export function getInjectedMemory(role: InjectedMemoryRole): string {
return `${INJECTED_MEMORY_HEADER}
${SCOPE_DESCRIPTIONS[role]}
${SCOPE_GUIDANCE[role]}`
}
+227
View File
@@ -0,0 +1,227 @@
import type { RalphState } from '../../services/ralph'
import { openDatabase, confirm } from '../utils'
import { execSync, spawnSync } from 'child_process'
import { existsSync } from 'fs'
import { resolve } from 'path'
interface CancelOptions {
projectId?: string
dbPath?: string
cleanup?: boolean
force?: boolean
help?: boolean
}
function parseArgs(args: string[]): CancelOptions & { worktreeName?: string } {
const options: CancelOptions & { worktreeName?: string } = {}
let i = 0
while (i < args.length) {
const arg = args[i]
if (arg === '--project' || arg === '-p') {
options.projectId = args[++i]
} else if (arg === '--db-path') {
options.dbPath = args[++i]
} else if (arg === '--cleanup') {
options.cleanup = true
} else if (arg === '--force') {
options.force = true
} else if (arg === '--help' || arg === '-h') {
options.help = true
} else if (!arg.startsWith('-')) {
options.worktreeName = arg
} else {
console.error(`Unknown option: ${arg}`)
help()
process.exit(1)
}
i++
}
return options
}
export function help(): void {
console.log(`
Cancel a Ralph loop
Usage:
ocm-mem cancel [name] [options]
Arguments:
name Worktree name to cancel (optional if only one active)
Options:
--cleanup Remove worktree directory after cancellation
--force Skip confirmation prompt
--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
`.trim())
}
export async function run(args: string[], globalOpts: { dbPath?: string; projectId?: string }): Promise<void> {
const options = parseArgs(args)
options.projectId = options.projectId || globalOpts.projectId
options.dbPath = options.dbPath || globalOpts.dbPath
if (options.help) {
help()
process.exit(0)
}
const db = openDatabase(options.dbPath)
try {
const projectId = options.projectId
const now = Date.now()
let query: string
let params: (string | number)[]
if (projectId) {
query = 'SELECT project_id, key, data FROM project_kv WHERE project_id = ? AND key LIKE ? AND expires_at > ?'
params = [projectId, 'ralph:%', now]
} else {
query = 'SELECT project_id, key, data FROM project_kv WHERE key LIKE ? AND expires_at > ?'
params = ['ralph:%', now]
}
let rows: Array<{ project_id: string; key: string; data: string }>
try {
rows = db.prepare(query).all(...params) as Array<{ project_id: string; key: string; data: string }>
} catch {
rows = []
}
if (rows.length === 0) {
console.log('')
console.log('No active Ralph loops.')
console.log('')
return
}
const loops: Array<{ state: RalphState; row: { project_id: string; key: string; data: string } }> = []
for (const row of rows) {
try {
const state = JSON.parse(row.data) as RalphState
if (state.active) {
loops.push({ state, row })
}
} catch {}
}
if (loops.length === 0) {
console.log('')
console.log('No active Ralph loops.')
console.log('')
return
}
let loopToCancel: { state: RalphState; row: { project_id: string; key: string; data: string } } | undefined
if (options.worktreeName) {
loopToCancel = loops.find((l) => l.state.worktreeName === options.worktreeName)
if (!loopToCancel) {
console.error(`Ralph loop not found: ${options.worktreeName}`)
console.error('')
console.error('Active loops:')
for (const l of loops) {
console.error(` - ${l.state.worktreeName}`)
}
console.error('')
process.exit(1)
}
} else {
if (loops.length === 1) {
loopToCancel = loops[0]
} else {
console.log('')
console.log('Multiple active Ralph loops. Please specify which one to cancel:')
console.log('')
for (const l of loops) {
console.log(` - ${l.state.worktreeName}`)
}
console.log('')
console.log("Run 'ocm-mem cancel <name>' to cancel a specific loop.")
console.log('')
process.exit(1)
}
}
if (!loopToCancel) {
console.error('Internal error: loop not found')
process.exit(1)
}
const { state } = loopToCancel
console.log('')
console.log(`Ralph Loop to Cancel:`)
console.log(` Worktree: ${state.worktreeName}`)
console.log(` Session: ${state.sessionId}`)
console.log(` Iteration: ${state.iteration}/${state.maxIterations}`)
console.log(` Phase: ${state.phase}`)
if (options.cleanup) {
console.log(` Worktree: ${state.worktreeDir} (will be removed)`)
}
console.log('')
await runCancel(db, loopToCancel, options)
} finally {
db.close()
}
}
async function runCancel(
db: ReturnType<typeof openDatabase>,
loopToCancel: { state: RalphState; row: { project_id: string; key: string; data: string } },
options: CancelOptions & { worktreeName?: string },
): Promise<void> {
const { state } = loopToCancel
const shouldProceed = options.force || await confirm(`Cancel Ralph loop '${state.worktreeName}'`)
if (!shouldProceed) {
console.log('Cancelled.')
return
}
const updatedState = {
...state,
active: false,
completedAt: new Date().toISOString(),
terminationReason: 'cancelled',
}
db.prepare('UPDATE project_kv SET data = ?, updated_at = ? WHERE project_id = ? AND key = ?').run(
JSON.stringify(updatedState),
Date.now(),
loopToCancel.row.project_id,
loopToCancel.row.key,
)
console.log(`Cancelled Ralph loop: ${state.worktreeName}`)
if (options.cleanup && state.worktreeDir && !state.inPlace) {
if (existsSync(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, '..')
const removeResult = spawnSync('git', ['worktree', 'remove', '-f', state.worktreeDir], { cwd: gitRoot, encoding: 'utf-8' })
if (removeResult.status !== 0) {
throw new Error(removeResult.stderr || 'git worktree remove failed')
}
console.log(`Removed worktree: ${state.worktreeDir}`)
} catch {
console.error(`Failed to remove worktree: ${state.worktreeDir}`)
console.error('You may need to remove it manually.')
}
}
}
console.log('')
}
+118 -1
View File
@@ -1,4 +1,9 @@
import { openDatabase, formatDate, truncate, confirm, resolveProjectNames, displayProjectId, MemoryScope } from '../utils'
import { existsSync, readFileSync } from 'fs'
import { join } from 'path'
import { homedir, platform } from 'os'
import { execSync } from 'child_process'
import { createConnection } from 'net'
interface CleanupOptions {
olderThan?: number
@@ -10,6 +15,7 @@ interface CleanupOptions {
projectId?: string
dbPath?: string
help?: boolean
vecWorkers?: boolean
}
function parseArgs(args: string[]): CleanupOptions {
@@ -49,6 +55,8 @@ function parseArgs(args: string[]): CleanupOptions {
options.projectId = args[++i]
} else if (arg === '--db-path') {
options.dbPath = args[++i]
} else if (arg === '--vec-workers') {
options.vecWorkers = true
} else if (arg === '--help' || arg === '-h') {
help()
process.exit(0)
@@ -70,6 +78,7 @@ Delete memories by criteria
Usage:
ocm-mem cleanup [options]
ocm-mem cleanup --vec-workers
Options:
--older-than <days> Delete memories older than N days
@@ -80,11 +89,12 @@ Options:
--force Skip confirmation prompt
--project, -p <id> Project ID (auto-detected from git if not provided)
--db-path <path> Path to memory database
--vec-workers Clean up orphaned vec-worker processes
--help, -h Show this help message
`.trim())
}
export function run(args: string[], globalOpts: { dbPath?: string; projectId?: string }): void {
export async function run(args: string[], globalOpts: { dbPath?: string; projectId?: string }): Promise<void> {
const options = parseArgs(args)
options.projectId = options.projectId || globalOpts.projectId
@@ -93,6 +103,12 @@ export function run(args: string[], globalOpts: { dbPath?: string; projectId?: s
process.exit(0)
}
if (options.vecWorkers) {
const result = await cleanupVecWorkers()
console.log(result)
return
}
if (!options.olderThan && !options.ids && !options.all) {
console.error('At least one filter must be provided: --older-than, --ids, or --all')
help()
@@ -198,3 +214,104 @@ async function runMemoryCleanup(db: ReturnType<typeof openDatabase>, options: Cl
console.log(`Deleted ${rows.length} memories. ${remainingCount.count} remaining.`)
console.log("Note: Run 'memory-health reindex' in OpenCode to clean up orphaned embeddings.")
}
export async function cleanupVecWorkers(): Promise<string> {
const workers = findVecWorkers()
const defaultDataDir = getDefaultDataDir()
if (workers.length === 0) {
return 'No vec-worker processes found.'
}
const results: string[] = []
let cleaned = 0
for (const worker of workers) {
const isDefault = worker.dbPath.startsWith(defaultDataDir)
const isHealthy = await isWorkerHealthy(worker.pid, worker.socketPath)
if (isHealthy) {
results.push(`✓ PID ${worker.pid} - healthy (data dir: ${isDefault ? 'global' : 'workspace'})`)
} else {
try {
process.kill(worker.pid, 'SIGTERM')
results.push(`✗ PID ${worker.pid} - terminated (was orphaned)`)
cleaned++
} catch (err) {
results.push(`✗ PID ${worker.pid} - failed to terminate`)
}
}
}
return `Vec-worker cleanup complete:\n${results.join('\n')}\n\nTerminated ${cleaned} orphaned worker(s).`
}
function getDefaultDataDir(): string {
const defaultBase = join(homedir(), platform() === 'win32' ? 'AppData' : '.local', 'share')
const xdgDataHome = process.env['XDG_DATA_HOME'] || defaultBase
return join(xdgDataHome, 'opencode', 'memory')
}
function findVecWorkers(): Array<{ pid: number; dbPath: string; socketPath: string }> {
const workers: Array<{ pid: number; dbPath: string; socketPath: string }> = []
try {
const output = execSync('ps aux | grep vec-worker | grep -v grep', { encoding: 'utf-8' })
const lines = output.split('\n').filter(line => line.trim())
for (const line of lines) {
const parts = line.trim().split(/\s+/)
const pid = parseInt(parts[1], 10)
const dbMatch = line.match(/--db\s+([^\s]+)/)
const socketMatch = line.match(/--socket\s+([^\s]+)/)
if (dbMatch && socketMatch && !isNaN(pid)) {
workers.push({
pid,
dbPath: dbMatch[1],
socketPath: socketMatch[1],
})
}
}
} catch {
}
return workers
}
async function isWorkerHealthy(pid: number, socketPath: string): Promise<boolean> {
if (!existsSync(socketPath)) return false
try {
process.kill(pid, 0)
return new Promise((resolve) => {
const client = createConnection({ path: socketPath })
const timeout = setTimeout(() => {
client.destroy()
resolve(false)
}, 2000)
client.on('connect', () => {
client.write(JSON.stringify({ action: 'health' }) + '\n')
})
client.on('data', (chunk) => {
clearTimeout(timeout)
client.destroy()
try {
const response = JSON.parse(chunk.toString())
resolve(response.status === 'ok')
} catch {
resolve(false)
}
})
client.on('error', () => {
clearTimeout(timeout)
resolve(false)
})
})
} catch {
return false
}
}
+256
View File
@@ -0,0 +1,256 @@
import type { RalphState } from '../../services/ralph'
import { openDatabase } from '../utils'
interface RalphLoopInfo {
sessionId: string
worktreeName: string
worktreeBranch: string
iteration: number
maxIterations: number
phase: 'coding' | 'auditing'
startedAt: string
audit: boolean
}
function parseArgs(args: string[]): { projectId?: string; dbPath?: string; help?: boolean; worktreeName?: string } {
const options: { projectId?: string; dbPath?: string; help?: boolean; worktreeName?: string } = {}
let i = 0
while (i < args.length) {
const arg = args[i]
if (arg === '--project' || arg === '-p') {
options.projectId = args[++i]
} else if (arg === '--db-path') {
options.dbPath = args[++i]
} else if (arg === '--help' || arg === '-h') {
options.help = true
} else if (!arg.startsWith('-')) {
options.worktreeName = arg
} else {
console.error(`Unknown option: ${arg}`)
help()
process.exit(1)
}
i++
}
return options
}
export function help(): void {
console.log(`
Show Ralph loop status
Usage:
ocm-mem status [options]
ocm-mem status <name> [options]
Arguments:
name Worktree name for detailed status (optional)
Options:
--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
`.trim())
}
export function run(args: string[], globalOpts: { dbPath?: string; projectId?: string }): void {
const options = parseArgs(args)
options.projectId = options.projectId || globalOpts.projectId
options.dbPath = options.dbPath || globalOpts.dbPath
if (options.help) {
help()
process.exit(0)
}
const db = openDatabase(options.dbPath)
try {
const projectId = options.projectId
const now = Date.now()
let query: string
let params: (string | number)[]
if (projectId) {
query = 'SELECT key, data FROM project_kv WHERE project_id = ? AND key LIKE ? AND expires_at > ?'
params = [projectId, 'ralph:%', now]
} else {
query = 'SELECT key, data FROM project_kv WHERE key LIKE ? AND expires_at > ?'
params = ['ralph:%', now]
}
let rows: Array<{ key: string; data: string }>
try {
rows = db.prepare(query).all(...params) as Array<{ key: string; data: string }>
} catch {
rows = []
}
const activeLoops: RalphLoopInfo[] = []
const recentLoops: Array<{ state: RalphState; row: { key: string; data: string } }> = []
for (const row of rows) {
try {
const state = JSON.parse(row.data) as RalphState
if (state.active) {
activeLoops.push({
sessionId: state.sessionId,
worktreeName: state.worktreeName,
worktreeBranch: state.worktreeBranch,
iteration: state.iteration,
maxIterations: state.maxIterations,
phase: state.phase,
startedAt: state.startedAt,
audit: state.audit,
})
} else if (state.completedAt) {
recentLoops.push({ state, row })
}
} catch {}
}
const worktreeName = options.worktreeName
if (worktreeName) {
let activeLoop = activeLoops.find((l) => l.worktreeName === worktreeName)
let recentLoop = recentLoops.find((l) => l.state.worktreeName === worktreeName)
if (!activeLoop && !recentLoop) {
console.error(`Ralph loop not found: ${worktreeName}`)
console.error('')
if (activeLoops.length > 0) {
console.error('Active loops:')
for (const l of activeLoops) {
console.error(` - ${l.worktreeName}`)
}
}
if (recentLoops.length > 0) {
console.error('Recently completed:')
for (const l of recentLoops) {
console.error(` - ${l.state.worktreeName}`)
}
}
console.error('')
process.exit(1)
}
if (activeLoop) {
const row = rows.find((r) => {
try {
const state = JSON.parse(r.data) as RalphState
return state.worktreeName === worktreeName
} catch {
return false
}
})
if (!row) {
console.error(`Failed to retrieve state for: ${worktreeName}`)
process.exit(1)
}
const state = JSON.parse(row.data) as RalphState
const duration = Date.now() - new Date(state.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)
console.log('')
console.log(`Ralph Loop: ${state.worktreeName}`)
console.log(` Session ID: ${state.sessionId}`)
console.log(` Worktree: ${state.worktreeName}`)
console.log(` Branch: ${state.worktreeBranch}`)
console.log(` Worktree Dir: ${state.worktreeDir}`)
if (state.inPlace) {
console.log(` Mode: in-place`)
}
console.log(` Phase: ${state.phase}`)
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()}`)
if (state.completionPromise) {
console.log(` Completion: ${state.completionPromise}`)
}
console.log('')
} else if (recentLoop) {
const state = recentLoop.state
const completedAt = state.completedAt!
const duration = new Date(completedAt).getTime() - new Date(state.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)
console.log('')
console.log(`Ralph Loop (Completed): ${state.worktreeName}`)
console.log(` Session ID: ${state.sessionId}`)
console.log(` Worktree: ${state.worktreeName}`)
console.log(` Branch: ${state.worktreeBranch}`)
console.log(` Worktree Dir: ${state.worktreeDir}`)
if (state.inPlace) {
console.log(` Mode: in-place (completed)`)
}
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(` Completed: ${new Date(completedAt).toISOString()}`)
console.log('')
}
} else {
if (activeLoops.length > 0) {
console.log('')
console.log('Active Ralph Loops:')
console.log('')
for (const loop of activeLoops) {
const duration = Date.now() - new Date(loop.startedAt).getTime()
const hours = Math.floor(duration / (1000 * 60 * 60))
const minutes = Math.floor((duration % (1000 * 60 * 60)) / (1000 * 60))
const durationStr = `${hours}h ${minutes}m`
const iterStr = `${loop.iteration}/${loop.maxIterations}`
const audit = loop.audit ? 'Yes' : 'No'
console.log(` ${loop.worktreeName}`)
console.log(` Phase: ${loop.phase} Iteration: ${iterStr} Duration: ${durationStr} Audit: ${audit}`)
console.log('')
}
console.log(`Total: ${activeLoops.length} active loop(s)`)
console.log('')
}
if (recentLoops.length > 0) {
console.log('Recently Completed:')
console.log('')
for (const loop of recentLoops) {
const reason = loop.state.terminationReason ?? 'unknown'
const completed = new Date(loop.state.completedAt!).toLocaleString()
console.log(` ${loop.state.worktreeName}`)
console.log(` Iterations: ${loop.state.iteration} Reason: ${reason} Completed: ${completed}`)
console.log('')
}
}
if (activeLoops.length === 0 && recentLoops.length === 0) {
console.log('')
console.log('No Ralph loops found.')
console.log('')
} else {
console.log("Run 'ocm-mem status <name>' for detailed information.")
console.log('')
}
}
} finally {
db.close()
}
}
+22
View File
@@ -67,6 +67,26 @@ const commands: Record<string, CommandModule> = {
help()
},
},
status: {
run: async (args, globalOpts) => {
const { run } = await import('./commands/status')
await run(args, globalOpts)
},
help: async () => {
const { help } = await import('./commands/status')
help()
},
},
cancel: {
run: async (args, globalOpts) => {
const { run } = await import('./commands/cancel')
await run(args, globalOpts)
},
help: async () => {
const { help } = await import('./commands/cancel')
help()
},
},
}
function printMainHelp(): void {
@@ -83,6 +103,8 @@ Commands:
stats Show memory statistics
cleanup Delete memories by criteria
upgrade Check for and install plugin updates
status Show Ralph loop status
cancel Cancel a Ralph loop
Global Options:
--db-path <path> Path to memory database
+12
View File
@@ -17,6 +17,18 @@ const PLUGIN_COMMANDS: Record<string, { template: string; description: string; a
subtask: true,
template: 'Review the current code changes. $ARGUMENTS',
},
'ralph-loop': {
description: 'Start a Ralph iterative development loop in a worktree',
agent: 'code',
subtask: false,
template: 'Use the memory-plan-ralph tool to start a Ralph loop. Use the following as the plan: $ARGUMENTS. Derive a short title from the plan.',
},
'cancel-ralph': {
description: 'Cancel the active Ralph loop',
agent: 'code',
subtask: false,
template: 'Use the ralph-cancel tool to cancel the active Ralph loop. $ARGUMENTS',
},
}
export function createConfigHandler(agents: Record<AgentRole, AgentDefinition>) {
+1
View File
@@ -7,3 +7,4 @@ export {
extractCompactionSummary,
} from './compaction-utils'
export { createMemoryInjectionHook, type MemoryInjectionHook } from './memory-injection'
export { createRalphEventHandler, type RalphEventHandler } from './ralph'
+713
View File
@@ -0,0 +1,713 @@
import type { PluginInput } from '@opencode-ai/plugin'
import type { OpencodeClient } from '@opencode-ai/sdk/v2'
import type { RalphService, RalphState } from '../services/ralph'
import { MAX_RETRIES, MAX_CONSECUTIVE_STALLS } from '../services/ralph'
import type { Logger, PluginConfig } from '../types'
import { parseModelString, retryWithModelFallback } from '../utils/model-fallback'
import { execSync, spawnSync } from 'child_process'
import { resolve } from 'path'
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
cancelBySessionId(sessionId: string): Promise<boolean>
}
export function createRalphEventHandler(
ralphService: RalphService,
client: PluginInput['client'],
v2Client: OpencodeClient,
logger: Logger,
getConfig: () => PluginConfig,
): RalphEventHandler {
const minAudits = ralphService.getMinAudits()
const retryTimeouts = new Map<string, NodeJS.Timeout>()
const lastActivityTime = new Map<string, number>()
const stallWatchdogs = new Map<string, NodeJS.Timeout>()
const consecutiveStalls = new Map<string, number>()
const childSessions = new Map<string, Set<string>>()
async function commitAndCleanupWorktree(state: RalphState): Promise<{ committed: boolean; cleaned: boolean }> {
if (state.inPlace) {
logger.log(`Ralph: in-place mode, skipping commit and cleanup`)
return { committed: false, cleaned: false }
}
let committed = false
let cleaned = false
try {
const addResult = spawnSync('git', ['add', '-A'], { cwd: state.worktreeDir, encoding: 'utf-8' })
if (addResult.status !== 0) {
throw new Error(addResult.stderr || 'git add failed')
}
const statusResult = spawnSync('git', ['status', '--porcelain'], { cwd: state.worktreeDir, encoding: 'utf-8' })
if (statusResult.status !== 0) {
throw new Error(statusResult.stderr || 'git status failed')
}
const status = statusResult.stdout.trim()
if (status) {
const message = `ralph: ${state.worktreeName} completed after ${state.iteration} iterations`
const commitResult = spawnSync('git', ['commit', '-m', message], { cwd: state.worktreeDir, encoding: 'utf-8' })
if (commitResult.status !== 0) {
throw new Error(commitResult.stderr || 'git commit failed')
}
committed = true
logger.log(`Ralph: committed changes on branch ${state.worktreeBranch}`)
} else {
logger.log(`Ralph: no uncommitted changes to commit on branch ${state.worktreeBranch}`)
}
} catch (err) {
logger.error(`Ralph: failed to commit changes in worktree ${state.worktreeDir}`, err)
}
try {
const gitCommonDir = execSync('git rev-parse --git-common-dir', { cwd: state.worktreeDir, encoding: 'utf-8' }).trim()
const gitRoot = resolve(state.worktreeDir, gitCommonDir, '..')
const removeResult = spawnSync('git', ['worktree', 'remove', '-f', state.worktreeDir], { cwd: gitRoot, encoding: 'utf-8' })
if (removeResult.status !== 0) {
throw new Error(removeResult.stderr || 'git worktree remove failed')
}
cleaned = true
logger.log(`Ralph: removed worktree ${state.worktreeDir}, branch ${state.worktreeBranch} preserved`)
} catch (err) {
logger.error(`Ralph: failed to remove worktree ${state.worktreeDir}`, err)
}
return { committed, cleaned }
}
function findRalphParent(childSessionId: string): string | undefined {
for (const [ralphId, children] of childSessions.entries()) {
if (children.has(childSessionId)) {
return ralphId
}
}
return undefined
}
function recordActivity(sessionId: string): void {
lastActivityTime.set(sessionId, Date.now())
}
function stopWatchdog(sessionId: string): void {
const interval = stallWatchdogs.get(sessionId)
if (interval) {
clearInterval(interval)
stallWatchdogs.delete(sessionId)
}
lastActivityTime.delete(sessionId)
consecutiveStalls.delete(sessionId)
childSessions.delete(sessionId)
}
function startWatchdog(sessionId: string): void {
stopWatchdog(sessionId)
lastActivityTime.set(sessionId, Date.now())
consecutiveStalls.set(sessionId, 0)
const stallTimeout = ralphService.getStallTimeoutMs()
const interval = setInterval(async () => {
const lastActivity = lastActivityTime.get(sessionId)
if (!lastActivity) return
const elapsed = Date.now() - lastActivity
if (elapsed < stallTimeout) return
const state = ralphService.getActiveState(sessionId)
if (!state?.active) {
stopWatchdog(sessionId)
return
}
try {
const statusResult = await v2Client.session.status()
const statuses = (statusResult.data ?? {}) as Record<string, { type: string }>
const sessionIds = [sessionId, ...(childSessions.get(sessionId) ?? [])]
const hasActiveWork = sessionIds.some(id => {
const status = statuses[id]?.type
return status === 'busy' || status === 'retry' || status === 'compact'
})
if (hasActiveWork) {
lastActivityTime.set(sessionId, Date.now())
logger.log(`Ralph watchdog: session ${sessionId} has active work, resetting timer`)
return
}
} catch (err) {
logger.error(`Ralph watchdog: failed to check session status`, err)
return
}
const stallCount = (consecutiveStalls.get(sessionId) ?? 0) + 1
consecutiveStalls.set(sessionId, stallCount)
lastActivityTime.set(sessionId, 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')
return
}
logger.log(`Ralph watchdog: stall detected for session ${sessionId} (${stallCount}/${MAX_CONSECUTIVE_STALLS}), re-triggering ${state.phase} phase`)
try {
if (state.phase === 'auditing') {
await handleAuditingPhase(sessionId, state)
} else {
await handleCodingPhase(sessionId, state)
}
} catch (err) {
await handlePromptError(sessionId, state, `watchdog recovery in ${state.phase} phase`, err)
}
}, stallTimeout)
stallWatchdogs.set(sessionId, interval)
logger.log(`Ralph watchdog: started for session ${sessionId} (timeout: ${stallTimeout}ms)`)
}
function getStallInfo(sessionId: string): { consecutiveStalls: number; lastActivityTime: number } | null {
const lastActivity = lastActivityTime.get(sessionId)
if (lastActivity === undefined) return null
return {
consecutiveStalls: consecutiveStalls.get(sessionId) ?? 0,
lastActivityTime: lastActivity,
}
}
async function terminateLoop(sessionId: string, state: RalphState, reason: string): Promise<void> {
const children = childSessions.get(sessionId)
if (children) {
await Promise.all(
Array.from(children).map(async (childId) => {
try {
await v2Client.session.abort({ sessionID: childId })
} catch {
// Child session may already be idle
}
})
)
}
stopWatchdog(sessionId)
const retryTimeout = retryTimeouts.get(sessionId)
if (retryTimeout) {
clearTimeout(retryTimeout)
retryTimeouts.delete(sessionId)
}
ralphService.setState(sessionId, {
...state,
active: false,
completedAt: new Date().toISOString(),
terminationReason: reason,
})
try {
await v2Client.session.abort({ sessionID: sessionId })
} catch {
// Session may already be idle
}
logger.log(`Ralph loop terminated: reason="${reason}", worktree="${state.worktreeName}", iteration=${state.iteration}`)
let commitResult: { committed: boolean; cleaned: boolean } | undefined
if (reason === 'completed') {
commitResult = await commitAndCleanupWorktree(state)
}
if (state.parentSessionId) {
try {
let notificationText: string
if (state.inPlace) {
if (reason === 'completed') {
notificationText = [
`Ralph loop "${state.worktreeName}" completed (in-place).`,
'',
`Iteration: ${state.iteration}`,
`Changes are in the current directory on branch: ${state.worktreeBranch}`,
].join('\n')
} else {
notificationText = `Ralph loop "${state.worktreeName}" terminated (in-place).\n\nReason: ${reason}\nIteration: ${state.iteration}\nDirectory: ${state.worktreeDir}\nBranch: ${state.worktreeBranch}`
}
} else if (reason === 'completed' && commitResult) {
const parts = [`Ralph loop "${state.worktreeName}" completed.`, '', `Iteration: ${state.iteration}`]
if (commitResult.committed) {
parts.push(`Changes committed on branch: ${state.worktreeBranch}`)
}
if (commitResult.cleaned) {
parts.push(`Worktree removed. Use \`git merge ${state.worktreeBranch}\` or \`git checkout ${state.worktreeBranch}\` to access the changes.`)
} else {
parts.push(`Worktree: ${state.worktreeDir}`)
}
notificationText = parts.join('\n')
} else {
notificationText = `Ralph loop "${state.worktreeName}" terminated.\n\nReason: ${reason}\nIteration: ${state.iteration}\nWorktree: ${state.worktreeDir}\nBranch: ${state.worktreeBranch}`
}
await client.session.promptAsync({
path: { id: state.parentSessionId },
body: {
parts: [{
type: 'text' as const,
text: notificationText,
}],
},
})
} catch (err) {
logger.error(`Ralph: failed to notify parent session`, err)
}
}
}
async function handlePromptError(sessionId: string, state: RalphState, context: string, err: unknown, retryFn?: () => Promise<void>): Promise<void> {
const currentState = ralphService.getActiveState(sessionId)
if (!currentState?.active) {
logger.log(`Ralph: loop ${sessionId} already terminated, ignoring error: ${context}`)
return
}
const nextErrorCount = (currentState.errorCount ?? 0) + 1
if (nextErrorCount < MAX_RETRIES) {
logger.error(`Ralph: ${context} (attempt ${nextErrorCount}/${MAX_RETRIES}), will retry`, err)
ralphService.setState(sessionId, { ...currentState, errorCount: nextErrorCount })
if (retryFn) {
const retryTimeout = setTimeout(async () => {
const freshState = ralphService.getActiveState(sessionId)
if (!freshState?.active) {
logger.log(`Ralph: loop cancelled, skipping retry`)
retryTimeouts.delete(sessionId)
return
}
try {
await retryFn()
} catch (retryErr) {
await handlePromptError(sessionId, freshState, context, retryErr, retryFn)
}
}, 2000)
retryTimeouts.set(sessionId, retryTimeout)
}
} else {
logger.error(`Ralph: ${context} (attempt ${nextErrorCount}/${MAX_RETRIES}), giving up`, err)
await terminateLoop(sessionId, currentState, `error_max_retries: ${context}`)
}
}
async function getLastAssistantText(sessionId: string, worktreeDir: string): Promise<string | null> {
try {
const messagesResult = await v2Client.session.messages({
sessionID: sessionId,
directory: worktreeDir,
limit: 4,
})
const messages = (messagesResult.data ?? []) as Array<{
info: { role: string }
parts: Array<{ type: string; text?: string }>
}>
const lastAssistant = [...messages].reverse().find((m) => m.info.role === 'assistant')
if (!lastAssistant) return null
return lastAssistant.parts
.filter((p) => p.type === 'text' && typeof p.text === 'string')
.map((p) => p.text as string)
.join('\n')
} catch (err) {
logger.error(`Ralph: could not read session messages`, err)
return null
}
}
async function handleCodingPhase(sessionId: string, state: RalphState): Promise<void> {
let currentState = ralphService.getActiveState(sessionId)
if (!currentState?.active) {
logger.log(`Ralph: loop ${sessionId} no longer active, skipping coding phase`)
return
}
if (currentState.completionPromise) {
const textContent = await getLastAssistantText(sessionId, currentState.worktreeDir)
if (textContent && ralphService.checkCompletionPromise(textContent, currentState.completionPromise)) {
const currentAuditCount = currentState.auditCount ?? 0
if (!currentState.audit || currentAuditCount >= minAudits) {
await terminateLoop(sessionId, currentState, 'completed')
logger.log(`Ralph loop completed: detected <promise>${currentState.completionPromise}</promise> at iteration ${currentState.iteration} (${currentAuditCount}/${minAudits} audits)`)
return
}
logger.log(`Ralph: completion promise detected but only ${currentAuditCount}/${minAudits} audits performed, continuing`)
}
}
if (currentState.maxIterations > 0 && currentState.iteration >= currentState.maxIterations) {
await terminateLoop(sessionId, currentState, 'max_iterations')
return
}
if (currentState.audit) {
ralphService.setState(sessionId, { ...currentState, phase: 'auditing', errorCount: 0 })
logger.log(`Ralph iteration ${currentState.iteration} complete, running auditor for session ${sessionId}`)
const auditPrompt = {
sessionID: sessionId,
directory: currentState.worktreeDir,
parts: [{
type: 'subtask' as const,
agent: 'auditor',
description: `Post-iteration ${currentState.iteration} code review`,
prompt: ralphService.buildAuditPrompt(currentState),
}],
}
const promptResult = await v2Client.session.promptAsync(auditPrompt)
if (promptResult.error) {
const retryFn = async () => {
const result = await v2Client.session.promptAsync(auditPrompt)
if (result.error) {
throw result.error
}
}
await handlePromptError(sessionId, { ...currentState, phase: 'coding' }, 'failed to send audit prompt', promptResult.error, retryFn)
return
}
const currentConfig = getConfig()
const configuredModel = currentConfig.auditorModel ?? currentConfig.ralph?.model ?? currentConfig.executionModel
logger.log(`auditor using agent-configured model: ${configuredModel ?? 'default'}`)
consecutiveStalls.set(sessionId, 0)
return
}
const nextIteration = currentState.iteration + 1
ralphService.setState(sessionId, { ...currentState, iteration: nextIteration, errorCount: 0 })
const continuationPrompt = ralphService.buildContinuationPrompt({ ...currentState, iteration: nextIteration })
logger.log(`Ralph iteration ${nextIteration} for session ${sessionId}`)
const currentConfig = getConfig()
const ralphModel = parseModelString(currentConfig.ralph?.model) ?? parseModelString(currentConfig.executionModel)
const sendContinuationPromptWithModel = async () => {
const freshState = ralphService.getActiveState(sessionId)
if (!freshState?.active) {
throw new Error('loop_cancelled')
}
const result = await v2Client.session.promptAsync({
sessionID: sessionId,
directory: freshState.worktreeDir,
parts: [{ type: 'text' as const, text: continuationPrompt }],
model: ralphModel!,
})
return { data: result.data, error: result.error }
}
const sendContinuationPromptWithoutModel = async () => {
const freshState = ralphService.getActiveState(sessionId)
if (!freshState?.active) {
throw new Error('loop_cancelled')
}
const result = await v2Client.session.promptAsync({
sessionID: sessionId,
directory: freshState.worktreeDir,
parts: [{ type: 'text' as const, text: continuationPrompt }],
})
return { data: result.data, error: result.error }
}
const { result: promptResult, usedModel: actualModel } = await retryWithModelFallback(
sendContinuationPromptWithModel,
sendContinuationPromptWithoutModel,
ralphModel,
logger,
)
if (promptResult.error) {
const retryFn = async () => {
const result = await sendContinuationPromptWithoutModel()
if (result.error) {
throw result.error
}
}
await handlePromptError(sessionId, currentState, 'failed to send continuation prompt', promptResult.error, retryFn)
return
}
if (actualModel) {
logger.log(`coding phase using model: ${actualModel.providerID}/${actualModel.modelID}`)
} else {
logger.log(`coding phase using default model (fallback)`)
}
consecutiveStalls.set(sessionId, 0)
}
async function handleAuditingPhase(sessionId: string, state: RalphState): Promise<void> {
// Re-fetch and validate state to catch aborts that happened during idle event processing
const currentState = ralphService.getActiveState(sessionId)
if (!currentState?.active) {
logger.log(`Ralph: loop ${sessionId} no longer active, skipping auditing phase`)
return
}
const auditText = await getLastAssistantText(sessionId, currentState.worktreeDir)
const nextIteration = currentState.iteration + 1
const newAuditCount = (currentState.auditCount ?? 0) + 1
logger.log(`Ralph audit ${newAuditCount} at iteration ${currentState.iteration}`)
// Always pass the full audit response to the code agent
const auditFindings = auditText ?? undefined
if (currentState.completionPromise && auditText) {
if (ralphService.checkCompletionPromise(auditText, currentState.completionPromise)) {
// Check if minimum audits have been performed
if (!currentState.audit || newAuditCount >= minAudits) {
await terminateLoop(sessionId, currentState, 'completed')
logger.log(`Ralph loop completed: detected <promise>${currentState.completionPromise}</promise> in audit at iteration ${currentState.iteration} (${newAuditCount}/${minAudits} audits)`)
return
}
logger.log(`Ralph: completion promise detected but only ${newAuditCount}/${minAudits} audits performed, continuing`)
}
}
if (currentState.maxIterations > 0 && nextIteration > currentState.maxIterations) {
await terminateLoop(sessionId, currentState, 'max_iterations')
return
}
ralphService.setState(sessionId, {
...currentState,
iteration: nextIteration,
phase: 'coding',
lastAuditResult: auditFindings,
auditCount: newAuditCount,
errorCount: 0,
})
const continuationPrompt = ralphService.buildContinuationPrompt(
{ ...currentState, iteration: nextIteration },
auditFindings,
)
logger.log(`Ralph iteration ${nextIteration} for session ${sessionId}`)
const currentConfig = getConfig()
const ralphModel = parseModelString(currentConfig.ralph?.model) ?? parseModelString(currentConfig.executionModel)
const sendContinuationPromptWithModel = async () => {
const freshState = ralphService.getActiveState(sessionId)
if (!freshState?.active) {
throw new Error('loop_cancelled')
}
const result = await v2Client.session.promptAsync({
sessionID: sessionId,
directory: freshState.worktreeDir,
parts: [{ type: 'text' as const, text: continuationPrompt }],
model: ralphModel!,
})
return { data: result.data, error: result.error }
}
const sendContinuationPromptWithoutModel = async () => {
const freshState = ralphService.getActiveState(sessionId)
if (!freshState?.active) {
throw new Error('loop_cancelled')
}
const result = await v2Client.session.promptAsync({
sessionID: sessionId,
directory: freshState.worktreeDir,
parts: [{ type: 'text' as const, text: continuationPrompt }],
})
return { data: result.data, error: result.error }
}
const { result: promptResult, usedModel: actualModel } = await retryWithModelFallback(
sendContinuationPromptWithModel,
sendContinuationPromptWithoutModel,
ralphModel,
logger,
)
if (promptResult.error) {
const retryFn = async () => {
const freshState = ralphService.getActiveState(sessionId)
if (!freshState?.active) {
throw new Error('loop_cancelled')
}
const result = await sendContinuationPromptWithoutModel()
if (result.error) {
throw result.error
}
}
await handlePromptError(sessionId, currentState, 'failed to send continuation prompt after audit', promptResult.error, retryFn)
return
}
if (actualModel) {
logger.log(`coding continuation using model: ${actualModel.providerID}/${actualModel.modelID}`)
} else {
logger.log(`coding continuation using default model (fallback)`)
}
consecutiveStalls.set(sessionId, 0)
}
async function onEvent(input: { event: { type: string; properties?: Record<string, unknown> } }): Promise<void> {
const { event } = input
if (event.type === 'worktree.failed') {
const message = event.properties?.message as string
const directory = event.properties?.directory as string
logger.error(`Ralph: worktree failed: ${message}`)
if (directory) {
const activeLoops = ralphService.listActive()
const affectedLoop = activeLoops.find((s) => s.worktreeDir === directory)
if (affectedLoop) {
await terminateLoop(affectedLoop.sessionId, affectedLoop, `worktree_failed: ${message}`)
}
}
return
}
if (event.type === 'session.created' || event.type === 'session.updated') {
const info = event.properties?.info as { id?: string; parentID?: string } | undefined
if (info?.id && info?.parentID) {
const parentState = ralphService.getActiveState(info.parentID)
if (parentState?.active) {
let children = childSessions.get(info.parentID)
if (!children) {
children = new Set()
childSessions.set(info.parentID, children)
}
children.add(info.id)
recordActivity(info.parentID)
}
}
}
if (event.type === 'session.status') {
const eventSessionId = event.properties?.sessionID as string
if (eventSessionId) {
if (ralphService.getActiveState(eventSessionId)?.active) {
recordActivity(eventSessionId)
}
const parentId = findRalphParent(eventSessionId)
if (parentId) {
recordActivity(parentId)
}
}
}
if (event.type === 'session.error') {
const errorProps = event.properties as { sessionID?: string; error?: { name?: string } }
const eventSessionId = errorProps?.sessionID
const errorName = errorProps?.error?.name
const isAbort = errorName === 'MessageAbortedError' || errorName === 'AbortError'
if (!eventSessionId || !isAbort) return
const state = ralphService.getActiveState(eventSessionId)
if (state?.active) {
logger.log(`Ralph: session ${eventSessionId} aborted, terminating loop`)
await terminateLoop(eventSessionId, state, 'user_aborted')
}
const parentId = findRalphParent(eventSessionId)
if (parentId) {
const parentState = ralphService.getActiveState(parentId)
if (parentState?.active) {
logger.log(`Ralph: child session abort detected, terminating parent loop ${parentId}`)
await terminateLoop(parentId, parentState, 'user_aborted')
}
}
const childLoops = ralphService.findByParentSessionId(eventSessionId)
for (const childLoop of childLoops) {
logger.log(`Ralph: launcher session ${eventSessionId} aborted, terminating child loop ${childLoop.sessionId}`)
await terminateLoop(childLoop.sessionId, childLoop, 'user_aborted')
}
return
}
if (event.type !== 'session.idle') return
const sessionId = event.properties?.sessionID as string
if (!sessionId) return
const state = ralphService.getActiveState(sessionId)
if (!state || !state.active) return
const parentId = findRalphParent(sessionId)
if (parentId) {
recordActivity(parentId)
}
recordActivity(sessionId)
try {
// Re-check state right before calling phase handler as extra safety
const freshState = ralphService.getActiveState(sessionId)
if (!freshState?.active) {
logger.log(`Ralph: loop ${sessionId} was terminated, skipping phase handler`)
return
}
if (freshState.phase === 'auditing') {
await handleAuditingPhase(sessionId, freshState)
} else {
await handleCodingPhase(sessionId, freshState)
}
} catch (err) {
const freshState = ralphService.getActiveState(sessionId)
await handlePromptError(sessionId, freshState ?? state, `unhandled error in ${(freshState ?? state).phase} phase`, err)
}
}
function terminateAll(): void {
ralphService.terminateAll()
}
function clearAllRetryTimeouts(): void {
for (const [sessionId, timeout] of retryTimeouts.entries()) {
clearTimeout(timeout)
retryTimeouts.delete(sessionId)
}
for (const [sessionId, interval] of stallWatchdogs.entries()) {
clearInterval(interval)
stallWatchdogs.delete(sessionId)
}
lastActivityTime.clear()
consecutiveStalls.clear()
childSessions.clear()
logger.log('Ralph: cleared all retry timeouts')
}
async function cancelBySessionId(sessionId: string): Promise<boolean> {
const state = ralphService.getActiveState(sessionId)
if (!state?.active) {
return false
}
await terminateLoop(sessionId, state, 'cancelled')
return true
}
return {
onEvent,
terminateAll,
clearAllRetryTimeouts,
startWatchdog,
getStallInfo,
cancelBySessionId,
}
}
+3 -1
View File
@@ -65,7 +65,9 @@ For each item found, store it with the appropriate scope:
- decision: architectural choices with their rationale
- context: project structure, key file locations, domain knowledge, known issues
Be selective — only store knowledge useful in future sessions. Check for duplicates before writing (use memory-read to search first).
Be selective — only store knowledge useful in future sessions. Check for duplicates before writing (use memory-read to search first).
Note the current git branch (via \`git branch --show-current\`) and append "(branch: <name>)" to each memory stored, so future sessions know the context in which the knowledge was captured.
End your response with:
1. A brief summary of what was stored
+740 -35
View File
@@ -1,10 +1,11 @@
import type { Plugin, PluginInput, Hooks } from '@opencode-ai/plugin'
import { tool } from '@opencode-ai/plugin'
import { createOpencodeClient as createV2Client } from '@opencode-ai/sdk/v2'
import { agents } from './agents'
import { createConfigHandler } from './config'
import { VERSION } from './version'
import { createSessionHooks, createMemoryInjectionHook } from './hooks'
import { join } from 'path'
import { createSessionHooks, createMemoryInjectionHook, createRalphEventHandler } from './hooks'
import { join, resolve } from 'path'
import { initializeDatabase, resolveDataDir, closeDatabase, createMetadataQuery } from './storage'
import type { MemoryService } from './services/memory'
import { createVecService } from './storage/vec'
@@ -12,19 +13,26 @@ 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 { loadPluginConfig } from './setup'
import { resolveLogPath } from './storage'
import { createLogger } from './utils/logger'
import { createLogger, slugify } from './utils/logger'
import { stripPromiseTags } from './utils/strip-promise-tags'
import type { Database } from 'bun:sqlite'
import type { PluginConfig, CompactionConfig, HealthStatus, Logger } from './types'
import type { EmbeddingProvider } from './embedding'
import type { VecService } from './storage/vec-types'
import { createNoopVecService } from './storage/vec'
import { checkForUpdate, formatUpgradeCheck, performUpgrade } from './utils/upgrade'
import { MAX_RETRIES } from './services/ralph'
import { parseModelString, retryWithModelFallback } from './utils/model-fallback'
import { execSync, spawnSync } from 'child_process'
import { existsSync } from 'fs'
const z = tool.schema
const DEFAULT_PLAN_COMPLETION_PROMISE = 'All phases of the plan have been completed successfully'
async function getHealthStatus(
projectId: string,
db: Database,
@@ -248,21 +256,13 @@ async function autoValidateOnLoad(
logger.log('Auto-validate: reindex complete')
}
function parseModelString(modelStr?: string): { providerID: string; modelID: string } | undefined {
if (!modelStr) return undefined
const slashIndex = modelStr.indexOf('/')
if (slashIndex <= 0 || slashIndex === modelStr.length - 1) return undefined
return {
providerID: modelStr.substring(0, slashIndex),
modelID: modelStr.substring(slashIndex + 1),
}
}
export function createMemoryPlugin(config: PluginConfig): Plugin {
return async (input: PluginInput): Promise<Hooks> => {
const { directory, project, client } = input
const projectId = project.id
const v2 = createV2Client({ baseUrl: input.serverUrl.toString(), directory })
const loggingConfig = config.logging
const logger = createLogger({
enabled: loggingConfig?.enabled ?? false,
@@ -297,6 +297,9 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
const kvService = createKvService(db, logger)
const ralphService = createRalphService(kvService, projectId, logger, config.ralph)
const ralphHandler = createRalphEventHandler(ralphService, client, v2, logger, () => config)
const mismatchState: DimensionMismatchState = {
detected: false,
expected: null,
@@ -375,6 +378,15 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
if (cleaned) return
cleaned = true
logger.log('Cleaning up plugin resources...')
// First, stop all active Ralph loops
ralphHandler.terminateAll()
logger.log('Ralph: all active loops terminated')
// Clear all retry timeouts to prevent callbacks after cleanup
ralphHandler.clearAllRetryTimeouts()
// Then proceed with remaining cleanup
memoryInjection.destroy()
await memoryService.destroy()
closeDatabase(db)
@@ -387,6 +399,234 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
const getCleanup = cleanup
interface RalphSetupOptions {
prompt: string
sessionTitle: string
worktreeName?: string
completionPromise: string | null
maxIterations: number
audit: boolean
agent?: string
model?: { providerID: string; modelID: string }
parentSessionId?: string
inPlace?: boolean
onLoopStarted?: (sessionId: string) => void
}
async function setupRalphLoop(options: RalphSetupOptions): Promise<string> {
const autoWorktreeName = options.worktreeName ?? `ralph-${slugify(options.sessionTitle.replace(/^Ralph:\s*/i, ''))}`
const projectDir = directory
const maxIter = options.maxIterations ?? config.ralph?.defaultMaxIterations ?? 0
interface LoopContext {
sessionId: string
directory: string
branch: string
workspaceId?: string
inPlace: boolean
}
let loopContext: LoopContext
if (options.inPlace) {
let currentBranch: string
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.'
}
const createResult = await v2.session.create({
title: options.sessionTitle,
directory: projectDir,
})
if (createResult.error || !createResult.data) {
logger.error(`ralph: failed to create session`, createResult.error)
return 'Failed to create Ralph session.'
}
loopContext = {
sessionId: createResult.data.id,
directory: projectDir,
branch: currentBranch,
inPlace: true,
}
} else {
const worktreeResult = await v2.worktree.create({
worktreeCreateInput: { name: autoWorktreeName },
})
if (worktreeResult.error || !worktreeResult.data) {
logger.error(`ralph: failed to create worktree`, worktreeResult.error)
return 'Failed to create worktree.'
}
const worktreeInfo = worktreeResult.data
logger.log(`ralph: worktree created at ${worktreeInfo.directory} (branch: ${worktreeInfo.branch})`)
const createResult = await v2.session.create({
title: options.sessionTitle,
directory: worktreeInfo.directory,
})
if (createResult.error || !createResult.data) {
logger.error(`ralph: failed to create session`, createResult.error)
try {
await v2.worktree.remove({ worktreeRemoveInput: { directory: worktreeInfo.directory } })
} catch (cleanupErr) {
logger.error(`ralph: failed to cleanup worktree`, cleanupErr)
}
return 'Failed to create Ralph session.'
}
loopContext = {
sessionId: createResult.data.id,
directory: worktreeInfo.directory,
branch: worktreeInfo.branch,
workspaceId: `wrk-${autoWorktreeName}`,
inPlace: false,
}
}
const state: RalphState = {
active: true,
sessionId: loopContext.sessionId,
worktreeName: autoWorktreeName,
worktreeDir: loopContext.directory,
worktreeBranch: loopContext.branch,
workspaceId: loopContext.workspaceId ?? '',
iteration: 1,
maxIterations: maxIter,
completionPromise: options.completionPromise,
startedAt: new Date().toISOString(),
prompt: options.prompt,
phase: 'coding',
audit: options.audit,
errorCount: 0,
auditCount: 0,
parentSessionId: options.parentSessionId,
inPlace: options.inPlace,
}
ralphService.setState(loopContext.sessionId, state)
logger.log(`ralph: state stored for session=${loopContext.sessionId}`)
let promptText = options.prompt
if (options.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>${options.completionPromise}</promise>\n\nDo NOT output this tag until every phase is truly complete. The loop will continue until this signal is detected.`
}
const { result: promptResult, usedModel: actualModel } = await retryWithModelFallback(
() => v2.session.promptAsync({
sessionID: loopContext.sessionId,
directory: loopContext.directory,
parts: [{ type: 'text' as const, text: promptText }],
...(options.agent && { agent: options.agent }),
model: options.model!,
}),
() => v2.session.promptAsync({
sessionID: loopContext.sessionId,
directory: loopContext.directory,
parts: [{ type: 'text' as const, text: promptText }],
...(options.agent && { agent: options.agent }),
}),
options.model,
logger,
)
if (promptResult.error) {
logger.error(`ralph: failed to send prompt`, promptResult.error)
ralphService.deleteState(loopContext.sessionId)
if (!options.inPlace && loopContext.workspaceId) {
try {
await v2.worktree.remove({ worktreeRemoveInput: { directory: loopContext.directory } })
} catch (cleanupErr) {
logger.error(`ralph: failed to cleanup worktree`, cleanupErr)
}
}
return options.inPlace
? 'Ralph session created but failed to send prompt.'
: 'Ralph session created but failed to send prompt. Cleaned up.'
}
options.onLoopStarted?.(loopContext.sessionId)
const maxInfo = maxIter > 0 ? maxIter.toString() : 'unlimited'
const auditInfo = options.audit ? 'enabled' : 'disabled'
const modelInfo = actualModel ? `${actualModel.providerID}/${actualModel.modelID}` : 'default'
const lines: string[] = [
options.inPlace ? 'Ralph loop activated! (in-place mode)' : 'Ralph loop activated!',
'',
`Session: ${loopContext.sessionId}`,
`Title: ${options.sessionTitle}`,
]
if (options.inPlace) {
lines.push(`Directory: ${loopContext.directory}`)
lines.push(`Branch: ${loopContext.branch} (in-place)`)
} else {
lines.push(`Workspace: ${loopContext.workspaceId}`)
lines.push(`Worktree name: ${autoWorktreeName}`)
lines.push(`Worktree: ${loopContext.directory}`)
lines.push(`Branch: ${loopContext.branch}`)
}
lines.push(
`Model: ${modelInfo}`,
`Max iterations: ${maxInfo}`,
`Completion promise: ${options.completionPromise ?? 'none'}`,
`Audit: ${auditInfo}`,
'',
'The loop will automatically continue when the session goes idle.',
'Your job is done — just confirm to the user that the loop has been launched.',
'The user can run ralph-status or ralph-cancel later if needed.',
)
return lines.join('\n')
}
const RALPH_BLOCKED_TOOLS: Record<string, string> = {
question: 'The question tool is not available during a Ralph loop. Do not ask questions — continue working on the task autonomously.',
'memory-plan-execute': 'The memory-plan-execute tool is not available during a Ralph loop. Focus on executing the current plan.',
'memory-plan-ralph': 'The memory-plan-ralph tool is not available during a Ralph loop. Focus on executing the current plan.',
}
const PLAN_APPROVAL_LABELS = ['New session', 'Execute here', 'Ralph (worktree)', 'Ralph (in place)']
const PLAN_APPROVAL_DIRECTIVES: Record<string, string> = {
'New session': `<system-reminder>
The user selected "New session". You MUST now call memory-plan-execute in this response with:
- plan: The FULL self-contained implementation plan (the code agent starts with zero context)
- title: A short descriptive title for the session
- inPlace: false (or omit)
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)
- title: A short descriptive title for the session
- inPlace: true
Do NOT output text without also making this tool call.
</system-reminder>`,
'Ralph (worktree)': `<system-reminder>
The user selected "Ralph (worktree)". You MUST now call memory-plan-ralph in this response with:
- plan: The FULL self-contained implementation plan (Ralph runs in an isolated worktree with no prior context)
- title: A short descriptive title for the session
- inPlace: false (or omit)
Do NOT output text without also making this tool call.
</system-reminder>`,
'Ralph (in place)': `<system-reminder>
The user selected "Ralph (in place)". You MUST now call memory-plan-ralph in this response with:
- plan: The FULL self-contained implementation plan (Ralph runs in the current directory with no prior context)
- title: A short descriptive title for the session
- inPlace: true
Do NOT output text without also making this tool call.
</system-reminder>`,
}
return {
getCleanup,
tool: {
@@ -519,18 +759,54 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
},
}),
'memory-plan-execute': tool({
description: 'Create a new Code session and send the plan as the first prompt. Call this after the user approves the plan.',
description: 'Send the plan to the Code agent for execution. By default creates a new session. Set inPlace to true to switch to the code agent in the current session (plan is already in context).',
args: {
plan: z.string().describe('The full implementation plan to send to the Code agent'),
title: z.string().describe('Short title for the session (shown in session list)'),
inPlace: z.boolean().optional().default(false).describe('Execute in the current session as a subtask instead of creating a new session'),
},
execute: async (args) => {
logger.log(`memory-plan-execute: creating session titled "${args.title}"`)
execute: async (args, context) => {
logger.log(`memory-plan-execute: ${args.inPlace ? 'switching to code agent' : 'creating session'} titled "${args.title}"`)
const sessionTitle = args.title.length > 60 ? `${args.title.substring(0, 57)}...` : args.title
const executionModel = parseModelString(config.executionModel)
const createResult = await client.session.create({
body: { title: sessionTitle },
if (args.inPlace) {
const { result: promptResult, usedModel: actualModel } = await retryWithModelFallback(
() => v2.session.promptAsync({
sessionID: context.sessionID,
directory,
agent: 'code',
parts: [{ type: 'text' as const, text: args.plan }],
...(executionModel ? { model: executionModel } : {}),
}),
() => v2.session.promptAsync({
sessionID: context.sessionID,
directory,
agent: 'code',
parts: [{ type: 'text' as const, text: args.plan }],
}),
executionModel,
logger,
)
if (promptResult.error) {
logger.error(`memory-plan-execute: in-place agent switch failed`, promptResult.error)
return `Failed to switch to code agent. Error: ${JSON.stringify(promptResult.error)}`
}
const modelInfo = actualModel ? `${actualModel.providerID}/${actualModel.modelID}` : 'default'
return `Switching to code agent for execution.\n\nTitle: ${sessionTitle}\nModel: ${modelInfo}\nAgent: code`
}
const { cleaned: planText, stripped } = stripPromiseTags(args.plan)
if (stripped) {
logger.log(`memory-plan-execute: stripped <promise> tags from plan text`)
}
const createResult = await v2.session.create({
title: sessionTitle,
directory,
})
if (createResult.error || !createResult.data) {
@@ -541,16 +817,23 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
const newSessionId = createResult.data.id
logger.log(`memory-plan-execute: created session=${newSessionId}`)
const executionModel = parseModelString(config.executionModel)
const promptResult = await client.session.promptAsync({
path: { id: newSessionId },
body: {
parts: [{ type: 'text' as const, text: args.plan }],
const { result: promptResult, usedModel: actualModel } = await retryWithModelFallback(
() => v2.session.promptAsync({
sessionID: newSessionId,
directory,
parts: [{ type: 'text' as const, text: planText }],
agent: 'code',
...(executionModel && { model: executionModel }),
},
})
model: executionModel!,
}),
() => v2.session.promptAsync({
sessionID: newSessionId,
directory,
parts: [{ type: 'text' as const, text: planText }],
agent: 'code',
}),
executionModel,
logger,
)
if (promptResult.error) {
logger.error(`memory-plan-execute: failed to prompt session`, promptResult.error)
@@ -559,10 +842,42 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
logger.log(`memory-plan-execute: prompted session=${newSessionId}`)
const modelInfo = executionModel ? `${executionModel.providerID}/${executionModel.modelID}` : 'default'
const modelInfo = actualModel ? `${actualModel.providerID}/${actualModel.modelID}` : 'default'
return `Implementation session created and plan sent.\n\nSession: ${newSessionId}\nTitle: ${sessionTitle}\nModel: ${modelInfo}\n\nSwitch to this session to begin. You can change the model from the session dropdown.`
},
}),
'memory-plan-ralph': tool({
description: 'Execute a plan using a Ralph iterative development loop. By default runs in an isolated git worktree. Set inPlace to true to run in the current directory instead.',
args: {
plan: z.string().describe('The full implementation plan to send to the Code agent'),
title: z.string().describe('Short title for the session (shown in session list)'),
inPlace: z.boolean().optional().default(false).describe('Run in current directory instead of creating a worktree'),
},
execute: async (args, context) => {
if (config.ralph?.enabled === false) {
return 'Ralph loops are disabled in plugin config. Use memory-plan-execute instead.'
}
logger.log(`memory-plan-ralph: creating worktree for plan="${args.title}"`)
const sessionTitle = args.title.length > 60 ? `${args.title.substring(0, 57)}...` : args.title
const ralphModel = parseModelString(config.ralph?.model) ?? parseModelString(config.executionModel)
const audit = config.ralph?.defaultAudit ?? true
return setupRalphLoop({
prompt: args.plan,
sessionTitle: `Ralph: ${sessionTitle}`,
completionPromise: DEFAULT_PLAN_COMPLETION_PROMISE,
maxIterations: config.ralph?.defaultMaxIterations ?? 0,
audit: audit,
agent: 'code',
model: ralphModel,
inPlace: args.inPlace,
parentSessionId: context.sessionID,
onLoopStarted: (id) => ralphHandler.startWatchdog(id),
})
},
}),
'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.',
args: {
@@ -612,24 +927,414 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
}
const formatted = entries.map((e) => {
const expiresIn = Math.round((e.expiresAt - Date.now()) / 60000)
const dataPreview = typeof e.data === 'string' ? e.data.substring(0, 100) : JSON.stringify(e.data).substring(0, 100)
return `- **${e.key}** (expires in ${expiresIn}m)\n ${dataPreview}${dataPreview.length >= 100 ? '...' : ''}`
const dataStr = typeof e.data === 'string' ? e.data : JSON.stringify(e.data)
const preview = dataStr.substring(0, 50).replace(/\n/g, ' ')
return `- **${e.key}** (expires in ${expiresIn}m): ${preview}${dataStr.length > 50 ? '...' : ''}`
})
logger.log(`memory-kv-list: ${entries.length} entries`)
return `${entries.length} active KV entries:\n\n${formatted.join('\n')}`
},
}),
'ralph-cancel': tool({
description: 'Cancel an active Ralph loop and optionally clean up the worktree.',
args: {
name: z.string().optional().describe('Worktree name of the Ralph loop to cancel'),
},
execute: async (args) => {
let state: RalphState | null = null
if (args.name) {
state = ralphService.findByWorktreeName(args.name)
if (!state) {
return `No active Ralph loop found for worktree "${args.name}".`
}
} else {
const active = ralphService.listActive()
if (active.length === 0) return 'No active Ralph loops.'
if (active.length === 1) {
state = active[0]
} else {
return `Multiple active Ralph loops. Specify a name:\n${active.map((s) => `- ${s.worktreeName} (iteration ${s.iteration})`).join('\n')}`
}
}
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) {
try {
const gitCommonDir = execSync('git rev-parse --git-common-dir', { cwd: state.worktreeDir, encoding: 'utf-8' }).trim()
const gitRoot = resolve(state.worktreeDir, gitCommonDir, '..')
const removeResult = spawnSync('git', ['worktree', 'remove', '-f', state.worktreeDir], { cwd: gitRoot, encoding: 'utf-8' })
if (removeResult.status !== 0) {
throw new Error(removeResult.stderr || 'git worktree remove failed')
}
logger.log(`ralph-cancel: removed worktree ${state.worktreeDir}`)
} catch (err) {
logger.error(`ralph-cancel: failed to remove worktree`, err)
}
}
const modeInfo = state.inPlace ? ' (in-place)' : ''
return `Cancelled Ralph loop "${state.worktreeName}"${modeInfo} (was at iteration ${state.iteration}).\nDirectory: ${state.worktreeDir}\nBranch: ${state.worktreeBranch}`
},
}),
'ralph-status': tool({
description: 'Check the status of Ralph loops. With no arguments, lists all active loops for the current project. Pass a worktree name for detailed status of a specific loop. Use restart to resume an inactive loop.',
args: {
name: z.string().optional().describe('Worktree name to check for detailed status'),
restart: z.boolean().optional().describe('Restart an inactive loop by name'),
},
execute: async (args) => {
const active = ralphService.listActive()
if (args.restart) {
if (!args.name) {
return 'Specify a loop name to restart. Use ralph-status to see available loops.'
}
const recent = ralphService.listRecent()
const stoppedState = [...active, ...recent].find((s) => s.worktreeName === args.name)
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}`
}
if (stoppedState.active) {
return `Loop "${stoppedState.worktreeName}" is already active. Nothing to restart.`
}
if (stoppedState.terminationReason === 'completed') {
return `Loop "${stoppedState.worktreeName}" completed successfully and cannot be restarted.`
}
if (!stoppedState.inPlace) {
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,
})
if (createResult.error || !createResult.data) {
logger.error(`ralph-restart: failed to create session`, createResult.error)
return `Failed to create new session for restart.`
}
const newSessionId = createResult.data.id
ralphService.deleteState(stoppedState.sessionId)
const newState: RalphState = {
active: true,
sessionId: newSessionId,
worktreeName: stoppedState.worktreeName,
worktreeDir: stoppedState.worktreeDir,
worktreeBranch: stoppedState.worktreeBranch,
workspaceId: stoppedState.workspaceId,
iteration: stoppedState.iteration,
maxIterations: stoppedState.maxIterations,
completionPromise: stoppedState.completionPromise,
startedAt: new Date().toISOString(),
prompt: stoppedState.prompt,
phase: 'coding',
audit: stoppedState.audit,
errorCount: 0,
auditCount: 0,
parentSessionId: stoppedState.parentSessionId,
inPlace: stoppedState.inPlace,
}
ralphService.setState(newSessionId, newState)
let promptText = stoppedState.prompt
if (stoppedState.completionPromise) {
promptText += `\n\n---\n\n**IMPORTANT - Completion Signal:** When you have completed ALL phases of this plan successfully, you MUST output the following tag exactly: <promise>${stoppedState.completionPromise}</promise>\n\nDo NOT output this tag until every phase is truly complete. The loop will continue until this signal is detected.`
}
const ralphModel = parseModelString(config.ralph?.model) ?? parseModelString(config.executionModel)
const { result: promptResult } = await retryWithModelFallback(
() => v2.session.promptAsync({
sessionID: newSessionId,
directory: stoppedState.worktreeDir,
parts: [{ type: 'text' as const, text: promptText }],
agent: 'code',
model: ralphModel!,
}),
() => v2.session.promptAsync({
sessionID: newSessionId,
directory: stoppedState.worktreeDir,
parts: [{ type: 'text' as const, text: promptText }],
agent: 'code',
}),
ralphModel,
logger,
)
if (promptResult.error) {
logger.error(`ralph-restart: failed to send prompt`, promptResult.error)
ralphService.deleteState(newSessionId)
return `Restart failed: could not send prompt to new session.`
}
ralphHandler.startWatchdog(newSessionId)
const modeInfo = stoppedState.inPlace ? ' (in-place)' : ''
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}`,
`Audit: ${stoppedState.audit ? 'enabled' : 'disabled'}`,
].join('\n')
}
if (!args.name) {
const recent = ralphService.listRecent()
if (active.length === 0) {
if (recent.length === 0) return 'No Ralph loops found.'
const lines: string[] = ['Recently Completed Ralph Loops', '']
recent.forEach((s, i) => {
const duration = s.completedAt
? 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('')
})
lines.push('Use ralph-status <name> for detailed info.')
return lines.join('\n')
}
let statuses: Record<string, { type: string; attempt?: number; message?: string; next?: number }> = {}
try {
const statusResult = await v2.session.status()
statuses = (statusResult.data ?? {}) as typeof statuses
} catch {
}
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 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 sessionStatus = statuses[s.sessionId]?.type ?? 'unknown'
const modeIndicator = s.inPlace ? ' (in-place)' : ''
const stallInfo = ralphHandler.getStallInfo(s.sessionId)
const stallCount = stallInfo?.consecutiveStalls ?? 0
const stallSuffix = stallCount > 0 ? ` | Stalls: ${stallCount}` : ''
lines.push(`${i + 1}. ${s.worktreeName}${modeIndicator}`)
lines.push(` Phase: ${s.phase} | Iteration: ${iterInfo} | Duration: ${duration} | Status: ${sessionStatus}${stallSuffix}`)
lines.push('')
})
if (recent.length > 0) {
lines.push('Recently Completed:')
lines.push('')
recent.forEach((s, i) => {
const duration = s.completedAt
? 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('')
})
}
lines.push('Use ralph-status <name> for detailed info, or ralph-cancel <name> to stop a loop.')
return lines.join('\n')
}
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')
}
return `No Ralph loop found for worktree "${args.name}".`
}
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
let sessionStatus = 'unknown'
try {
const statusResult = await v2.session.status()
const statuses = statusResult.data as Record<string, { type: string; attempt?: number; message?: string; next?: number }> | undefined
const status = statuses?.[state.sessionId]
if (status) {
sessionStatus = status.type === 'retry'
? `retry (attempt ${status.attempt}, next in ${Math.round(((status.next ?? 0) - Date.now()) / 1000)}s)`
: status.type
}
} catch {
sessionStatus = 'unavailable'
}
const elapsed = Math.round((Date.now() - new Date(state.startedAt).getTime()) / 1000)
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 secondsSinceActivity = stallInfo
? Math.round((Date.now() - stallInfo.lastActivityTime) / 1000)
: null
const stallCount = stallInfo?.consecutiveStalls ?? 0
const statusLines: string[] = [
'Ralph Loop Status',
'',
`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(
`Status: ${sessionStatus}`,
`Phase: ${state.phase}`,
`Iteration: ${maxInfo}`,
`Duration: ${duration}`,
`Audit: ${state.audit ? 'enabled' : 'disabled'}`,
`Branch: ${state.worktreeBranch}`,
`Completion promise: ${state.completionPromise ?? 'none'}`,
`Started: ${state.startedAt}`,
...(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'}`,
...(stallCount > 0 ? [`Stalls: ${stallCount}`] : []),
...(secondsSinceActivity !== null ? [`Last activity: ${secondsSinceActivity}s ago`] : []),
'',
`Prompt: ${promptPreview}`,
)
return statusLines.join('\n')
},
}),
},
config: createConfigHandler(
config.auditorModel
? { ...agents, auditor: { ...agents.auditor, defaultModel: config.auditorModel } }
: agents
),
'chat.message': async (input, output) => {
await sessionHooks.onMessage(input, output)
},
config: createConfigHandler(agents),
'chat.message': sessionHooks.onMessage,
event: async (input) => {
const eventInput = input as { event: { type: string; properties?: Record<string, unknown> } }
if (eventInput.event?.type === 'server.instance.disposed') {
cleanup()
return
}
await ralphHandler.onEvent(eventInput)
await sessionHooks.onEvent(eventInput)
},
'tool.execute.before': async (
input: { tool: string; sessionID: string; callID: string },
output: { args: unknown }
) => {
const state = ralphService.getActiveState(input.sessionID)
if (!state?.active) return
if (!(input.tool in RALPH_BLOCKED_TOOLS)) return
logger.log(`Ralph: blocking ${input.tool} tool before execution in ${state.phase} phase for session ${input.sessionID}`)
throw new Error(RALPH_BLOCKED_TOOLS[input.tool]!)
},
'tool.execute.after': async (
input: { tool: string; sessionID: string; callID: string; args: unknown },
output: { title: string; output: string; metadata: unknown }
) => {
if (input.tool === 'question') {
const args = input.args as { questions?: Array<{ options?: Array<{ label: string }> }> } | undefined
const options = args?.questions?.[0]?.options
if (options) {
const labels = options.map((o) => o.label)
const isPlanApproval = PLAN_APPROVAL_LABELS.every((l) => labels.includes(l))
if (isPlanApproval) {
const answer = output.output.trim()
const matchedLabel = PLAN_APPROVAL_LABELS.find((l) => answer === l || answer.startsWith(l))
const directive = matchedLabel ? PLAN_APPROVAL_DIRECTIVES[matchedLabel] : '<system-reminder>\nThe user cancelled or provided a custom response. Do NOT call memory-plan-execute or memory-plan-ralph.\n</system-reminder>'
output.output = `${output.output}\n\n${directive}`
logger.log(`Plan approval: detected "${matchedLabel ?? 'cancel/custom'}" answer, injected directive`)
}
}
return
}
const state = ralphService.getActiveState(input.sessionID)
if (!state?.active) return
if (!(input.tool in RALPH_BLOCKED_TOOLS)) return
logger.log(`Ralph: blocked ${input.tool} tool in ${state.phase} phase for session ${input.sessionID}`)
output.title = 'Tool blocked'
output.output = RALPH_BLOCKED_TOOLS[input.tool]!
},
'permission.ask': async (input, output) => {
const req = input as unknown as { sessionID: string; patterns: string[] }
const state = ralphService.getActiveState(req.sessionID)
if (!state?.active) return
if (req.patterns.some((p) => p.startsWith('git push'))) {
logger.log(`Ralph: denied git push for session ${req.sessionID}`)
output.status = 'deny'
return
}
},
'experimental.session.compacting': async (input, output) => {
logger.log(`Compacting triggered`)
await sessionHooks.onCompacting(
@@ -695,9 +1400,9 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
text: `<system-reminder>
Plan mode is active. You MUST NOT make any file edits, run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supersedes any other instructions you have received.
You may ONLY: observe, analyze, plan, and use memory tools (memory-read, memory-write, memory-edit, memory-delete, memory-kv-set, memory-kv-get, memory-kv-list), and mcp_question.
You may ONLY: observe, analyze, plan, and use memory tools (memory-read, memory-write, memory-edit, memory-delete, memory-kv-set, memory-kv-get, memory-kv-list), mcp_question, memory-plan-execute, and memory-plan-ralph.
You MUST get explicit approval via mcp_question before calling memory-plan-execute. Never execute a plan without approval.
You MUST get explicit approval via mcp_question before calling memory-plan-execute or memory-plan-ralph. Never execute a plan without approval.
</system-reminder>`,
synthetic: true,
})
+18 -1
View File
@@ -16,11 +16,11 @@ export interface KvService {
set<T = unknown>(projectId: string, key: string, data: T, ttlMs?: number): void
delete(projectId: string, key: string): void
list(projectId: string): KvEntry[]
listByPrefix(projectId: string, prefix: string): KvEntry[]
}
export function createKvService(db: Database, logger?: Logger): KvService {
const queries = createKvQuery(db)
queries.deleteExpired()
return {
get<T = unknown>(projectId: string, key: string): T | null {
@@ -59,5 +59,22 @@ export function createKvService(db: Database, logger?: Logger): KvService {
}
})
},
listByPrefix(projectId: string, prefix: string): KvEntry[] {
const rows = queries.listByPrefix(projectId, prefix)
return rows.map((row) => {
let data: unknown = null
try {
data = JSON.parse(row.data)
} catch {
}
return {
key: row.key,
data,
updatedAt: row.updatedAt,
expiresAt: row.expiresAt,
}
})
},
}
}
+188
View File
@@ -0,0 +1,188 @@
import type { KvService } from './kv'
import type { Logger, RalphConfig } from '../types'
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 interface RalphState {
active: boolean
sessionId: string
worktreeName: string
worktreeDir: string
worktreeBranch: string
workspaceId: string
iteration: number
maxIterations: number
completionPromise: string | null
startedAt: string
prompt: string
phase: 'coding' | 'auditing'
audit: boolean
lastAuditResult?: string
errorCount: number
auditCount: number
terminationReason?: string
completedAt?: string
parentSessionId?: string
inPlace?: boolean
}
export interface RalphService {
getActiveState(sessionId: string): RalphState | null
getAnyState(sessionId: string): RalphState | null
setState(sessionId: string, state: RalphState): void
deleteState(sessionId: string): void
checkCompletionPromise(text: string, promise: string): boolean
buildContinuationPrompt(state: RalphState, auditFindings?: string): string
buildAuditPrompt(state: RalphState): string
listActive(): RalphState[]
listRecent(): RalphState[]
findByWorktreeName(name: string): RalphState | null
findByParentSessionId(parentId: string): RalphState[]
getStallTimeoutMs(): number
getMinAudits(): number
terminateAll(): void
}
export function createRalphService(
kvService: KvService,
projectId: string,
logger: Logger,
ralphConfig?: RalphConfig,
): RalphService {
const stateKey = (sessionId: string) => `ralph:${sessionId}`
function getAnyState(sessionId: string): RalphState | null {
return kvService.get<RalphState>(projectId, stateKey(sessionId))
}
function getActiveState(sessionId: string): RalphState | null {
const state = kvService.get<RalphState>(projectId, stateKey(sessionId))
if (!state || !state.active) {
return null
}
return state
}
function setState(sessionId: string, state: RalphState): void {
kvService.set(projectId, stateKey(sessionId), state)
}
function deleteState(sessionId: string): void {
kvService.delete(projectId, stateKey(sessionId))
}
function checkCompletionPromise(text: string, promise: string): boolean {
const match = text.match(/<promise>([\s\S]*?)<\/promise>/)
if (!match) {
return false
}
const extracted = match[1].trim().replace(/\s+/g, ' ')
return extracted === promise
}
function buildContinuationPrompt(state: RalphState, auditFindings?: string): string {
let systemLine = `Ralph iteration ${state.iteration}`
if (state.completionPromise) {
systemLine += ` | To stop: output <promise>${state.completionPromise}</promise> (ONLY when all requirements are met)`
} else if (state.maxIterations > 0) {
systemLine += ` / ${state.maxIterations}`
} else {
systemLine += ` | No completion promise set - loop runs until cancelled`
}
let prompt = `[${systemLine}]\n\n${state.prompt}`
if (auditFindings) {
const completionInstruction = state.completionPromise
? '\n\nAfter fixing all issues, output the completion signal.'
: ''
prompt += `\n\n---\nThe code auditor reviewed your changes. You MUST address all bugs and convention violations below — do not dismiss findings as unrelated to the task. Fix them directly without creating a plan or asking for approval.\n\n${auditFindings}${completionInstruction}`
}
return prompt
}
function buildAuditPrompt(state: RalphState): string {
const taskSummary = state.prompt.length > 200
? `${state.prompt.substring(0, 197)}...`
: state.prompt
return [
`Post-iteration ${state.iteration} code review (branch: ${state.worktreeBranch}).`,
'',
`Task context: ${taskSummary}`,
'',
'Review the code changes in this worktree. Focus on bugs, logic errors, missing error handling, and convention violations.',
'If you find bugs in related code that affect the correctness of this task, report them — even if the buggy code was not directly modified.',
'If everything looks good, state "No issues found." clearly.',
'',
'This is an automated loop — do not direct the agent to "create a plan" or "present for approval." Just report findings directly.',
].join('\n')
}
function listActive(): RalphState[] {
const entries = kvService.listByPrefix(projectId, 'ralph:')
return entries
.map((entry) => entry.data as RalphState)
.filter((state): state is RalphState => state !== null && state.active)
}
function listRecent(): RalphState[] {
const entries = kvService.listByPrefix(projectId, 'ralph:')
return entries
.map((entry) => entry.data as RalphState)
.filter((state): state is RalphState => state !== null && !state.active)
}
function findByWorktreeName(name: string): RalphState | null {
const active = listActive()
return active.find((s) => s.worktreeName === name) ?? null
}
function findByParentSessionId(parentId: string): RalphState[] {
return listActive().filter((s) => s.parentSessionId === parentId)
}
function getStallTimeoutMs(): number {
return ralphConfig?.stallTimeoutMs ?? STALL_TIMEOUT_MS
}
function getMinAudits(): number {
return ralphConfig?.minAudits ?? DEFAULT_MIN_AUDITS
}
function terminateAll(): void {
const active = listActive()
for (const state of active) {
const updated: RalphState = {
...state,
active: false,
completedAt: new Date().toISOString(),
terminationReason: 'shutdown',
}
setState(state.sessionId, updated)
}
logger.log(`Ralph: terminated ${active.length} active loop(s)`)
}
return {
getActiveState,
getAnyState,
setState,
deleteState,
checkCompletionPromise,
buildContinuationPrompt,
buildAuditPrompt,
listActive,
listRecent,
findByWorktreeName,
findByParentSessionId,
getStallTimeoutMs,
getMinAudits,
terminateAll,
}
}
+44 -19
View File
@@ -1,37 +1,53 @@
import { readFileSync, existsSync, mkdirSync, copyFileSync } from 'fs'
import { dirname, join } from 'path'
import { fileURLToPath } from 'url'
import { homedir, platform } from 'os'
import { resolveDataDir, resolveLogPath } from './storage'
import type { PluginConfig, EmbeddingConfig } from './types'
import { parse as parseJsoncLib, type ParseError } from 'jsonc-parser'
function resolveBundledConfigPath(): string {
const pluginDir = dirname(fileURLToPath(import.meta.url))
return join(pluginDir, '..', 'config.json')
return join(pluginDir, '..', 'config.jsonc')
}
function resolveConfigDir(): string {
const defaultBase = join(homedir(), platform() === 'win32' ? 'AppData' : '.config')
const xdgConfigHome = process.env['XDG_CONFIG_HOME'] || defaultBase
return join(xdgConfigHome, 'opencode')
}
export function resolveConfigPath(): string {
return join(resolveConfigDir(), 'memory-config.jsonc')
}
function resolveOldConfigPath(): string {
const dataDir = resolveDataDir()
return `${dataDir}/config.json`
return join(dataDir, 'config.json')
}
function ensureGlobalConfig(): void {
const dataDir = resolveDataDir()
const globalConfigPath = resolveConfigPath()
const configDir = resolveConfigDir()
const newConfigPath = resolveConfigPath()
if (existsSync(globalConfigPath)) {
if (existsSync(newConfigPath)) {
return
}
if (!existsSync(configDir)) {
mkdirSync(configDir, { recursive: true })
}
const oldConfigPath = resolveOldConfigPath()
if (existsSync(oldConfigPath)) {
copyFileSync(oldConfigPath, newConfigPath)
return
}
const bundledConfigPath = resolveBundledConfigPath()
if (!existsSync(bundledConfigPath)) {
return
if (existsSync(bundledConfigPath)) {
copyFileSync(bundledConfigPath, newConfigPath)
}
if (!existsSync(dataDir)) {
mkdirSync(dataDir, { recursive: true })
}
copyFileSync(bundledConfigPath, globalConfigPath)
}
function getDefaultEmbeddingConfig(): EmbeddingConfig {
@@ -72,6 +88,18 @@ function isValidPluginConfig(config: unknown): config is PluginConfig {
return true
}
function parseJsonc<T = unknown>(content: string): T {
const errors: ParseError[] = []
const result = parseJsoncLib(content, errors, {
allowTrailingComma: true,
disallowComments: false,
})
if (errors.length > 0) {
throw new SyntaxError(`Invalid JSONC at offset ${errors[0]!.offset}`)
}
return result as T
}
export function loadPluginConfig(): PluginConfig {
ensureGlobalConfig()
@@ -83,8 +111,7 @@ export function loadPluginConfig(): PluginConfig {
try {
const content = readFileSync(configPath, 'utf-8')
const sanitized = sanitizeJson(content)
const parsed = JSON.parse(sanitized)
const parsed = parseJsonc(content)
if (!isValidPluginConfig(parsed)) {
console.warn(`[memory] Invalid config at ${configPath}, using defaults`)
@@ -99,10 +126,6 @@ export function loadPluginConfig(): PluginConfig {
}
}
function sanitizeJson(raw: string): string {
return raw.replace(/,(\s*[}\]])/g, '$1')
}
function normalizeConfig(config: PluginConfig): PluginConfig {
const normalized: PluginConfig = {
dataDir: config.dataDir,
@@ -113,6 +136,8 @@ function normalizeConfig(config: PluginConfig): PluginConfig {
memoryInjection: config.memoryInjection,
messagesTransform: config.messagesTransform,
executionModel: config.executionModel,
auditorModel: config.auditorModel,
ralph: config.ralph,
}
if (normalized.embedding) {
+1 -1
View File
@@ -1,5 +1,5 @@
export { initializeDatabase, closeDatabase, resolveDataDir, resolveLogPath } from './database'
export { createVecService } from './vec'
export { createVecService, cleanupOrphanedWorkers } from './vec'
export type { VecService, VecSearchResult, TableDimensionsResult } from './vec-types'
export { createMemoryQuery } from './memory-queries'
export { createMetadataQuery } from './metadata-queries'
+26
View File
@@ -29,6 +29,9 @@ function mapRow(row: KvRowRaw): KvRow {
}
}
const CLEANUP_INTERVAL_MS = 300_000
let lastCleanupAt = 0
export function createKvQuery(db: Database) {
const getStmt = db.prepare(
`SELECT project_id, key, data, expires_at, created_at, updated_at
@@ -54,6 +57,13 @@ export function createKvQuery(db: Database) {
ORDER BY updated_at DESC`
)
const listByPrefixStmt = db.prepare(
`SELECT project_id, key, data, expires_at, created_at, updated_at
FROM project_kv
WHERE project_id = ? AND key LIKE ? AND expires_at > ?
ORDER BY updated_at DESC`
)
const deleteExpiredStmt = db.prepare(
`DELETE FROM project_kv WHERE expires_at < ?`
)
@@ -67,6 +77,17 @@ export function createKvQuery(db: Database) {
set(projectId: string, key: string, data: string, expiresAt: number): void {
const now = Date.now()
setStmt.run(projectId, key, data, expiresAt, now, now)
if (now - lastCleanupAt > CLEANUP_INTERVAL_MS) {
lastCleanupAt = now
setImmediate(() => {
try {
deleteExpiredStmt.run(now)
} catch {
// Ignore errors from cleanup (e.g., if db is closed)
}
})
}
},
delete(projectId: string, key: string): void {
@@ -78,6 +99,11 @@ export function createKvQuery(db: Database) {
return rows.map(mapRow)
},
listByPrefix(projectId: string, prefix: string): KvRow[] {
const rows = listByPrefixStmt.all(projectId, `${prefix}%`, Date.now()) as KvRowRaw[]
return rows.map(mapRow)
},
deleteExpired(): number {
const result = deleteExpiredStmt.run(Date.now())
return result.changes
+38 -4
View File
@@ -47,12 +47,13 @@ function sendRequest(socketPath: string, request: Record<string, unknown>): Prom
})
}
function isWorkerRunning(pidPath: string, socketPath: string): boolean {
async function isWorkerRunning(pidPath: string, socketPath: string): Promise<boolean> {
if (!existsSync(pidPath) || !existsSync(socketPath)) return false
try {
const pid = parseInt(readFileSync(pidPath, 'utf-8'), 10)
process.kill(pid, 0)
return true
const response = await sendRequest(socketPath, { action: 'health' })
return response.status === 'ok'
} catch {
return false
}
@@ -70,6 +71,33 @@ function cleanupStale(pidPath: string, socketPath: string): void {
} catch {}
}
export function cleanupOrphanedWorkers(pidPath: string, socketPath: string): void {
if (existsSync(socketPath) && !existsSync(pidPath)) {
try {
unlinkSync(socketPath)
} catch {}
}
if (existsSync(pidPath)) {
try {
const pid = parseInt(readFileSync(pidPath, 'utf-8'), 10)
try {
process.kill(pid, 0)
if (!existsSync(socketPath)) {
try {
process.kill(pid, 'SIGTERM')
} catch {}
}
} catch {
unlinkSync(pidPath)
if (existsSync(socketPath)) {
unlinkSync(socketPath)
}
}
} catch {}
}
}
async function startWorker(config: {
dbPath: string
dataDir: string
@@ -78,11 +106,17 @@ async function startWorker(config: {
const socketPath = join(config.dataDir, 'vec-worker.sock')
const pidPath = join(config.dataDir, 'vec-worker.pid')
if (isWorkerRunning(pidPath, socketPath)) {
cleanupOrphanedWorkers(pidPath, socketPath)
if (await isWorkerRunning(pidPath, socketPath)) {
return socketPath
}
cleanupStale(pidPath, socketPath)
if (existsSync(socketPath)) {
try {
unlinkSync(socketPath)
} catch {}
}
const workerScriptJs = join(__dirname, 'vec-worker.js')
const workerScript = existsSync(workerScriptJs)
+2
View File
@@ -2,8 +2,10 @@ import type { Database } from 'bun:sqlite'
import { join } from 'path'
import type { VecService } from './vec-types'
import type { Logger } from '../types'
import { cleanupOrphanedWorkers } from './vec-client'
export type { VecService, VecSearchResult } from './vec-types'
export { cleanupOrphanedWorkers }
export async function createVecService(_db: Database, dataDir: string, dimensions: number, logger?: Logger): Promise<VecService> {
try {
+12
View File
@@ -59,6 +59,16 @@ export interface Logger {
debug: (message: string, ...args: unknown[]) => void
}
export interface RalphConfig {
enabled?: boolean
defaultMaxIterations?: number
cleanupWorktree?: boolean
defaultAudit?: boolean
model?: string
stallTimeoutMs?: number
minAudits?: number
}
export interface PluginConfig {
dataDir?: string
embedding: EmbeddingConfig
@@ -68,6 +78,8 @@ export interface PluginConfig {
memoryInjection?: MemoryInjectionConfig
messagesTransform?: MessagesTransformConfig
executionModel?: string
auditorModel?: string
ralph?: RalphConfig
}
export interface ListMemoriesFilter {
+10
View File
@@ -5,6 +5,16 @@ import type { LoggingConfig } from '../types'
const PREFIX = '[OpenCodeManagerMemory]'
const MAX_LOG_FILE_SIZE = 10 * 1024 * 1024
export function slugify(text: string): string {
return text
.toLowerCase()
.replace(/[^\w\s-]/g, '')
.trim()
.replace(/\s+/g, '-')
.replace(/-+/g, '-')
.substring(0, 50)
}
function ensureLogDir(filePath: string): void {
const dir = dirname(filePath)
if (!existsSync(dir)) {
@@ -0,0 +1,38 @@
export function parseModelString(modelStr?: string): { providerID: string; modelID: string } | undefined {
if (!modelStr) return undefined
const slashIndex = modelStr.indexOf('/')
if (slashIndex <= 0 || slashIndex === modelStr.length - 1) return undefined
return {
providerID: modelStr.substring(0, slashIndex),
modelID: modelStr.substring(slashIndex + 1),
}
}
export async function retryWithModelFallback<T>(
callWithModel: () => Promise<{ data?: T; error?: unknown }>,
callWithoutModel: () => Promise<{ data?: T; error?: unknown }>,
model: { providerID: string; modelID: string } | undefined,
logger: { error: (msg: string, err?: unknown) => void; log: (msg: string) => void },
maxRetries: number = 2
): Promise<{ result: { data?: T; error?: unknown }; usedModel: { providerID: string; modelID: string } | undefined }> {
if (!model) {
return { result: await callWithoutModel(), usedModel: undefined }
}
let lastError: unknown
for (let attempt = 1; attempt <= maxRetries; attempt++) {
const result = await callWithModel()
if (!result.error) {
return { result, usedModel: model }
}
lastError = result.error
if (attempt < maxRetries) {
logger.log(`model attempt ${attempt}/${maxRetries} failed, retrying`)
} else {
logger.log(`model attempt ${attempt}/${maxRetries} failed`)
}
}
logger.error(`configured model unavailable after ${maxRetries} attempts, falling back to default`, lastError)
return { result: await callWithoutModel(), usedModel: undefined }
}
@@ -0,0 +1,6 @@
export function stripPromiseTags(text: string): { cleaned: string; stripped: boolean } {
let cleaned = text.replace(/\n*---\n\n\*\*IMPORTANT - Completion Signal:\*\*[\s\S]*?<promise>[\s\S]*?<\/promise>[\s\S]*?(?:until this signal is detected\.|$)/g, '')
cleaned = cleaned.replace(/<promise>[\s\S]*?<\/promise>/g, '')
cleaned = cleaned.trimEnd()
return { cleaned, stripped: cleaned !== text.trimEnd() }
}
+1 -1
View File
@@ -1 +1 @@
export const VERSION = '0.0.18'
export const VERSION = '0.0.20'