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

+1 -1
View File
@@ -101,7 +101,7 @@ RUN cd /opt/opencode-plugins/src && npm install
RUN mkdir -p /opt/opencode-plugins/node_modules/@opencode-manager/memory && \
cp -r /opt/opencode-plugins/src/dist/* /opt/opencode-plugins/node_modules/@opencode-manager/memory/ && \
cp /opt/opencode-plugins/src/package.json /opt/opencode-plugins/node_modules/@opencode-manager/memory/ && \
cp /opt/opencode-plugins/src/config.json /opt/opencode-plugins/node_modules/@opencode-manager/memory/config.json 2>/dev/null || true && \
cp /opt/opencode-plugins/src/config.jsonc /opt/opencode-plugins/node_modules/@opencode-manager/memory/config.jsonc 2>/dev/null || true && \
cp -r /opt/opencode-plugins/src/node_modules/* /opt/opencode-plugins/node_modules/ 2>/dev/null || true
COPY scripts/docker-entrypoint.sh /docker-entrypoint.sh
+255 -67
View File
@@ -1,17 +1,21 @@
import { Hono } from 'hono'
import { Database } from 'bun:sqlite'
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs'
import { readFileSync, writeFileSync, existsSync, mkdirSync, copyFileSync } from 'fs'
import { join } from 'path'
import { logger } from '../utils/logger'
import { PluginMemoryService } from '../services/plugin-memory'
import { resolveProjectId } from '../services/project-id-resolver'
import { getRepoById } from '../db/queries'
import { getWorkspacePath } from '@opencode-manager/shared/config/env'
import { getWorkspacePath, getConfigPath } from '@opencode-manager/shared/config/env'
import { parseJsonc } from '@opencode-manager/shared/utils'
import {
CreateMemoryRequestSchema,
UpdateMemoryRequestSchema,
MemoryListQuerySchema,
KvListQuerySchema,
PluginConfigSchema,
CreateKvEntryRequestSchema,
UpdateKvEntryRequestSchema,
type PluginConfig,
} from '@opencode-manager/shared/schemas'
@@ -20,6 +24,10 @@ function resolveMemoryDataDir(): string {
}
function resolvePluginConfigPath(): string {
return join(getConfigPath(), 'memory-config.jsonc')
}
function resolveOldPluginConfigPath(): string {
return join(resolveMemoryDataDir(), 'config.json')
}
@@ -36,21 +44,30 @@ function getDefaultPluginConfig(): PluginConfig {
function loadPluginConfigFromDisk(): PluginConfig {
const configPath = resolvePluginConfigPath()
if (!existsSync(configPath)) {
return getDefaultPluginConfig()
const oldPath = resolveOldPluginConfigPath()
if (existsSync(oldPath)) {
const configDir = getConfigPath()
if (!existsSync(configDir)) {
mkdirSync(configDir, { recursive: true })
}
copyFileSync(oldPath, configPath)
} else {
return getDefaultPluginConfig()
}
}
try {
const content = readFileSync(configPath, 'utf-8')
const parsed = JSON.parse(content)
const parsed = parseJsonc(content)
const result = PluginConfigSchema.safeParse(parsed)
if (!result.success) {
logger.error('Invalid plugin config:', result.error)
return getDefaultPluginConfig()
}
return result.data
} catch (error) {
logger.error('Failed to load plugin config:', error)
@@ -60,13 +77,58 @@ function loadPluginConfigFromDisk(): PluginConfig {
function savePluginConfigToDisk(config: PluginConfig): void {
const configPath = resolvePluginConfigPath()
const dataDir = resolveMemoryDataDir()
if (!existsSync(dataDir)) {
mkdirSync(dataDir, { recursive: true })
const configDir = getConfigPath()
if (!existsSync(configDir)) {
mkdirSync(configDir, { recursive: true })
}
// Read existing content to preserve comments
let existingContent = ''
if (existsSync(configPath)) {
try {
existingContent = readFileSync(configPath, 'utf-8')
} catch {
// File doesn't exist or can't be read, will create new
}
}
// If we have existing content, preserve comments by extracting them
// and re-adding them to the new content
if (existingContent) {
// Extract comments from existing content
const lines = existingContent.split('\n')
const commentLines: string[] = []
for (const line of lines) {
const trimmed = line.trim()
if (trimmed.startsWith('//')) {
commentLines.push(line.match(/\/\/\s*(.*)/)?.[1] || '')
}
}
// Create new JSON string
const newContent = JSON.stringify(config, null, 2)
// If we found comments, try to preserve them
if (commentLines.length > 0) {
const newLines = newContent.split('\n')
const result: string[] = []
// Add comments at the beginning
for (const comment of commentLines) {
result.push(`// ${comment}`)
}
result.push(...newLines)
writeFileSync(configPath, result.join('\n'), 'utf-8')
return
}
writeFileSync(configPath, newContent, 'utf-8')
} else {
writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8')
}
writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8')
}
export function createMemoryRoutes(db: Database): Hono {
@@ -153,8 +215,9 @@ export function createMemoryRoutes(db: Database): Hono {
}
const stats = pluginMemory.getStats(projectId)
const kvCount = pluginMemory.getKvCount(projectId)
return c.json({ projectId, stats })
return c.json({ projectId, stats, kvCount })
} catch (error) {
logger.error('Failed to get project summary:', error)
return c.json({ projectId: null, stats: { total: 0, byScope: {} }, error: 'Failed to get project summary' }, 500)
@@ -334,6 +397,183 @@ export function createMemoryRoutes(db: Database): Hono {
}
})
app.post('/reindex', async (c) => {
try {
const db = pluginMemory.getDb()
if (!db) {
return c.json({
error: 'Memory database not found. Make sure the memory plugin has been initialized.',
total: 0,
embedded: 0,
failed: 0
}, 404)
}
const memories = pluginMemory.listAll()
if (memories.length === 0) {
return c.json({
success: true,
message: 'No memories to reindex',
total: 0,
embedded: 0,
failed: 0
})
}
try {
db.exec('DELETE FROM memory_embeddings')
} catch {
return c.json({
success: true,
message: 'Cleared embeddings. Server restart required to regenerate embeddings with new model.',
total: memories.length,
embedded: 0,
failed: 0,
requiresRestart: true
})
}
return c.json({
success: true,
message: `Cleared ${memories.length} embeddings. Server restart required to regenerate embeddings.`,
total: memories.length,
embedded: 0,
failed: 0,
requiresRestart: true
})
} catch (error) {
logger.error('Failed to reindex memories:', error)
return c.json({ error: 'Failed to reindex memories', details: error instanceof Error ? error.message : 'Unknown error' }, 500)
}
})
app.get('/kv', async (c) => {
const query = c.req.query()
const parsed = KvListQuerySchema.safeParse({
projectId: query.projectId,
prefix: query.prefix,
})
if (!parsed.success) {
return c.json({ error: 'Invalid query parameters', details: parsed.error }, 400)
}
const { projectId, prefix } = parsed.data
const entries = pluginMemory.listKv(projectId, prefix)
return c.json({ entries })
})
app.post('/kv', async (c) => {
const body = await c.req.json()
const parsed = CreateKvEntryRequestSchema.safeParse(body)
if (!parsed.success) {
return c.json({ error: 'Invalid request', details: parsed.error }, 400)
}
try {
pluginMemory.setKv(parsed.data.projectId, parsed.data.key, parsed.data.data, parsed.data.ttlMs)
const entry = pluginMemory.getKv(parsed.data.projectId, parsed.data.key)
return c.json({ entry }, 201)
} catch (error) {
logger.error('Failed to create KV entry:', error)
return c.json({ error: 'Failed to create KV entry' }, 500)
}
})
app.put('/kv/:key', async (c) => {
const key = decodeURIComponent(c.req.param('key'))
const projectId = c.req.query('projectId')
if (!projectId) {
return c.json({ error: 'Missing projectId parameter' }, 400)
}
const body = await c.req.json()
const parsed = UpdateKvEntryRequestSchema.safeParse(body)
if (!parsed.success) {
return c.json({ error: 'Invalid request', details: parsed.error }, 400)
}
try {
pluginMemory.setKv(projectId, key, parsed.data.data, parsed.data.ttlMs)
const entry = pluginMemory.getKv(projectId, key)
return c.json({ entry })
} catch (error) {
logger.error('Failed to update KV entry:', error)
return c.json({ error: 'Failed to update KV entry' }, 500)
}
})
app.delete('/kv/:key', async (c) => {
const key = decodeURIComponent(c.req.param('key'))
const projectId = c.req.query('projectId')
if (!projectId) {
return c.json({ error: 'Missing projectId parameter' }, 400)
}
try {
pluginMemory.deleteKv(projectId, key)
return c.json({ success: true })
} catch (error) {
logger.error('Failed to delete KV entry:', error)
return c.json({ error: 'Failed to delete KV entry' }, 500)
}
})
app.post('/ralph/cancel', async (c) => {
try {
const body = await c.req.json()
const { repoId, sessionId } = body
if (!repoId || !sessionId) {
return c.json({ error: 'Missing repoId or sessionId' }, 400)
}
const repo = getRepoById(db, parseInt(repoId, 10))
if (!repo) {
return c.json({ cancelled: false })
}
const projectId = await resolveProjectId(repo.fullPath)
if (!projectId) {
return c.json({ cancelled: false })
}
const kvEntry = pluginMemory.getKv(projectId, `ralph:${sessionId}`)
if (!kvEntry) {
return c.json({ cancelled: false })
}
const state = kvEntry.data as { active?: boolean; worktreeName?: string } | undefined
if (!state?.active) {
return c.json({ cancelled: false })
}
const updatedState = {
...state,
active: false,
terminationReason: 'cancelled',
completedAt: new Date().toISOString(),
}
pluginMemory.setKv(projectId, `ralph:${sessionId}`, updatedState)
return c.json({ cancelled: true, worktreeName: state.worktreeName })
} catch (error) {
logger.error('Failed to cancel Ralph loop:', error)
return c.json({ error: 'Failed to cancel Ralph loop' }, 500)
}
})
app.get('/:id', async (c) => {
const id = parseInt(c.req.param('id'), 10)
@@ -390,57 +630,5 @@ export function createMemoryRoutes(db: Database): Hono {
}
})
app.post('/reindex', async (c) => {
try {
const db = pluginMemory.getDb()
if (!db) {
return c.json({
error: 'Memory database not found. Make sure the memory plugin has been initialized.',
total: 0,
embedded: 0,
failed: 0
}, 404)
}
const memories = pluginMemory.listAll()
if (memories.length === 0) {
return c.json({
success: true,
message: 'No memories to reindex',
total: 0,
embedded: 0,
failed: 0
})
}
try {
db.exec('DELETE FROM memory_embeddings')
} catch {
return c.json({
success: true,
message: 'Cleared embeddings. Server restart required to regenerate embeddings with new model.',
total: memories.length,
embedded: 0,
failed: 0,
requiresRestart: true
})
}
return c.json({
success: true,
message: `Cleared ${memories.length} embeddings. Server restart required to regenerate embeddings.`,
total: memories.length,
embedded: 0,
failed: 0,
requiresRestart: true
})
} catch (error) {
logger.error('Failed to reindex memories:', error)
return c.json({ error: 'Failed to reindex memories', details: error instanceof Error ? error.message : 'Unknown error' }, 500)
}
})
return app
}
+92
View File
@@ -27,6 +27,15 @@ interface DbMemoryRow {
updated_at: number
}
interface DbKvRow {
project_id: string
key: string
data: string
expires_at: number
created_at: number
updated_at: number
}
interface MemoryFilters {
scope?: 'convention' | 'decision' | 'context'
content?: string
@@ -52,6 +61,22 @@ function mapRowToMemory(row: DbMemoryRow): PluginMemory {
}
}
function mapRowToKvEntry(row: DbKvRow): { key: string; data: unknown; createdAt: number; updatedAt: number; expiresAt: number } {
let data: unknown = null
try {
data = JSON.parse(row.data)
} catch {
data = row.data
}
return {
key: row.key,
data,
createdAt: row.created_at,
updatedAt: row.updated_at,
expiresAt: row.expires_at,
}
}
export class PluginMemoryService {
private db: Database | null = null
@@ -233,6 +258,73 @@ export class PluginMemoryService {
return { projectId, total, byScope }
}
listKv(projectId: string, prefix?: string): { key: string; data: unknown; createdAt: number; updatedAt: number; expiresAt: number }[] {
const db = this.getDb()
if (!db) return []
const now = Date.now()
let sql = 'SELECT project_id, key, data, expires_at, created_at, updated_at FROM project_kv WHERE project_id = ? AND expires_at > ?'
const params: (string | number)[] = [projectId, now]
if (prefix) {
sql += ' AND key LIKE ?'
params.push(`${prefix}%`)
}
sql += ' ORDER BY updated_at DESC'
const stmt = db.prepare(sql)
const rows = stmt.all(...params) as DbKvRow[]
return rows.map(mapRowToKvEntry)
}
getKv(projectId: string, key: string): { key: string; data: unknown; createdAt: number; updatedAt: number; expiresAt: number } | undefined {
const db = this.getDb()
if (!db) return undefined
const stmt = db.prepare(
'SELECT project_id, key, data, expires_at, created_at, updated_at FROM project_kv WHERE project_id = ? AND key = ? AND expires_at > ?'
)
const row = stmt.get(projectId, key, Date.now()) as DbKvRow | undefined
return row ? mapRowToKvEntry(row) : undefined
}
setKv(projectId: string, key: string, data: unknown, ttlMs?: number): void {
const db = this.getDb()
if (!db) throw new Error('Plugin database not available')
const now = Date.now()
const expiresAt = ttlMs ? now + ttlMs : Number.MAX_SAFE_INTEGER
const serializedData = JSON.stringify(data)
const stmt = db.prepare(`
INSERT INTO project_kv (project_id, key, data, expires_at, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(project_id, key) DO UPDATE SET
data = excluded.data,
expires_at = excluded.expires_at,
updated_at = excluded.updated_at
`)
stmt.run(projectId, key, serializedData, expiresAt, now, now)
}
deleteKv(projectId: string, key: string): void {
const db = this.getDb()
if (!db) throw new Error('Plugin database not available')
const stmt = db.prepare('DELETE FROM project_kv WHERE project_id = ? AND key = ?')
stmt.run(projectId, key)
}
getKvCount(projectId: string): number {
const db = this.getDb()
if (!db) return 0
const stmt = db.prepare('SELECT COUNT(*) as count FROM project_kv WHERE project_id = ? AND expires_at > ?')
const result = stmt.get(projectId, Date.now()) as { count: number }
return result.count
}
close(): void {
if (this.db) {
this.db.close()
+198 -37
View File
@@ -32,12 +32,14 @@ Then register the plugin in your `opencode.json`:
## Configuration
On first run, the plugin copies a bundled `config.json` to the global data directory:
On first run, the plugin copies a bundled `config.jsonc` to the global config directory:
- `~/.local/share/opencode/memory/config.json`
- Falls back to `$XDG_DATA_HOME/opencode/memory/config.json`
- `~/.config/opencode/memory-config.jsonc`
- Falls back to: `$XDG_CONFIG_HOME/opencode/memory-config.jsonc`
The file is only created if it does not already exist. The config is validated on load — if it fails validation, defaults are used automatically.
The plugin supports JSONC format, allowing comments with `//` and `/* */`.
The file is only created if it does not already exist. The config is validated on load — if it fails validation, defaults are used automatically. If a config exists at the old location (`~/.local/share/opencode/memory/config.json`), it will be automatically migrated to the new location.
### Full Default Config
@@ -70,7 +72,16 @@ The file is only created if it does not already exist. The config is validated o
"enabled": true,
"debug": false
},
"executionModel": ""
"executionModel": "",
"auditorModel": "",
"ralph": {
"enabled": true,
"defaultMaxIterations": 15,
"cleanupWorktree": false,
"defaultAudit": true,
"model": "",
"minAudits": 1
}
}
```
@@ -121,6 +132,13 @@ Set `baseUrl` to point at any OpenAI-compatible self-hosted service (vLLM, Ollam
| `messagesTransform.enabled` | Enable the messages transform hook (memory injection + Architect enforcement) | `true` |
| `messagesTransform.debug` | Enable debug logging for messages transform | `false` |
| `executionModel` | Model override for plan execution sessions (`provider/model`). Falls back to OpenCode's default model. | — |
| `ralph.enabled` | Enable Ralph iterative development loops | `true` |
| `ralph.defaultMaxIterations` | Default max iterations (0 = unlimited) | `15` |
| `ralph.cleanupWorktree` | Auto-remove worktree on cancel | `false` |
| `ralph.defaultAudit` | Run auditor after each coding iteration | `true` |
| `ralph.model` | Model override for Ralph sessions (`provider/model`), falls back to `executionModel` | — |
| `ralph.minAudits` | Minimum audit iterations required before completion | `1` |
| `auditorModel` | Model override for the auditor agent (`provider/model`). When set, overrides the auditor agent's default model. When not set, the auditor uses the platform default. | — |
---
@@ -139,9 +157,9 @@ The plugin is composed of several subsystems that work together:
│ Embedding │ Vec Search │ Cache │
│ Service │ (sqlite-vec) │ (In-Memory) │
├──────────────┴────────────────┬───────────────────┤
│ KV Service │ Auto-Cleanup │
│ (ephemeral state + TTL) │ (30min interval)│
├──────────────┴────────────────┴───────────────────┤
│ KV Service │ Ralph Service │ Auto-Cleanup │
│ (TTL state) │ (loop mgmt) │ (30min) │
├─────────────────┴─────────────────┴───────────────┤
│ SQLite Database (WAL) │
│ memories | metadata | project_kv (TTL indexed) │
└──────────────────────────────────────────────────┘
@@ -175,6 +193,17 @@ The KV store provides ephemeral project state management with automatic TTL-base
The KV service is initialized on plugin startup and begins its cleanup interval automatically. Call `kvService.destroy()` during cleanup to stop the interval.
### Ralph Service
The Ralph service manages iterative development loops using the KV store for state persistence:
- **State Management**: Each loop's state is stored in the KV store under `ralph:{sessionId}` with fields: `active` (boolean), `sessionId`, `worktreeName`, `worktreeDir`, `worktreeBranch`, `workspaceId`, `iteration`, `maxIterations`, `completionPromise`, `startedAt`, `prompt`, `phase` (coding/auditing), `audit`, `lastAuditResult`, `errorCount`, `auditCount`, `terminationReason`, `completedAt`, `parentSessionId`, `inPlace`
- **Two-Phase Cycle**: Alternates between coding (Code agent works on the task) and auditing (Auditor agent reviews changes). Audit findings feed back into the next coding iteration
- **Completion Criteria**: Requires the `completionPromise` to be detected in `<promise>` tags AND `minAudits` (default 1) audit iterations before marking the loop as completed. Without a `completionPromise`, the loop only terminates via other conditions (max iterations, errors, cancellation, etc.)
- **Error Handling**: Tracks consecutive errors with `MAX_RETRIES` (3). If 3 consecutive iterations fail, the loop terminates with reason `error_max_retries`
- **Worktree Management**: By default creates an isolated git worktree for each loop. Uses `git rev-parse --git-common-dir` to find the main repo root. On completion, auto-commits changes and removes the worktree (preserving the branch). Set `inPlace: true` to skip worktree isolation
- **Termination Reasons**: `completed`, `max_iterations`, `error_max_retries`, `worktree_failed`, `cancelled`, `user_aborted`, `stall_timeout`, `shutdown`
### Vector Search
Vector similarity search is powered by `sqlite-vec`, a SQLite extension. The vec service:
@@ -275,7 +304,7 @@ When deduplication triggers, the existing memory's ID is returned instead of cre
## Tools
The plugin registers thirteen tools that the AI agent can call:
The plugin registers seventeen tools that the AI agent can call:
### memory-read
@@ -324,7 +353,7 @@ Check plugin health or trigger a reindex of all embeddings.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `action` | enum | No | `check` (default) or `reindex` |
| `action` | enum | No | `check` (default), `reindex`, or `upgrade` |
**Check** returns:
@@ -342,6 +371,12 @@ Check plugin health or trigger a reindex of all embeddings.
- Updates the `plugin_metadata` table on success
- Reports total, success, and failure counts
**Upgrade** installs the latest version of the plugin:
- Checks npm registry for the latest available version
- Installs via `bun add --force --no-cache --exact @opencode-manager/memory@latest`
- Reports the old and new version numbers
!!! warning "Model Changes Require Reindex"
If you change `embedding.model` or `embedding.dimensions`, existing embeddings will have mismatched dimensions. Auto-validation handles this on startup, but you can also trigger it manually with `memory-health reindex`.
@@ -353,10 +388,11 @@ Create a new Code session and send an implementation plan as the first prompt. D
|-----------|------|----------|-------------|
| `plan` | string | Yes | The full implementation plan to send to the Code agent |
| `title` | string | Yes | Short title for the session (shown in session list, max 60 chars) |
| `inPlace` | boolean | No | Execute in the current session as a subtask instead of creating a new session (default: false) |
Creates a new session via the OpenCode API and sends the plan as the first message to the Code agent. Returns the session ID and title. Only the Architect agent has access to this tool — it is excluded from Code and Memory agents.
By default, creates a new session via the OpenCode API and sends the plan as the first message to the Code agent. When `inPlace` is true, switches to the Code agent in the current session instead. Returns the session ID and title. Only the Architect agent has access to this tool — it is excluded from Code and Memory agents.
The model used for the new Code session is determined by `executionModel` in the plugin config (format: `provider/model`, e.g. `anthropic/claude-sonnet-4-20250514`). If not set, OpenCode's default model resolution is used — typically the `model` field from `opencode.json`.
The model used for execution is determined by `executionModel` in the plugin config (format: `provider/model`, e.g. `anthropic/claude-sonnet-4-20250514`). If not set, OpenCode's default model resolution is used — typically the `model` field from `opencode.json`.
### memory-kv-set
@@ -398,6 +434,34 @@ No parameters required.
Returns a list of all stored keys with their values and expiration times. Useful for debugging or inspecting current project state.
### ralph-cancel
Cancel an active Ralph loop and optionally clean up the worktree.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `name` | string | No | Worktree name of the loop to cancel (auto-selects if only one active) |
### ralph-status
Check the status of Ralph loops. With no arguments, lists all active loops for the current project. Pass a worktree name for detailed status.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `name` | string | No | Worktree name for detailed status |
Returns iteration count, current phase, audit results, model configuration, and termination status.
### memory-plan-ralph
Execute an architect plan using a Ralph iterative development loop. Designed to be called by the Architect agent after the user approves a plan with the "Execute with Ralph loop" or "Ralph in place" option.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `plan` | string | Yes | The full implementation plan |
| `title` | string | Yes | Short title for the session |
| `inPlace` | boolean | No | Run in current directory instead of worktree (default: false) |
!!! note "KV Store vs Memory"
The KV store is designed for **ephemeral** project state that expires automatically (default 24 hours). Use `memory-write` for **durable** knowledge that should persist across sessions, such as conventions, decisions, and context.
@@ -414,7 +478,11 @@ The Architect and Code agents work together in a plan-then-execute pattern. The
1. **Switch to the Architect agent** using the agent selector in the chat header
2. **Describe your task** — the Architect researches the codebase, checks memory for conventions and decisions, and designs a plan
3. **Review the plan** — the Architect presents a structured plan with objectives, phases, and decisions for your approval
4. **Approve the plan** — the Architect calls `memory-plan-execute`, which creates a new Code session and sends the full plan as context
4. **Approve the plan** — choose an execution mode:
- **Approve plan** → `memory-plan-execute` creates a new Code session with the plan
- **Execute with Ralph loop** → `memory-plan-ralph` runs the plan in an isolated worktree with iterative coding/auditing
- **Ralph in place** → Same as Ralph loop but in the current directory (no worktree isolation)
- **Reject plan** → Cancel
5. **Switch to the new session** — the Code agent executes the plan phase by phase
The Architect operates in read-only mode — it cannot edit files. This separation ensures planning is thorough before any code changes are made.
@@ -425,7 +493,7 @@ Planning requires strong reasoning — use a smart model (e.g., `claude-opus-4-6
This gives you the best of both worlds: high-quality plans at the reasoning tier, fast execution at a fraction of the cost.
**Configure the execution model** in the memory plugin config (`~/.local/share/opencode/memory/config.json`):
**Configure the execution model** in the memory plugin config (`~/.config/opencode/memory-config.jsonc`):
```json
{
@@ -438,6 +506,57 @@ Or set it from the UI: **Settings > Memory Plugin > Execution Model**.
!!! tip "Cost Optimization"
With this setup, only the planning phase uses the expensive model. The Code session — which typically consumes far more tokens implementing the plan — runs on the cheaper model. The Architect's plan provides enough structure and detail that the Code agent doesn't need the same level of reasoning capability.
### Ralph Loop
The Ralph loop is an iterative development system that alternates between coding and auditing phases until the task is complete.
#### How It Works
1. A new session is created (in a worktree or in-place)
2. The Code agent receives the task prompt and works on it
3. When the session goes idle, the Ralph handler checks the phase:
- **Coding phase** → If auditing is enabled, switches to auditing phase and runs the Auditor agent as a subtask
- **Auditing phase** → Processes audit findings, switches back to coding phase, and sends a continuation prompt with the findings
4. The loop repeats until one of these conditions is met:
- **Completion**: The `completionPromise` phrase is detected in `<promise>` tags AND `minAudits` (default 1) audit iterations have been performed. Without a `completionPromise`, the loop does not auto-complete.
- **Max iterations**: Reached `maxIterations` limit (if > 0)
- **Error limit**: 3 consecutive failures (`MAX_RETRIES`)
- **Stall timeout**: 5 consecutive stalls detected by the watchdog (`MAX_CONSECUTIVE_STALLS`)
- **Worktree failure**: The worktree becomes unavailable
- **Cancelled**: User cancels via `ralph-cancel` or `/cancel-ralph`
- **User abort**: Session is aborted
#### Worktree vs In-Place
| Mode | Isolation | Auto-Commit | Cleanup | Permission Scoping |
|------|-----------|-------------|---------|-------------------|
| Worktree (default) | Isolated git worktree | Yes, on completion | Worktree removed, branch preserved | File ops scoped to worktree, git push denied |
| In-place (`inPlace: true`) | None — runs in current directory | No | None | Git push denied only |
#### Tool Blocking
During a Ralph loop, certain tools are blocked to keep the agent focused:
- `question` — No interactive questions; work autonomously
- `memory-plan-execute` — Cannot start new plan sessions
- `memory-plan-ralph` — Cannot start nested Ralph loops
Blocking is enforced via `tool.execute.before` (throws error) with `tool.execute.after` as defense in depth.
#### Model Configuration
| Config Key | Purpose | Fallback |
|------------|---------|----------|
| `ralph.model` | Model for Ralph coding sessions | `executionModel` → platform default |
| `auditorModel` | Model for the auditor agent | Platform default (no fallback chain) |
#### Slash Commands
| Command | Description |
|---------|-------------|
| `/ralph-loop <prompt>` | Start a Ralph loop (delegates to memory-plan-ralph) |
| `/cancel-ralph` | Cancel the active Ralph loop |
---
## Agents
@@ -454,17 +573,19 @@ The Code agent's system prompt instructs it to:
- Check memory before modifying unfamiliar code areas or making architectural decisions
- Store durable knowledge with rationale (not just "we use X" but "we use X because Y")
- Use the @Memory subagent for complex memory operations (multi-query research, contradiction resolution, bulk curation)
- Use the @Librarian subagent for complex memory operations (multi-query research, contradiction resolution, bulk curation)
- Check for duplicates with `memory-read` before writing new memories
- Update stale memories with `memory-edit` rather than creating duplicates
### Memory Agent (subagent)
### Librarian Agent (subagent)
- **Display name:** `Memory`
- **Display name:** `librarian`
- **ID:** `ocm-librarian`
- **Mode:** `subagent`
- **Temperature:** 0.0
- **Role:** Institutional memory manager
The Memory agent handles:
The Librarian agent handles:
- Strategic retrieval across scopes with prioritized results
- Storage with proper scope categorization and rationale
@@ -485,20 +606,23 @@ The Architect agent follows a Research → Design → Plan → Execute workflow:
1. **Research** — Reads relevant files, searches the codebase, checks memory for conventions and decisions
2. **Design** — Considers approaches, weighs tradeoffs, asks clarifying questions
3. **Plan** — Presents a structured plan with objectives, phases, decisions, conventions, and key context
4. **Execute** — When the user approves, calls `memory-plan-execute` with the plan and title.
4. **Execute** — When the user approves via the question tool, calls `memory-plan-execute` or `memory-plan-ralph` depending on the chosen execution mode.
The Architect is the only agent with access to the `memory-plan-execute` tool. Plans must be fully self-contained since the Code agent receiving them has no access to the Architect's conversation.
The Architect is the only agent with access to `memory-plan-execute` and `memory-plan-ralph`. Plans must be fully self-contained since the Code agent receiving them has no access to the Architect's conversation.
### Code Review Agent (subagent)
### Auditor Agent (subagent)
- **Display name:** `Code Review`
- **Display name:** `auditor`
- **ID:** `ocm-auditor`
- **Mode:** `subagent`
- **Temperature:** 0.0 (deterministic)
- **Role:** Convention-aware code reviewer with memory access
The Code Review agent is a read-only subagent invoked by other agents via the Task tool to review diffs, commits, branches, or PRs. It checks changes against stored project conventions and decisions, then returns a structured review summary with issues (bug/warning/suggestion) and observations.
The Auditor agent is a read-only subagent invoked by other agents via the Task tool to review diffs, commits, branches, or PRs. It checks changes against stored project conventions and decisions, then returns a structured review summary with issues (bug/warning/suggestion), observations, and next steps.
The agent can read memory (`memory-read`) but cannot write, edit, or delete memories. It also cannot execute plans — `memory-plan-execute`, `memory-write`, `memory-edit`, and `memory-delete` are excluded.
The agent can read memory (`memory-read`) but cannot write, edit, or delete memories. It also cannot execute plans — `memory-plan-execute`, `memory-plan-ralph`, `memory-health`, `memory-write`, `memory-edit`, and `memory-delete` are excluded.
The Auditor persists review findings to the KV store (key pattern: `review-finding:<file_path>:<line_number>`) and retrieves past findings at the start of every review for continuity.
The `/review` slash command triggers this agent as a subtask with the template: "Review the current code changes."
@@ -511,13 +635,15 @@ The plugin also modifies built-in OpenCode agents:
| `plan` | Gets access to `memory-read` tool |
| `build` | Hidden (replaced by the Code agent) |
The default agent is set to `Code`.
The default agent is set to `code`.
!!! note "Removed Features"
The following features were removed in a recent refactor:
- Keyword activation (regex-based detection of "remember this", "recall", etc.)
- LLM parameter adjustment based on detected modes (temperature, thinking budget, maxSteps)
- `resumeAfterCompaction` config option
### Slash Commands
| Command | Description | Agent | Mode |
|---------|-------------|-------|------|
| `/review` | Run a code review on current changes | auditor | subtask |
| `/ralph-loop` | Start a Ralph loop (delegates to memory-plan-ralph) | code | direct |
| `/cancel-ralph` | Cancel the active Ralph loop | code | direct |
---
@@ -571,6 +697,37 @@ Memory injection is controlled independently by `memoryInjection.enabled` (defau
2. If so, appends a synthetic `<system-reminder>` part enforcing read-only mode
3. This provides message-level enforcement on top of the agent's `edit: { '*': 'deny' }` permission config
### tool.execute.before
Blocks certain tools during active Ralph loops to keep the agent focused on the current task. Throws an error with a descriptive message when a blocked tool is called. Blocked tools: `question`, `memory-plan-execute`, `memory-plan-ralph`.
### tool.execute.after
Defense-in-depth companion to `tool.execute.before`. If a blocked tool somehow executes during a Ralph loop, this hook overrides the output with the denial message.
### permission.ask
Auto-resolves permissions during Ralph loops:
- **Deny**: `git push` operations (always denied during Ralph loops)
- All other permission requests are passed through to the default handler
### session.idle (event handler)
Drives the Ralph iteration loop by listening for `session.idle` events:
1. Checks if the idle session belongs to an active Ralph loop
2. Records activity to reset the watchdog stall timer
3. Re-fetches state as a safety check against race conditions
4. Dispatches to the appropriate phase handler:
- **Coding phase**: If auditing is enabled, switches to auditing phase and runs the Auditor agent as a subtask. Checks for completion promise. Checks max iterations.
- **Auditing phase**: Processes audit results, increments `auditCount`, switches back to coding phase, sends continuation prompt with findings. Checks for completion promise. Checks max iterations.
5. On completion: auto-commits changes (worktree mode), removes worktree (preserving branch), notifies parent session
### worktree.failed (event handler)
Terminates any Ralph loop associated with a failed worktree. Sets the loop status to stopped with reason `worktree_failed`.
---
## Data Lifecycle
@@ -583,7 +740,8 @@ Memory injection is controlled independently by `memoryInjection.enabled` (defau
4. Initialize SQLite database with WAL mode
5. Create memory service with no-op vec service
6. Initialize KV service and start auto-cleanup interval (30 minutes)
7. Initialize vec service asynchronously:
7. Initialize Ralph service (uses KV store for state persistence)
8. Initialize vec service asynchronously:
- If available: sync missing embeddings, auto-validate model drift
- If unavailable: continue with no-op (semantic search degraded)
@@ -591,11 +749,12 @@ Memory injection is controlled independently by `memoryInjection.enabled` (defau
On process exit, `SIGINT`, or `SIGTERM`:
1. Stop KV cleanup interval
2. Dispose vec service
3. Destroy in-memory cache
4. Dispose embedding provider (disconnect from shared server or release model)
5. Close SQLite database
1. Stop any active Ralph loops
2. Stop KV cleanup interval
3. Dispose vec service
4. Destroy in-memory cache
5. Dispose embedding provider (disconnect from shared server or release model)
6. Close SQLite database
The cleanup function is idempotent — calling it multiple times is safe.
@@ -604,13 +763,15 @@ The cleanup function is idempotent — calling it multiple times is safe.
| File | Location | Purpose |
|------|----------|---------|
| `memory.db` | `{dataDir}/` | SQLite database with all memories |
| `config.json` | `{dataDir}/` | Plugin configuration |
| `memory-config.jsonc` | `{configDir}/` | Plugin configuration (JSONC format, supports comments) |
| `embedding.sock` | `{dataDir}/` | Unix socket for shared embedding server |
| `embedding.pid` | `{dataDir}/` | PID file for the embedding server process |
| `embedding.startup.lock` | `{dataDir}/` | Directory-based lock to prevent duplicate server starts |
| `memory.log` | `{dataDir}/logs/` | Debug log (when logging is enabled) |
| `models/` | `{dataDir}/` | Hugging Face model cache for local embeddings |
Where `{dataDir}` is `~/.local/share/opencode/memory` (or `$XDG_DATA_HOME/opencode/memory`) and `{configDir}` is `~/.config/opencode` (or `$XDG_CONFIG_HOME/opencode`).
---
## CLI
+1
View File
@@ -58,6 +58,7 @@ OpenCode Manager provides a comprehensive web interface for managing OpenCode AI
- **Automatic Extraction** - Durable knowledge extracted after session compaction
- **Compaction Awareness** - Injects project memories into compaction context
- **Architect → Code** - Plan with a smart model, execute with a fast model for cost-optimized workflows
- **Ralph Loops** - Iterative development with automatic auditing in isolated worktrees
[Learn more →](memory.md)
+37 -1
View File
@@ -1,6 +1,6 @@
import { fetchWrapper, fetchWrapperVoid } from './fetchWrapper'
import { API_BASE_URL } from '@/config'
import type { Memory, MemoryStats, CreateMemoryRequest, UpdateMemoryRequest, PluginConfig } from '@opencode-manager/shared/types'
import type { Memory, MemoryStats, CreateMemoryRequest, UpdateMemoryRequest, PluginConfig, KvEntry, CreateKvEntryRequest, UpdateKvEntryRequest } from '@opencode-manager/shared/types'
export async function listMemories(filters?: {
projectId?: string
@@ -94,3 +94,39 @@ export async function testEmbeddingConfig(): Promise<TestEmbeddingResult> {
body: JSON.stringify({}),
})
}
export async function listKvEntries(projectId: string, prefix?: string): Promise<{ entries: KvEntry[] }> {
const params = new URLSearchParams({ projectId })
if (prefix) params.set('prefix', prefix)
return fetchWrapper(`${API_BASE_URL}/api/memory/kv?${params.toString()}`)
}
export async function deleteKvEntry(projectId: string, key: string): Promise<void> {
return fetchWrapperVoid(`${API_BASE_URL}/api/memory/kv/${encodeURIComponent(key)}?projectId=${encodeURIComponent(projectId)}`, {
method: 'DELETE',
})
}
export async function createKvEntry(data: CreateKvEntryRequest): Promise<{ entry: KvEntry }> {
return fetchWrapper(`${API_BASE_URL}/api/memory/kv`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
}
export async function updateKvEntry(projectId: string, key: string, data: UpdateKvEntryRequest): Promise<{ entry: KvEntry }> {
return fetchWrapper(`${API_BASE_URL}/api/memory/kv/${encodeURIComponent(key)}?projectId=${encodeURIComponent(projectId)}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
}
export async function cancelRalphLoop(repoId: string, sessionId: string): Promise<{ cancelled: boolean; worktreeName?: string }> {
return fetchWrapper(`${API_BASE_URL}/api/memory/ralph/cancel`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ repoId, sessionId }),
})
}
@@ -0,0 +1,186 @@
import { useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { useCreateKvEntry, useUpdateKvEntry } from '@/hooks/useMemories'
import type { KvEntry, CreateKvEntryRequest, UpdateKvEntryRequest } from '@opencode-manager/shared/types'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
const kvSchema = z.object({
key: z.string().min(1, 'Key is required'),
data: z.string().min(1, 'Data is required'),
ttlHours: z.number().optional(),
})
type KvFormData = z.infer<typeof kvSchema>
interface KvFormDialogProps {
entry?: KvEntry
projectId?: string
open: boolean
onOpenChange: (open: boolean) => void
}
export function KvFormDialog({ entry, projectId, open, onOpenChange }: KvFormDialogProps) {
const createMutation = useCreateKvEntry()
const updateMutation = useUpdateKvEntry()
const [jsonError, setJsonError] = useState<string | undefined>()
const {
register,
handleSubmit,
reset,
formState: { errors },
} = useForm<KvFormData>({
resolver: zodResolver(kvSchema),
defaultValues: {
key: '',
data: '',
ttlHours: undefined,
},
})
useEffect(() => {
if (open) {
if (entry) {
const ttlMs = entry.expiresAt - entry.updatedAt
const ttlHoursValue = ttlMs > 0 && ttlMs < Number.MAX_SAFE_INTEGER
? Math.round(ttlMs / (1000 * 60 * 60))
: undefined
reset({
key: entry.key,
data: JSON.stringify(entry.data, null, 2),
ttlHours: ttlHoursValue,
})
} else {
reset({
key: '',
data: '',
ttlHours: undefined,
})
}
setJsonError(undefined)
}
}, [open, entry, reset])
const validateJson = (value: string): boolean => {
try {
JSON.parse(value)
setJsonError(undefined)
return true
} catch (e) {
setJsonError(e instanceof Error ? e.message : 'Invalid JSON')
return false
}
}
const onSubmit = async (data: KvFormData) => {
if (!validateJson(data.data)) {
return
}
const parsedData = JSON.parse(data.data)
const ttlMs = data.ttlHours ? data.ttlHours * 1000 * 60 * 60 : undefined
if (entry) {
const updateData: UpdateKvEntryRequest = {
data: parsedData,
ttlMs,
}
await updateMutation.mutateAsync({ projectId: projectId!, key: entry.key, data: updateData })
} else if (projectId) {
const createData: CreateKvEntryRequest = {
projectId,
key: data.key,
data: parsedData,
ttlMs,
}
await createMutation.mutateAsync(createData)
}
onOpenChange(false)
}
const isLoading = createMutation.isPending || updateMutation.isPending
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[500px]">
<DialogHeader>
<DialogTitle>{entry ? 'Edit KV Entry' : 'Create KV Entry'}</DialogTitle>
<DialogDescription>
{entry
? 'Update the KV entry data and TTL.'
: 'Add a new key-value entry to store project data.'}
</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="key">Key</Label>
<Input
id="key"
{...register('key')}
placeholder="Enter key..."
disabled={!!entry}
/>
{errors.key && (
<p className="text-sm text-destructive">{errors.key.message}</p>
)}
</div>
<div className="space-y-2">
<Label htmlFor="data">Data (JSON)</Label>
<Textarea
id="data"
{...register('data')}
placeholder='{"key": "value"}'
rows={6}
className="resize-none font-mono"
onBlur={(e) => validateJson(e.target.value)}
/>
{errors.data && (
<p className="text-sm text-destructive">{errors.data.message}</p>
)}
{jsonError && (
<p className="text-sm text-destructive">{jsonError}</p>
)}
</div>
<div className="space-y-2">
<Label htmlFor="ttlHours">TTL (hours, optional)</Label>
<Input
id="ttlHours"
type="number"
min="0"
step="1"
{...register('ttlHours', { valueAsNumber: true })}
placeholder="Enter TTL in hours..."
/>
</div>
<DialogFooter className='flex gap-2 flex-wrap'>
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
Cancel
</Button>
<Button type="submit" disabled={isLoading || !!jsonError}>
{isLoading ? 'Saving...' : entry ? 'Update' : 'Create'}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
)
}
+182
View File
@@ -0,0 +1,182 @@
import { useState } from 'react'
import { useKvEntries, useDeleteKvEntry } from '@/hooks/useMemories'
import { useDebounce } from '@/hooks/useDebounce'
import type { KvEntry } from '@opencode-manager/shared/types'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Loader2, Trash2, Key, ChevronDown, ChevronRight, Plus } from 'lucide-react'
import { DeleteDialog } from '@/components/ui/delete-dialog'
import { KvFormDialog } from './KvFormDialog'
interface KvListProps {
projectId?: string
}
function formatTimeRemaining(expiresAt: number): string {
const now = Date.now()
const diff = expiresAt - now
if (diff <= 0) {
return 'expired'
}
const hours = Math.floor(diff / (1000 * 60 * 60))
const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
if (hours > 0) {
return `${hours}h ${minutes}m`
}
return `${minutes}m`
}
export function KvList({ projectId }: KvListProps) {
const [searchQuery, setSearchQuery] = useState<string>('')
const debouncedSearch = useDebounce(searchQuery, 300)
const [expandedKey, setExpandedKey] = useState<string | null>(null)
const [deleteKey, setDeleteKey] = useState<string | null>(null)
const [dialogOpen, setDialogOpen] = useState(false)
const [editingEntry, setEditingEntry] = useState<KvEntry | undefined>(undefined)
const { data: entries, isLoading } = useKvEntries(projectId, debouncedSearch || undefined)
const deleteMutation = useDeleteKvEntry()
const handleDelete = () => {
if (deleteKey && projectId) {
deleteMutation.mutate({ projectId, key: deleteKey })
setDeleteKey(null)
}
}
const toggleExpand = (key: string) => {
setExpandedKey(expandedKey === key ? null : key)
}
const handleEdit = (entry: KvEntry) => {
setEditingEntry(entry)
setDialogOpen(true)
}
const handleCreate = () => {
setEditingEntry(undefined)
setDialogOpen(true)
}
return (
<div className="space-y-4">
<div className="flex items-center gap-2">
<Input
placeholder="Filter by key prefix..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-64"
/>
<Button onClick={handleCreate} size="sm">
<Plus className="w-4 h-4 mr-2" />
Add KV Entry
</Button>
</div>
{isLoading ? (
<div className="flex items-center justify-center p-8">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
</div>
) : !entries || entries.length === 0 ? (
<div className="text-center p-8 text-muted-foreground">
<Key className="w-8 h-8 mx-auto mb-2 opacity-50" />
<p>No KV entries found</p>
</div>
) : (
<div className="space-y-2">
{entries.map((entry: KvEntry) => {
const isExpanded = expandedKey === entry.key
const dataPreview = JSON.stringify(entry.data)
const formattedData = JSON.stringify(entry.data, null, 2)
const truncatedPreview = dataPreview.length > 100
? dataPreview.slice(0, 100) + '...'
: dataPreview
return (
<div
key={entry.key}
className="p-4 rounded-lg border border-border bg-card hover:bg-accent/50 transition-colors"
>
<div className="flex items-center justify-between gap-2 mb-2">
<div className="flex items-center gap-2 flex-wrap min-w-0 flex-1">
<Button
variant="ghost"
size="icon"
className="h-6 w-6 p-0"
onClick={() => toggleExpand(entry.key)}
>
{isExpanded ? (
<ChevronDown className="w-4 h-4" />
) : (
<ChevronRight className="w-4 h-4" />
)}
</Button>
<span className="font-medium truncate">{entry.key}</span>
<Badge
variant="outline"
className="text-xs bg-amber-600/20 text-amber-400 border-amber-600/40"
>
{formatTimeRemaining(entry.expiresAt)}
</Badge>
</div>
<div className="flex gap-1">
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => handleEdit(entry)}
>
<Key className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-destructive"
onClick={() => setDeleteKey(entry.key)}
>
<Trash2 className="w-4 h-4" />
</Button>
</div>
</div>
<div className="text-sm text-muted-foreground font-mono break-all">
{truncatedPreview}
</div>
{isExpanded && (
<pre className="mt-2 p-2 bg-muted rounded text-xs overflow-auto max-h-64">
{formattedData}
</pre>
)}
<p className="text-xs text-muted-foreground mt-2">
Updated: {new Date(entry.updatedAt).toLocaleString()}
</p>
</div>
)
})}
</div>
)}
<DeleteDialog
open={deleteKey !== null}
onOpenChange={(open: boolean) => !open && setDeleteKey(null)}
onConfirm={handleDelete}
onCancel={() => setDeleteKey(null)}
title="Delete KV Entry"
description="Are you sure you want to delete this KV entry? This action cannot be undone."
itemName={deleteKey || undefined}
isDeleting={deleteMutation.isPending}
/>
<KvFormDialog
entry={editingEntry}
projectId={projectId}
open={dialogOpen}
onOpenChange={setDialogOpen}
/>
</div>
)
}
@@ -54,6 +54,7 @@ interface PromptInputProps {
opcodeUrl: string
directory?: string
sessionID: string
repoId?: number
disabled?: boolean
showScrollButton?: boolean
hasActiveStream?: boolean
@@ -69,7 +70,8 @@ interface PromptInputProps {
export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(function PromptInput({
opcodeUrl,
directory,
sessionID,
sessionID,
repoId,
disabled,
showScrollButton,
hasActiveStream = false,
@@ -139,7 +141,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
}), [imageAttachments, clearSTT, isRecording, abortRecording])
const sendPrompt = useSendPrompt(opcodeUrl, directory)
const sendShell = useSendShell(opcodeUrl, directory)
const abortSession = useAbortSession(opcodeUrl, directory, sessionID)
const abortSession = useAbortSession(opcodeUrl, directory, sessionID, repoId)
const { filterCommands } = useCommands(opcodeUrl)
const { executeCommand } = useCommandHandler({
opcodeUrl,
+63 -1
View File
@@ -6,8 +6,12 @@ import {
updateMemory,
deleteMemory,
getProjectSummary,
listKvEntries,
deleteKvEntry,
createKvEntry,
updateKvEntry,
} from '@/api/memory'
import type { CreateMemoryRequest, UpdateMemoryRequest } from '@opencode-manager/shared/types'
import type { CreateMemoryRequest, UpdateMemoryRequest, CreateKvEntryRequest, UpdateKvEntryRequest } from '@opencode-manager/shared/types'
import { showToast } from '@/lib/toast'
export function useMemories(filters?: {
@@ -92,3 +96,61 @@ export function useProjectSummary(repoId: number | undefined) {
enabled: repoId !== undefined,
})
}
export function useKvEntries(projectId?: string, prefix?: string) {
return useQuery({
queryKey: ['kvEntries', projectId, prefix],
queryFn: () => listKvEntries(projectId!, prefix).then(r => r.entries),
enabled: !!projectId,
})
}
export function useDeleteKvEntry() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: ({ projectId, key }: { projectId: string; key: string }) =>
deleteKvEntry(projectId, key),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['kvEntries'] })
queryClient.invalidateQueries({ queryKey: ['projectSummary'] })
showToast.success('KV entry deleted')
},
onError: (error) => {
showToast.error(`Failed to delete KV entry: ${error}`)
},
})
}
export function useCreateKvEntry() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (data: CreateKvEntryRequest) => createKvEntry(data).then(r => r.entry),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['kvEntries'] })
queryClient.invalidateQueries({ queryKey: ['projectSummary'] })
showToast.success('KV entry created')
},
onError: (error) => {
showToast.error(`Failed to create KV entry: ${error}`)
},
})
}
export function useUpdateKvEntry() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: ({ projectId, key, data }: { projectId: string; key: string; data: UpdateKvEntryRequest }) =>
updateKvEntry(projectId, key, data).then(r => r.entry),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['kvEntries'] })
queryClient.invalidateQueries({ queryKey: ['projectSummary'] })
showToast.success('KV entry updated')
},
onError: (error) => {
showToast.error(`Failed to update KV entry: ${error}`)
},
})
}
+7 -1
View File
@@ -3,6 +3,7 @@ import { useMemo, useRef, useEffect, useCallback, useState } from "react";
import { OpenCodeClient } from "../api/opencode";
import { API_BASE_URL } from "../config";
import { fetchWrapper } from "../api/fetchWrapper";
import { cancelRalphLoop } from "../api/memory";
import type {
Message,
Part,
@@ -421,7 +422,8 @@ const MAX_ABORT_RETRIES = 10;
export const useAbortSession = (
opcodeUrl: string | null | undefined,
directory?: string,
sessionID?: string
sessionID?: string,
repoId?: number
) => {
const client = useOpenCodeClient(opcodeUrl, directory);
const queryClient = useQueryClient();
@@ -541,6 +543,10 @@ export const useAbortSession = (
attemptAbort();
if (repoId) {
cancelRalphLoop(String(repoId), targetSessionID).catch(() => {})
}
retryIntervalRef.current = setInterval(() => {
retryCountRef.current++;
+40 -10
View File
@@ -2,20 +2,23 @@ import { useState } from 'react'
import { useParams } from 'react-router-dom'
import { useQuery } from '@tanstack/react-query'
import { getRepo } from '@/api/repos'
import { useProjectSummary } from '@/hooks/useMemories'
import { useProjectSummary, useKvEntries } from '@/hooks/useMemories'
import { Header } from '@/components/ui/header'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent } from '@/components/ui/card'
import { Loader2, Plus, Brain } from 'lucide-react'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
import { Loader2, Plus, Brain, Key } from 'lucide-react'
import { getRepoDisplayName } from '@/lib/utils'
import { MemoryList } from '@/components/memory/MemoryList'
import { MemoryFormDialog } from '@/components/memory/MemoryFormDialog'
import { KvList } from '@/components/memory/KvList'
export function Memories() {
const { id } = useParams<{ id: string }>()
const repoId = id ? Number(id) : undefined
const [createOpen, setCreateOpen] = useState(false)
const [activeTab, setActiveTab] = useState('memories')
const { data: repo, isLoading: repoLoading } = useQuery({
queryKey: ['repo', repoId],
@@ -24,6 +27,7 @@ export function Memories() {
})
const { data: projectSummary, isLoading: projectSummaryLoading } = useProjectSummary(repoId)
const { data: kvEntries } = useKvEntries(projectSummary?.projectId ?? undefined)
const projectId = projectSummary?.projectId ?? null
const stats = projectSummary?.stats ?? null
@@ -71,13 +75,17 @@ export function Memories() {
</Header.Title>
</div>
<Header.Actions>
<Button onClick={() => setCreateOpen(true)} size="sm" className="hidden sm:flex">
<Plus className="w-4 h-4 mr-2" />
New Memory
</Button>
<Button onClick={() => setCreateOpen(true)} size="sm" className="sm:hidden">
<Plus className="w-4 h-4" />
</Button>
{activeTab === 'memories' && (
<>
<Button onClick={() => setCreateOpen(true)} size="sm" className="hidden sm:flex">
<Plus className="w-4 h-4 mr-2" />
New Memory
</Button>
<Button onClick={() => setCreateOpen(true)} size="sm" className="sm:hidden">
<Plus className="w-4 h-4" />
</Button>
</>
)}
</Header.Actions>
</Header>
@@ -98,11 +106,33 @@ export function Memories() {
))}
</div>
)}
{kvEntries && kvEntries.length > 0 && (
<Badge variant="outline" className="text-sm">
KV Entries: {kvEntries.length}
</Badge>
)}
</CardContent>
</Card>
)}
<MemoryList projectId={projectId} showFilters={true} />
<Tabs value={activeTab} onValueChange={setActiveTab}>
<TabsList>
<TabsTrigger value="memories">
<Brain className="w-4 h-4 mr-2" />
Memories
</TabsTrigger>
<TabsTrigger value="kv">
<Key className="w-4 h-4 mr-2" />
Key-Value
</TabsTrigger>
</TabsList>
<TabsContent value="memories">
<MemoryList projectId={projectId} showFilters={true} />
</TabsContent>
<TabsContent value="kv">
<KvList projectId={projectId ?? undefined} />
</TabsContent>
</Tabs>
</div>
<MemoryFormDialog
+1
View File
@@ -525,6 +525,7 @@ export function SessionDetail() {
opcodeUrl={opcodeUrl}
directory={repoDirectory}
sessionID={sessionId}
repoId={repoId}
disabled={!isConnected}
showScrollButton={showScrollButton}
hasActiveStream={hasActiveStream}
+71 -7
View File
@@ -63,7 +63,7 @@ The architect agent operates in read-only mode (`temperature: 0.0`, all edits de
| `memory-write` | Store a new project memory |
| `memory-edit` | Update an existing project memory |
| `memory-delete` | Delete a project memory by ID |
| `memory-health` | Health check or full reindex of the memory store |
| `memory-health` | Health check, reindex, or upgrade the plugin to latest version |
| `memory-plan-execute` | Create a new Code session and send an approved plan as the first prompt |
### Project KV Tools
@@ -76,6 +76,24 @@ Ephemeral key-value storage for project state with automatic TTL-based expiratio
| `memory-kv-get` | Retrieve a value by key |
| `memory-kv-list` | List all active KV entries for the project |
### Ralph Loop Tools
Iterative development loops with automatic auditing. Runs in an isolated git worktree by default, or in the current directory with `inPlace`.
| Tool | Description |
|------|-------------|
| `ralph-cancel` | Cancel an active Ralph loop and clean up the worktree |
| `ralph-status` | Check status of active Ralph loops |
| `memory-plan-ralph` | Execute an architect plan using a Ralph iterative loop |
## Slash Commands
| Command | Description | Agent |
|---------|-------------|-------|
| `/review` | Run a code review on current changes | auditor (subtask) |
| `/ralph-loop` | Start a Ralph loop (delegates to memory-plan-ralph) | code |
| `/cancel-ralph` | Cancel the active Ralph loop | code |
## CLI
Manage memories using the `ocm-mem` CLI. The CLI auto-detects the project ID from git and resolves the database path automatically.
@@ -166,11 +184,13 @@ ocm-mem cleanup --all --project my-project
## Configuration
On first run, the plugin automatically copies the bundled config to your data directory:
- Path: `~/.local/share/opencode/memory/config.json`
- Falls back to: `$XDG_DATA_HOME/opencode/memory/config.json`
On first run, the plugin automatically copies the bundled config to your config directory:
- Path: `~/.config/opencode/memory-config.jsonc`
- Falls back to: `$XDG_CONFIG_HOME/opencode/memory-config.jsonc`
You can edit this file to customize settings. The file is created only if it doesn't already exist.
The plugin supports JSONC format, allowing comments with `//` and `/* */`.
You can edit this file to customize settings. The file is created only if it doesn't already exist. If a config exists at the old location (`~/.local/share/opencode/memory/config.json`), it will be automatically migrated to the new location.
```json
{
@@ -201,7 +221,16 @@ You can edit this file to customize settings. The file is created only if it doe
"enabled": true,
"debug": false
},
"executionModel": ""
"executionModel": "",
"auditorModel": "",
"ralph": {
"enabled": true,
"defaultMaxIterations": 15,
"cleanupWorktree": false,
"defaultAudit": true,
"model": "",
"minAudits": 1
}
}
```
@@ -233,10 +262,14 @@ For API-based embeddings:
- `dataDir` - Directory for SQLite database storage (default: `"~/.local/share/opencode/memory"`)
- `dedupThreshold` - Similarity threshold for deduplication (0–1, default: `0.25`, clamped to `0.05–0.40`)
#### Config Location
- Config file: `~/.config/opencode/memory-config.jsonc` (or `$XDG_CONFIG_HOME/opencode/memory-config.jsonc`)
- Old config location (`~/.local/share/opencode/memory/config.json`) is automatically migrated on first load
#### Logging
- `logging.enabled` - Enable file logging (default: `false`)
- `logging.debug` - Enable debug-level log output (default: `false`)
- `logging.file` - Log file path. When empty, resolves to `~/.local/share/opencode/memory/logs/memory.log` (default: `""`)
- `logging.file` - Log file path. When empty, resolves to `~/.local/share/opencode/memory/logs/memory.log` (default: `""`). Logs remain in the data directory, only config has moved.
When enabled, logs are written to the specified file with timestamps. The log file has a 10MB size limit with automatic rotation.
@@ -259,14 +292,45 @@ When enabled, logs are written to the specified file with timestamps. The log fi
#### Execution
- `executionModel` - Model override for plan execution sessions, format: `provider/model` (e.g. `anthropic/claude-haiku-3-5-20241022`). When set, `memory-plan-execute` uses this model for the new Code session. When empty or omitted, OpenCode's default model is used (typically the `model` field from `opencode.json`). **Recommended:** Set this to a fast, cheap model (e.g. Haiku or MiniMax) and use a smart model (e.g. Opus) for the Architect session — planning needs reasoning, execution needs speed.
#### Ralph
- `ralph.enabled` - Enable Ralph iterative development loops (default: `true`)
- `ralph.defaultMaxIterations` - Default max iterations for loops, 0 = unlimited (default: `15`)
- `ralph.cleanupWorktree` - Auto-remove worktree on cancel (default: `false`)
- `ralph.defaultAudit` - Run auditor after each coding iteration by default (default: `true`)
- `ralph.model` - Model override for Ralph sessions (`provider/model`), falls back to `executionModel` (default: `""`)
- `ralph.minAudits` - Minimum audit iterations required before completion (default: `1`)
#### Auditor
- `auditorModel` - Model override for the auditor agent (`provider/model`). When set, overrides the auditor agent's default model. When not set, uses platform default (default: `""`)
## architect → code Workflow
Plan with a smart model, execute with a fast model. The architect agent researches and designs; the code agent implements.
After the architect presents a plan, the user approves via one of three execution modes:
- **Approve plan** — Creates a new Code session via `memory-plan-execute`
- **Execute with Ralph loop** — Runs the plan in an isolated worktree with iterative coding/auditing via `memory-plan-ralph`
- **Ralph in place** — Same as Ralph loop but runs in the current directory (no worktree isolation)
Set `executionModel` in your config to a fast model (e.g., Haiku) and use a smart model (e.g., Opus) for the architect session.
See the [full workflow guide](https://chriswritescode-dev.github.io/opencode-manager/features/memory/#architect--code) for setup details.
## Ralph Loop
The Ralph loop is an iterative development system that alternates between coding and auditing phases:
1. **Coding phase** — The Code agent works on the task
2. **Auditing phase** — The Auditor agent reviews changes against project conventions
3. **Repeat** — Findings from the audit feed back into the next coding iteration
The loop completes when the Code agent outputs the completion promise. It auto-terminates after `maxIterations` (if set) or after 3 consecutive errors.
By default, Ralph loops run in an isolated git worktree. Set `inPlace: true` to run in the current directory instead (skips worktree creation, auto-commit, and cleanup).
See the [full documentation](https://chriswritescode-dev.github.io/opencode-manager/features/memory/#ralph-loop) for details on the Ralph loop system.
## Documentation
Full documentation available at [chriswritescode-dev.github.io/opencode-manager/features/memory](https://chriswritescode-dev.github.io/opencode-manager/features/memory/)
@@ -26,5 +26,14 @@
"enabled": true,
"debug": false
},
"executionModel": ""
"executionModel": "",
"auditorModel": "",
"ralph": {
"enabled": true,
"defaultMaxIterations": 15,
"cleanupWorktree": false,
"defaultAudit": true,
"model": "",
"minAudits": 1
}
}
+4 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@opencode-manager/memory",
"version": "0.0.18",
"version": "0.0.20",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
@@ -12,7 +12,7 @@
},
"files": [
"dist",
"config.json",
"config.jsonc",
"scripts",
"README.md"
],
@@ -38,6 +38,8 @@
"dependencies": {
"@huggingface/transformers": "^3.8.1",
"@opencode-ai/plugin": "^1.2.16",
"@opencode-ai/sdk": "^1.2.26",
"jsonc-parser": "^3.3.1",
"sqlite-vec": "0.1.7-alpha.2"
},
"optionalDependencies": {
+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'
+367
View File
@@ -0,0 +1,367 @@
import { describe, test, expect, beforeEach, afterEach } from 'bun:test'
import { Database } from 'bun:sqlite'
import { createKvService } from '../src/services/kv'
import { createRalphService } from '../src/services/ralph'
import type { Logger } from '../src/types'
const TEST_DIR = '/tmp/opencode-manager-plan-approval-test-' + Date.now()
function createTestDb(): Database {
const db = new Database(`${TEST_DIR}-${Math.random().toString(36).slice(2)}.db`)
db.run(`
CREATE TABLE IF NOT EXISTS project_kv (
project_id TEXT NOT NULL,
key TEXT NOT NULL,
data TEXT NOT NULL,
expires_at INTEGER NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
PRIMARY KEY (project_id, key)
)
`)
db.run(`CREATE INDEX IF NOT EXISTS idx_project_kv_expires_at ON project_kv(expires_at)`)
return db
}
function createMockLogger(): Logger {
return {
log: () => {},
error: () => {},
debug: () => {},
}
}
describe('Plan Approval Tool Interception', () => {
let db: Database
let ralphService: ReturnType<typeof createRalphService>
const projectId = 'test-project'
const sessionID = 'test-session-123'
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>`,
}
const CANCEL_DIRECTIVE = '<system-reminder>\nThe user cancelled or provided a custom response. Do NOT call memory-plan-execute or memory-plan-ralph.\n</system-reminder>'
beforeEach(() => {
db = createTestDb()
const kvService = createKvService(db)
ralphService = createRalphService(kvService, projectId, createMockLogger())
})
afterEach(() => {
db.close()
})
function simulateToolExecuteAfter(
tool: string,
args: unknown,
output: { title: string; output: string; metadata: unknown },
sessionActive = false
) {
if (sessionActive) {
const state = {
active: true,
sessionId: sessionID,
worktreeName: 'test-worktree',
worktreeDir: '/test/worktree',
worktreeBranch: 'opencode/ralph-test',
workspaceId: 'wrk-test-worktree',
iteration: 1,
maxIterations: 5,
completionPromise: 'DONE',
startedAt: new Date().toISOString(),
prompt: 'Test prompt',
phase: 'coding' as const,
audit: false,
errorCount: 0,
auditCount: 0,
inPlace: false,
}
ralphService.setState(sessionID, state)
}
if (tool === 'question') {
const questionArgs = args as { questions?: Array<{ options?: Array<{ label: string }> }> } | undefined
const options = questionArgs?.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] : CANCEL_DIRECTIVE
output.output = `${output.output}\n\n${directive}`
}
}
return
}
if (!sessionActive) return
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.',
}
if (!(tool in RALPH_BLOCKED_TOOLS)) return
output.title = 'Tool blocked'
output.output = RALPH_BLOCKED_TOOLS[tool]!
}
test('Detects plan approval question and injects "New session" directive', () => {
const args = {
questions: [{
question: 'How would you like to proceed?',
options: [
{ label: 'New session', description: 'Create new session' },
{ label: 'Execute here', description: 'Execute here' },
{ label: 'Ralph (worktree)', description: 'Ralph worktree' },
{ label: 'Ralph (in place)', description: 'Ralph in place' },
],
}],
}
const output = { title: '', output: 'New session', metadata: {} }
simulateToolExecuteAfter('question', args, output)
expect(output.output).toContain('New session')
expect(output.output).toContain('<system-reminder>')
expect(output.output).toContain('memory-plan-execute')
expect(output.output).toContain('inPlace: false')
})
test('Detects plan approval question and injects "Execute here" directive', () => {
const args = {
questions: [{
question: 'How would you like to proceed?',
options: [
{ label: 'New session', description: 'Create new session' },
{ label: 'Execute here', description: 'Execute here' },
{ label: 'Ralph (worktree)', description: 'Ralph worktree' },
{ label: 'Ralph (in place)', description: 'Ralph in place' },
],
}],
}
const output = { title: '', output: 'Execute here', metadata: {} }
simulateToolExecuteAfter('question', args, output)
expect(output.output).toContain('Execute here')
expect(output.output).toContain('<system-reminder>')
expect(output.output).toContain('memory-plan-execute')
expect(output.output).toContain('inPlace: true')
})
test('Detects plan approval question and injects "Ralph (worktree)" directive', () => {
const args = {
questions: [{
question: 'How would you like to proceed?',
options: [
{ label: 'New session', description: 'Create new session' },
{ label: 'Execute here', description: 'Execute here' },
{ label: 'Ralph (worktree)', description: 'Ralph worktree' },
{ label: 'Ralph (in place)', description: 'Ralph in place' },
],
}],
}
const output = { title: '', output: 'Ralph (worktree)', metadata: {} }
simulateToolExecuteAfter('question', args, output)
expect(output.output).toContain('Ralph (worktree)')
expect(output.output).toContain('<system-reminder>')
expect(output.output).toContain('memory-plan-ralph')
expect(output.output).toContain('inPlace: false')
})
test('Detects plan approval question and injects "Ralph (in place)" directive', () => {
const args = {
questions: [{
question: 'How would you like to proceed?',
options: [
{ label: 'New session', description: 'Create new session' },
{ label: 'Execute here', description: 'Execute here' },
{ label: 'Ralph (worktree)', description: 'Ralph worktree' },
{ label: 'Ralph (in place)', description: 'Ralph in place' },
],
}],
}
const output = { title: '', output: 'Ralph (in place)', metadata: {} }
simulateToolExecuteAfter('question', args, output)
expect(output.output).toContain('Ralph (in place)')
expect(output.output).toContain('<system-reminder>')
expect(output.output).toContain('memory-plan-ralph')
expect(output.output).toContain('inPlace: true')
})
test('Injects cancel directive for unknown answer', () => {
const args = {
questions: [{
question: 'How would you like to proceed?',
options: [
{ label: 'New session', description: 'Create new session' },
{ label: 'Execute here', description: 'Execute here' },
{ label: 'Ralph (worktree)', description: 'Ralph worktree' },
{ label: 'Ralph (in place)', description: 'Ralph in place' },
],
}],
}
const output = { title: '', output: 'Custom answer', metadata: {} }
simulateToolExecuteAfter('question', args, output)
expect(output.output).toContain('Custom answer')
expect(output.output).toContain('<system-reminder>')
expect(output.output).toContain('cancelled or provided a custom response')
expect(output.output).toContain('Do NOT call memory-plan-execute or memory-plan-ralph')
})
test('Matches partial answer that starts with label', () => {
const args = {
questions: [{
question: 'How would you like to proceed?',
options: [
{ label: 'New session', description: 'Create new session' },
{ label: 'Execute here', description: 'Execute here' },
{ label: 'Ralph (worktree)', description: 'Ralph worktree' },
{ label: 'Ralph (in place)', description: 'Ralph in place' },
],
}],
}
const output = { title: '', output: 'New session (with custom config)', metadata: {} }
simulateToolExecuteAfter('question', args, output)
expect(output.output).toContain('New session (with custom config)')
expect(output.output).toContain('<system-reminder>')
expect(output.output).toContain('memory-plan-execute')
})
test('Does not match partial label in middle of text', () => {
const args = {
questions: [{
question: 'How would you like to proceed?',
options: [
{ label: 'New session', description: 'Create new session' },
{ label: 'Execute here', description: 'Execute here' },
{ label: 'Ralph (worktree)', description: 'Ralph worktree' },
{ label: 'Ralph (in place)', description: 'Ralph in place' },
],
}],
}
const output = { title: '', output: 'I want to create a session', metadata: {} }
simulateToolExecuteAfter('question', args, output)
expect(output.output).toContain('I want to create a session')
expect(output.output).toContain('<system-reminder>')
expect(output.output).toContain('cancelled or provided a custom response')
})
test('Does not modify non-approval questions', () => {
const args = {
questions: [{
question: 'What is your preference?',
options: [
{ label: 'Option A', description: 'First option' },
{ label: 'Option B', description: 'Second option' },
],
}],
}
const output = { title: '', output: 'Option A', metadata: {} }
const originalOutput = output.output
simulateToolExecuteAfter('question', args, output)
expect(output.output).toBe(originalOutput)
expect(output.output).not.toContain('<system-reminder>')
})
test('Does not modify non-question tools', () => {
const output = { title: '', output: 'Some result', metadata: {} }
const originalOutput = output.output
simulateToolExecuteAfter('memory-read', {}, output)
expect(output.output).toBe(originalOutput)
})
test('Ralph blocking still works for question tool when Ralph is active', () => {
const output = { title: '', output: 'test', metadata: {} }
simulateToolExecuteAfter('question', {}, output, true)
expect(output.title).toBe('')
expect(output.output).toBe('test')
})
test('Ralph blocking works for memory-plan-execute tool', () => {
const output = { title: '', output: 'test', metadata: {} }
simulateToolExecuteAfter('memory-plan-execute', {}, output, true)
expect(output.title).toBe('Tool blocked')
expect(output.output).toContain('memory-plan-execute tool is not available')
})
test('Ralph blocking works for memory-plan-ralph tool', () => {
const output = { title: '', output: 'test', metadata: {} }
simulateToolExecuteAfter('memory-plan-ralph', {}, output, true)
expect(output.title).toBe('Tool blocked')
expect(output.output).toContain('memory-plan-ralph tool is not available')
})
test('Ralph blocking does not affect non-blocked tools', () => {
const output = { title: '', output: 'test', metadata: {} }
simulateToolExecuteAfter('memory-read', {}, output, true)
expect(output.title).toBe('')
expect(output.output).toBe('test')
})
test('Ralph blocking only applies when Ralph is active', () => {
const output = { title: '', output: 'test', metadata: {} }
simulateToolExecuteAfter('memory-plan-execute', {}, output, false)
expect(output.title).toBe('')
expect(output.output).toBe('test')
})
})
+939
View File
@@ -0,0 +1,939 @@
import { describe, test, expect, beforeEach, afterEach } from 'bun:test'
import { Database } from 'bun:sqlite'
import { createKvQuery } from '../src/storage/kv-queries'
import { createKvService } from '../src/services/kv'
import { createRalphService } from '../src/services/ralph'
const TEST_DIR = '/tmp/opencode-manager-ralph-test-' + Date.now()
function createTestDb(): Database {
const db = new Database(`${TEST_DIR}-${Math.random().toString(36).slice(2)}.db`)
db.run(`
CREATE TABLE IF NOT EXISTS project_kv (
project_id TEXT NOT NULL,
key TEXT NOT NULL,
data TEXT NOT NULL,
expires_at INTEGER NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
PRIMARY KEY (project_id, key)
)
`)
db.run(`CREATE INDEX IF NOT EXISTS idx_project_kv_expires_at ON project_kv(expires_at)`)
return db
}
function createMockLogger() {
return {
log: () => {},
error: () => {},
debug: () => {},
}
}
describe('RalphService', () => {
let db: Database
let kvService: ReturnType<typeof createKvService>
let ralphService: ReturnType<typeof createRalphService>
const projectId = 'test-project'
beforeEach(() => {
db = createTestDb()
kvService = createKvService(db)
ralphService = createRalphService(kvService, projectId, createMockLogger())
})
afterEach(() => {
db.close()
})
test('state CRUD operations', () => {
const state = {
active: true,
sessionId: 'session-123',
worktreeName: 'test-worktree',
worktreeDir: '/path/to/worktree',
worktreeBranch: 'opencode/ralph-test',
workspaceId: 'wrk-test-worktree',
iteration: 1,
maxIterations: 5,
completionPromise: 'DONE',
startedAt: new Date().toISOString(),
prompt: 'Test prompt',
phase: 'coding' as const,
audit: false,
errorCount: 0,
auditCount: 0,
}
ralphService.setState('session-123', state)
const retrieved = ralphService.getActiveState('session-123')
expect(retrieved).toEqual(state)
ralphService.setState('session-123', { ...state, iteration: 2 })
const updated = ralphService.getActiveState('session-123')
expect(updated?.iteration).toBe(2)
ralphService.deleteState('session-123')
const deleted = ralphService.getActiveState('session-123')
expect(deleted).toBeNull()
})
test('getState returns null for inactive state', () => {
const inactiveState = {
active: false,
sessionId: 'session-456',
worktreeName: 'test-worktree',
worktreeDir: '/path/to/worktree',
worktreeBranch: 'opencode/ralph-test',
workspaceId: 'wrk-test-worktree',
iteration: 1,
maxIterations: 0,
completionPromise: null,
startedAt: new Date().toISOString(),
prompt: 'Test prompt',
phase: 'coding' as const,
audit: false,
errorCount: 0,
auditCount: 0,
}
ralphService.setState('session-456', inactiveState)
const retrieved = ralphService.getActiveState('session-456')
expect(retrieved).toBeNull()
})
test('getActiveState returns null for non-existent session', () => {
const retrieved = ralphService.getActiveState('non-existent')
expect(retrieved).toBeNull()
})
test('checkCompletionPromise matches exact promise', () => {
const text = 'Some response text <promise>DONE</promise> more text'
expect(ralphService.checkCompletionPromise(text, 'DONE')).toBe(true)
})
test('checkCompletionPromise returns false when no promise tags', () => {
const text = 'Some response text without promise tags'
expect(ralphService.checkCompletionPromise(text, 'DONE')).toBe(false)
})
test('checkCompletionPromise returns false when promise does not match', () => {
const text = 'Some response <promise>NOT_DONE</promise> text'
expect(ralphService.checkCompletionPromise(text, 'DONE')).toBe(false)
})
test('checkCompletionPromise handles whitespace normalization', () => {
const text = 'Response <promise> DONE WITH SPACES </promise> text'
expect(ralphService.checkCompletionPromise(text, 'DONE WITH SPACES')).toBe(true)
})
test('checkCompletionPromise matches first promise tag when multiple present', () => {
const text = 'First <promise>FIRST</promise> second <promise>SECOND</promise>'
expect(ralphService.checkCompletionPromise(text, 'FIRST')).toBe(true)
expect(ralphService.checkCompletionPromise(text, 'SECOND')).toBe(false)
})
test('checkCompletionPromise handles multiline promise', () => {
const text = 'Response <promise>\n MULTI\n LINE\n</promise> text'
expect(ralphService.checkCompletionPromise(text, 'MULTI LINE')).toBe(true)
})
test('buildContinuationPrompt includes iteration number', () => {
const state = {
active: true,
sessionId: 'session-789',
worktreeName: 'test-worktree',
worktreeDir: '/path/to/worktree',
worktreeBranch: 'opencode/ralph-test',
workspaceId: 'wrk-test-worktree',
iteration: 3,
maxIterations: 0,
completionPromise: null,
startedAt: new Date().toISOString(),
prompt: 'My test prompt',
phase: 'coding' as const,
audit: false,
errorCount: 0,
auditCount: 0,
}
const prompt = ralphService.buildContinuationPrompt(state)
expect(prompt).toContain('Ralph iteration 3')
expect(prompt).toContain('My test prompt')
})
test('buildContinuationPrompt includes completion promise instruction', () => {
const state = {
active: true,
sessionId: 'session-789',
worktreeName: 'test-worktree',
worktreeDir: '/path/to/worktree',
worktreeBranch: 'opencode/ralph-test',
workspaceId: 'wrk-test-worktree',
iteration: 1,
maxIterations: 0,
completionPromise: 'COMPLETE_TASK',
startedAt: new Date().toISOString(),
prompt: 'My test prompt',
phase: 'coding' as const,
audit: false,
errorCount: 0,
auditCount: 0,
}
const prompt = ralphService.buildContinuationPrompt(state)
expect(prompt).toContain('[Ralph iteration 1 | To stop: output <promise>COMPLETE_TASK</promise> (ONLY when all requirements are met)]')
})
test('buildContinuationPrompt includes max iterations when no promise', () => {
const state = {
active: true,
sessionId: 'session-789',
worktreeName: 'test-worktree',
worktreeDir: '/path/to/worktree',
worktreeBranch: 'opencode/ralph-test',
workspaceId: 'wrk-test-worktree',
iteration: 2,
maxIterations: 10,
completionPromise: null,
startedAt: new Date().toISOString(),
prompt: 'My test prompt',
phase: 'coding' as const,
audit: false,
errorCount: 0,
auditCount: 0,
}
const prompt = ralphService.buildContinuationPrompt(state)
expect(prompt).toContain('[Ralph iteration 2 / 10]')
})
test('buildContinuationPrompt shows unlimited message when no promise and no max', () => {
const state = {
active: true,
sessionId: 'session-789',
worktreeName: 'test-worktree',
worktreeDir: '/path/to/worktree',
worktreeBranch: 'opencode/ralph-test',
workspaceId: 'wrk-test-worktree',
iteration: 1,
maxIterations: 0,
completionPromise: null,
startedAt: new Date().toISOString(),
prompt: 'My test prompt',
phase: 'coding' as const,
audit: false,
errorCount: 0,
auditCount: 0,
}
const prompt = ralphService.buildContinuationPrompt(state)
expect(prompt).toContain('[Ralph iteration 1 | No completion promise set - loop runs until cancelled]')
})
test('state persists across service recreation', () => {
const state = {
active: true,
sessionId: 'session-persist',
worktreeName: 'test-worktree',
worktreeDir: '/path/to/worktree',
worktreeBranch: 'opencode/ralph-test',
workspaceId: 'wrk-test-worktree',
iteration: 5,
maxIterations: 10,
completionPromise: 'PERSIST_TEST',
startedAt: new Date().toISOString(),
prompt: 'Persistence test',
phase: 'coding' as const,
audit: false,
errorCount: 0,
auditCount: 0,
}
ralphService.setState('session-persist', state)
const newKvService = createKvService(db)
const newRalphService = createRalphService(newKvService, projectId, createMockLogger())
const retrieved = newRalphService.getActiveState('session-persist')
expect(retrieved).toEqual(state)
})
test('buildAuditPrompt returns audit instruction', () => {
const state = {
active: true,
sessionId: 'session-audit',
worktreeName: 'test-worktree',
worktreeDir: '/path/to/worktree',
worktreeBranch: 'opencode/ralph-test',
workspaceId: 'wrk-test-worktree',
iteration: 1,
maxIterations: 0,
completionPromise: null,
startedAt: new Date().toISOString(),
prompt: 'Test prompt',
phase: 'coding' as const,
audit: true,
errorCount: 0,
auditCount: 0,
}
const prompt = ralphService.buildAuditPrompt(state)
expect(prompt).toContain('Review the code changes')
expect(prompt).toContain('bugs, logic errors, missing error handling')
expect(prompt).toContain('No issues found')
expect(prompt).toContain('do not direct the agent to')
})
test('buildContinuationPrompt appends audit findings when provided', () => {
const state = {
active: true,
sessionId: 'session-audit',
worktreeName: 'test-worktree',
worktreeDir: '/path/to/worktree',
worktreeBranch: 'opencode/ralph-test',
workspaceId: 'wrk-test-worktree',
iteration: 2,
maxIterations: 0,
completionPromise: null,
startedAt: new Date().toISOString(),
prompt: 'Test prompt',
phase: 'coding' as const,
audit: true,
errorCount: 0,
auditCount: 0,
}
const auditFindings = 'Found a bug in line 10'
const prompt = ralphService.buildContinuationPrompt(state, auditFindings)
expect(prompt).toContain('Ralph iteration 2')
expect(prompt).toContain('Test prompt')
expect(prompt).toContain('The code auditor reviewed your changes')
expect(prompt).toContain('do not dismiss findings as unrelated to the task')
expect(prompt).toContain('Found a bug in line 10')
})
test('buildContinuationPrompt without audit findings does not append section', () => {
const state = {
active: true,
sessionId: 'session-audit',
worktreeName: 'test-worktree',
worktreeDir: '/path/to/worktree',
worktreeBranch: 'opencode/ralph-test',
workspaceId: 'wrk-test-worktree',
iteration: 2,
maxIterations: 0,
completionPromise: null,
startedAt: new Date().toISOString(),
prompt: 'Test prompt',
phase: 'coding' as const,
audit: true,
errorCount: 0,
auditCount: 0,
}
const prompt = ralphService.buildContinuationPrompt(state)
expect(prompt).toContain('Ralph iteration 2')
expect(prompt).toContain('Test prompt')
expect(prompt).not.toContain('The following issues were found')
})
test('buildContinuationPrompt with audit findings includes completion reminder', () => {
const state = {
active: true,
sessionId: 'session-audit',
worktreeName: 'test-worktree',
worktreeDir: '/path/to/worktree',
worktreeBranch: 'opencode/ralph-test',
workspaceId: 'wrk-test-worktree',
iteration: 2,
maxIterations: 0,
completionPromise: 'DONE',
startedAt: new Date().toISOString(),
prompt: 'Test prompt',
phase: 'coding' as const,
audit: true,
errorCount: 0,
auditCount: 0,
}
const auditFindings = 'Found a bug in line 10'
const prompt = ralphService.buildContinuationPrompt(state, auditFindings)
expect(prompt).toContain('After fixing all issues, output the completion signal')
expect(prompt).toContain('without creating a plan or asking for approval')
})
test('listActive returns only active states', () => {
const activeState1 = {
active: true,
sessionId: 'active-1',
worktreeName: 'worktree-1',
worktreeDir: '/path/to/worktree1',
worktreeBranch: 'opencode/ralph-worktree-1',
workspaceId: 'wrk-worktree-1',
iteration: 1,
maxIterations: 0,
completionPromise: null,
startedAt: new Date().toISOString(),
prompt: 'Active prompt 1',
phase: 'coding' as const,
audit: false,
errorCount: 0,
auditCount: 0,
}
const activeState2 = {
active: true,
sessionId: 'active-2',
worktreeName: 'worktree-2',
worktreeDir: '/path/to/worktree2',
worktreeBranch: 'opencode/ralph-worktree-2',
workspaceId: 'ralph-worktree-2',
iteration: 2,
maxIterations: 0,
completionPromise: null,
startedAt: new Date().toISOString(),
prompt: 'Active prompt 2',
phase: 'coding' as const,
audit: false,
errorCount: 0,
auditCount: 0,
}
const inactiveState = {
active: false,
sessionId: 'inactive-1',
worktreeName: 'worktree-3',
worktreeDir: '/path/to/worktree3',
worktreeBranch: 'opencode/ralph-worktree-3',
workspaceId: 'ralph-worktree-3',
iteration: 1,
maxIterations: 0,
completionPromise: null,
startedAt: new Date().toISOString(),
prompt: 'Inactive prompt',
phase: 'coding' as const,
audit: false,
errorCount: 0,
auditCount: 0,
}
ralphService.setState('active-1', activeState1)
ralphService.setState('active-2', activeState2)
ralphService.setState('inactive-1', inactiveState)
const active = ralphService.listActive()
expect(active.length).toBe(2)
expect(active.map((s) => s.sessionId)).toContain('active-1')
expect(active.map((s) => s.sessionId)).toContain('active-2')
expect(active.map((s) => s.sessionId)).not.toContain('inactive-1')
})
test('findByWorktreeName returns state by worktree name', () => {
const state1 = {
active: true,
sessionId: 'session-1',
worktreeName: 'unique-worktree-name',
worktreeDir: '/path/to/worktree',
worktreeBranch: 'opencode/ralph-unique-worktree-name',
workspaceId: 'wrk-unique-worktree-name',
iteration: 1,
maxIterations: 0,
completionPromise: null,
startedAt: new Date().toISOString(),
prompt: 'Test prompt',
phase: 'coding' as const,
audit: false,
errorCount: 0,
auditCount: 0,
}
ralphService.setState('session-1', state1)
const found = ralphService.findByWorktreeName('unique-worktree-name')
expect(found).toEqual(state1)
const notFound = ralphService.findByWorktreeName('non-existent')
expect(notFound).toBeNull()
})
test('state with errorCount and auditCount persists correctly', () => {
const state = {
active: true,
sessionId: 'session-err',
worktreeName: 'test-worktree',
worktreeDir: '/path/to/worktree',
worktreeBranch: 'opencode/ralph-test',
workspaceId: 'wrk-test-worktree',
iteration: 1,
maxIterations: 5,
completionPromise: 'DONE',
startedAt: new Date().toISOString(),
prompt: 'Test prompt',
phase: 'coding' as const,
audit: false,
errorCount: 2,
auditCount: 1,
terminationReason: undefined,
parentSessionId: 'parent-session-123',
}
ralphService.setState('session-err', state)
const retrieved = ralphService.getActiveState('session-err')
expect(retrieved?.errorCount).toBe(2)
expect(retrieved?.auditCount).toBe(1)
expect(retrieved?.parentSessionId).toBe('parent-session-123')
})
test('state defaults errorCount to 0', () => {
const state = {
active: true,
sessionId: 'session-default',
worktreeName: 'test-worktree',
worktreeDir: '/path/to/worktree',
worktreeBranch: 'opencode/ralph-test',
workspaceId: 'wrk-test-worktree',
iteration: 1,
maxIterations: 0,
completionPromise: null,
startedAt: new Date().toISOString(),
prompt: 'Test prompt',
phase: 'coding' as const,
audit: false,
errorCount: 0,
auditCount: 0,
}
ralphService.setState('session-default', state)
const retrieved = ralphService.getActiveState('session-default')
expect(retrieved?.errorCount).toBe(0)
expect(retrieved?.auditCount).toBe(0)
})
test('state with inPlace flag persists correctly', () => {
const inPlaceState = {
active: true,
sessionId: 'session-inplace',
worktreeName: 'inplace-worktree',
worktreeDir: '/path/to/project',
worktreeBranch: 'main',
workspaceId: '',
iteration: 1,
maxIterations: 5,
completionPromise: 'DONE',
startedAt: new Date().toISOString(),
prompt: 'In-place test prompt',
phase: 'coding' as const,
audit: false,
errorCount: 0,
auditCount: 0,
inPlace: true,
}
ralphService.setState('session-inplace', inPlaceState)
const retrieved = ralphService.getActiveState('session-inplace')
expect(retrieved?.inPlace).toBe(true)
expect(retrieved?.workspaceId).toBe('')
expect(retrieved?.worktreeDir).toBe('/path/to/project')
})
test('findByWorktreeName works with inPlace state', () => {
const inPlaceState = {
active: true,
sessionId: 'session-inplace-2',
worktreeName: 'unique-inplace-name',
worktreeDir: '/path/to/project',
worktreeBranch: 'develop',
workspaceId: '',
iteration: 2,
maxIterations: 0,
completionPromise: null,
startedAt: new Date().toISOString(),
prompt: 'Test prompt',
phase: 'coding' as const,
audit: true,
errorCount: 0,
auditCount: 1,
inPlace: true,
}
ralphService.setState('session-inplace-2', inPlaceState)
const found = ralphService.findByWorktreeName('unique-inplace-name')
expect(found).toEqual(inPlaceState)
expect(found?.inPlace).toBe(true)
})
test('buildContinuationPrompt works with inPlace state', () => {
const inPlaceState = {
active: true,
sessionId: 'session-inplace-3',
worktreeName: 'inplace-prompt-test',
worktreeDir: '/path/to/project',
worktreeBranch: 'main',
workspaceId: '',
iteration: 3,
maxIterations: 0,
completionPromise: 'COMPLETE',
startedAt: new Date().toISOString(),
prompt: 'In-place prompt test',
phase: 'coding' as const,
audit: false,
errorCount: 0,
auditCount: 0,
inPlace: true,
}
const prompt = ralphService.buildContinuationPrompt(inPlaceState)
expect(prompt).toContain('Ralph iteration 3')
expect(prompt).toContain('In-place prompt test')
expect(prompt).toContain('<promise>COMPLETE</promise>')
})
test('buildContinuationPrompt with audit findings works with inPlace state', () => {
const inPlaceState = {
active: true,
sessionId: 'session-inplace-4',
worktreeName: 'inplace-audit-test',
worktreeDir: '/path/to/project',
worktreeBranch: 'main',
workspaceId: '',
iteration: 2,
maxIterations: 0,
completionPromise: null,
startedAt: new Date().toISOString(),
prompt: 'In-place audit test',
phase: 'coding' as const,
audit: true,
errorCount: 0,
auditCount: 0,
inPlace: true,
}
const auditFindings = 'Bug found in component'
const prompt = ralphService.buildContinuationPrompt(inPlaceState, auditFindings)
expect(prompt).toContain('Ralph iteration 2')
expect(prompt).toContain('In-place audit test')
expect(prompt).toContain('The code auditor reviewed your changes')
expect(prompt).toContain('do not dismiss findings as unrelated to the task')
expect(prompt).toContain('Bug found in component')
})
test('getMinAudits returns default when not configured', () => {
const minAudits = ralphService.getMinAudits()
expect(minAudits).toBe(1)
})
test('getMinAudits returns configured value', () => {
const kvService = createKvService(db)
const customRalphService = createRalphService(kvService, projectId, createMockLogger(), { minAudits: 3 })
expect(customRalphService.getMinAudits()).toBe(3)
})
})
describe('Stall Detection', () => {
test('getStallInfo returns null when no watchdog running', () => {
const db = createTestDb()
const kvService = createKvService(db)
const ralphService = createRalphService(kvService, 'test-project', createMockLogger())
const mockClient = {
session: {
promptAsync: async () => ({ data: undefined, error: undefined }),
create: async () => ({ data: { id: 'test-session' }, error: undefined }),
messages: async () => ({ data: [] }),
status: async () => ({ data: {} }),
},
worktree: {
create: async () => ({ data: { id: 'wt-1', directory: '/tmp/wt', branch: 'main' }, error: undefined }),
remove: async () => ({ data: undefined, error: undefined }),
},
} as any
const mockV2Client = {
session: {
promptAsync: async () => ({ data: undefined, error: undefined }),
create: async () => ({ data: { id: 'test-session' }, error: undefined }),
messages: async () => ({ data: [] }),
status: async () => ({ data: {} }),
},
worktree: {
create: async () => ({ data: { id: 'wt-1', directory: '/tmp/wt', branch: 'main' }, error: undefined }),
remove: async () => ({ data: undefined, error: undefined }),
},
} as any
const { createRalphEventHandler } = require('../src/hooks/ralph')
const mockGetConfig = () => ({ ralph: {}, executionModel: undefined, auditorModel: undefined })
const handler = createRalphEventHandler(ralphService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const info = handler.getStallInfo('test-session')
expect(info).toBeNull()
})
test('startWatchdog initializes stall state', () => {
const db = createTestDb()
const kvService = createKvService(db)
const ralphService = createRalphService(kvService, 'test-project', createMockLogger(), { stallTimeoutMs: 100 })
const mockClient = {
session: {
promptAsync: async () => ({ data: undefined, error: undefined }),
create: async () => ({ data: { id: 'test-session' }, error: undefined }),
messages: async () => ({ data: [] }),
status: async () => ({ data: {} }),
},
worktree: {
create: async () => ({ data: { id: 'wt-1', directory: '/tmp/wt', branch: 'main' }, error: undefined }),
remove: async () => ({ data: undefined, error: undefined }),
},
} as any
const mockV2Client = {
session: {
promptAsync: async () => ({ data: undefined, error: undefined }),
create: async () => ({ data: { id: 'test-session' }, error: undefined }),
messages: async () => ({ data: [] }),
status: async () => ({ data: {} }),
},
worktree: {
create: async () => ({ data: { id: 'wt-1', directory: '/tmp/wt', branch: 'main' }, error: undefined }),
remove: async () => ({ data: undefined, error: undefined }),
},
} as any
const { createRalphEventHandler } = require('../src/hooks/ralph')
const mockGetConfig = () => ({ ralph: {}, executionModel: undefined, auditorModel: undefined })
const handler = createRalphEventHandler(ralphService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const sessionId = 'test-session'
ralphService.setState(sessionId, {
active: true,
sessionId,
worktreeName: 'test',
worktreeDir: '/tmp/test',
worktreeBranch: 'main',
workspaceId: '',
iteration: 1,
maxIterations: 0,
completionPromise: null,
startedAt: new Date().toISOString(),
prompt: 'test',
phase: 'coding',
audit: false,
errorCount: 0,
auditCount: 0,
})
handler.startWatchdog(sessionId)
const info = handler.getStallInfo(sessionId)
expect(info).not.toBeNull()
expect(info?.consecutiveStalls).toBe(0)
expect(info?.lastActivityTime).toBeDefined()
expect(Date.now() - info!.lastActivityTime).toBeLessThan(100)
})
test('session.created event tracks child sessions', async () => {
const db = createTestDb()
const kvService = createKvService(db)
const ralphService = createRalphService(kvService, 'test-project', createMockLogger(), { stallTimeoutMs: 1000 })
const mockClient = {
session: {
promptAsync: async () => ({ data: undefined, error: undefined }),
create: async () => ({ data: { id: 'test-session' }, error: undefined }),
messages: async () => ({ data: [] }),
status: async () => ({ data: {} }),
},
worktree: {
create: async () => ({ data: { id: 'wt-1', directory: '/tmp/wt', branch: 'main' }, error: undefined }),
remove: async () => ({ data: undefined, error: undefined }),
},
} as any
const mockV2Client = {
session: {
promptAsync: async () => ({ data: undefined, error: undefined }),
create: async () => ({ data: { id: 'test-session' }, error: undefined }),
messages: async () => ({ data: [] }),
status: async () => ({ data: {} }),
},
worktree: {
create: async () => ({ data: { id: 'wt-1', directory: '/tmp/wt', branch: 'main' }, error: undefined }),
remove: async () => ({ data: undefined, error: undefined }),
},
} as any
const { createRalphEventHandler } = require('../src/hooks/ralph')
const mockGetConfig = () => ({ ralph: {}, executionModel: undefined, auditorModel: undefined })
const handler = createRalphEventHandler(ralphService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const parentId = 'parent-session'
const childId = 'child-session'
ralphService.setState(parentId, {
active: true,
sessionId: parentId,
worktreeName: 'test',
worktreeDir: '/tmp/test',
worktreeBranch: 'main',
workspaceId: '',
iteration: 1,
maxIterations: 0,
completionPromise: null,
startedAt: new Date().toISOString(),
prompt: 'test',
phase: 'coding',
audit: false,
errorCount: 0,
auditCount: 0,
})
handler.startWatchdog(parentId)
const initialInfo = handler.getStallInfo(parentId)
const initialTime = initialInfo?.lastActivityTime
await handler.onEvent({
event: {
type: 'session.created',
properties: {
info: {
id: childId,
parentID: parentId,
},
},
},
})
const updatedInfo = handler.getStallInfo(parentId)
expect(updatedInfo?.lastActivityTime).toBeGreaterThanOrEqual(initialTime!)
})
test('session.status event updates activity time', async () => {
const db = createTestDb()
const kvService = createKvService(db)
const ralphService = createRalphService(kvService, 'test-project', createMockLogger(), { stallTimeoutMs: 1000 })
const mockClient = {
session: {
promptAsync: async () => ({ data: undefined, error: undefined }),
create: async () => ({ data: { id: 'test-session' }, error: undefined }),
messages: async () => ({ data: [] }),
status: async () => ({ data: {} }),
},
worktree: {
create: async () => ({ data: { id: 'wt-1', directory: '/tmp/wt', branch: 'main' }, error: undefined }),
remove: async () => ({ data: undefined, error: undefined }),
},
} as any
const mockV2Client = {
session: {
promptAsync: async () => ({ data: undefined, error: undefined }),
create: async () => ({ data: { id: 'test-session' }, error: undefined }),
messages: async () => ({ data: [] }),
status: async () => ({ data: {} }),
},
worktree: {
create: async () => ({ data: { id: 'wt-1', directory: '/tmp/wt', branch: 'main' }, error: undefined }),
remove: async () => ({ data: undefined, error: undefined }),
},
} as any
const { createRalphEventHandler } = require('../src/hooks/ralph')
const mockGetConfig = () => ({ ralph: {}, executionModel: undefined, auditorModel: undefined })
const handler = createRalphEventHandler(ralphService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const sessionId = 'test-session'
ralphService.setState(sessionId, {
active: true,
sessionId,
worktreeName: 'test',
worktreeDir: '/tmp/test',
worktreeBranch: 'main',
workspaceId: '',
iteration: 1,
maxIterations: 0,
completionPromise: null,
startedAt: new Date().toISOString(),
prompt: 'test',
phase: 'coding',
audit: false,
errorCount: 0,
auditCount: 0,
})
handler.startWatchdog(sessionId)
const initialInfo = handler.getStallInfo(sessionId)
const initialTime = initialInfo?.lastActivityTime
await new Promise(resolve => setTimeout(resolve, 10))
await handler.onEvent({
event: {
type: 'session.status',
properties: {
sessionID: sessionId,
},
},
})
const updatedInfo = handler.getStallInfo(sessionId)
expect(updatedInfo?.lastActivityTime).toBeGreaterThanOrEqual(initialTime!)
})
test('stopWatchdog cleans up all state', () => {
const db = createTestDb()
const kvService = createKvService(db)
const ralphService = createRalphService(kvService, 'test-project', createMockLogger(), { stallTimeoutMs: 1000 })
const mockClient = {
session: {
promptAsync: async () => ({ data: undefined, error: undefined }),
create: async () => ({ data: { id: 'test-session' }, error: undefined }),
messages: async () => ({ data: [] }),
status: async () => ({ data: {} }),
},
worktree: {
create: async () => ({ data: { id: 'wt-1', directory: '/tmp/wt', branch: 'main' }, error: undefined }),
remove: async () => ({ data: undefined, error: undefined }),
},
} as any
const mockV2Client = {
session: {
promptAsync: async () => ({ data: undefined, error: undefined }),
create: async () => ({ data: { id: 'test-session' }, error: undefined }),
messages: async () => ({ data: [] }),
status: async () => ({ data: {} }),
},
worktree: {
create: async () => ({ data: { id: 'wt-1', directory: '/tmp/wt', branch: 'main' }, error: undefined }),
remove: async () => ({ data: undefined, error: undefined }),
},
} as any
const { createRalphEventHandler } = require('../src/hooks/ralph')
const mockGetConfig = () => ({ ralph: {}, executionModel: undefined, auditorModel: undefined })
const handler = createRalphEventHandler(ralphService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
const sessionId = 'test-session'
ralphService.setState(sessionId, {
active: true,
sessionId,
worktreeName: 'test',
worktreeDir: '/tmp/test',
worktreeBranch: 'main',
workspaceId: '',
iteration: 1,
maxIterations: 0,
completionPromise: null,
startedAt: new Date().toISOString(),
prompt: 'test',
phase: 'coding',
audit: false,
errorCount: 0,
auditCount: 0,
})
handler.startWatchdog(sessionId)
expect(handler.getStallInfo(sessionId)).not.toBeNull()
handler.clearAllRetryTimeouts()
expect(handler.getStallInfo(sessionId)).toBeNull()
})
})
describe('Minimum Audits', () => {
test('getMinAudits returns configured value', () => {
const db = createTestDb()
const kvService = createKvService(db)
const ralphService = createRalphService(kvService, 'test-project', createMockLogger(), { minAudits: 2 })
expect(ralphService.getMinAudits()).toBe(2)
})
})
+59 -24
View File
@@ -1,24 +1,32 @@
import { describe, test, expect, beforeEach, afterEach } from 'bun:test'
import { loadPluginConfig, resolveConfigPath } from '../src/setup'
import { mkdirSync, rmSync, writeFileSync, existsSync } from 'fs'
import { mkdirSync, rmSync, writeFileSync, existsSync, copyFileSync } from 'fs'
import { join } from 'path'
import { homedir } from 'os'
const TEST_DIR = '/tmp/opencode-manager-memory-setup-test-' + Date.now()
describe('loadPluginConfig', () => {
let testDir: string
let testConfigDir: string
let testDataDir: string
beforeEach(() => {
testDir = TEST_DIR + '-' + Math.random().toString(36).slice(2)
mkdirSync(testDir, { recursive: true })
process.env['XDG_DATA_HOME'] = testDir
testConfigDir = TEST_DIR + '-config-' + Math.random().toString(36).slice(2)
testDataDir = TEST_DIR + '-data-' + Math.random().toString(36).slice(2)
mkdirSync(testConfigDir, { recursive: true })
mkdirSync(testDataDir, { recursive: true })
process.env['XDG_CONFIG_HOME'] = testConfigDir
process.env['XDG_DATA_HOME'] = testDataDir
})
afterEach(() => {
delete process.env['XDG_CONFIG_HOME']
delete process.env['XDG_DATA_HOME']
if (existsSync(testDir)) {
rmSync(testDir, { recursive: true, force: true })
if (existsSync(testConfigDir)) {
rmSync(testConfigDir, { recursive: true, force: true })
}
if (existsSync(testDataDir)) {
rmSync(testDataDir, { recursive: true, force: true })
}
})
@@ -30,8 +38,8 @@ describe('loadPluginConfig', () => {
})
test('reads and parses valid config file', () => {
const configPath = join(testDir, 'opencode', 'memory', 'config.json')
mkdirSync(join(testDir, 'opencode', 'memory'), { recursive: true })
const configPath = join(testConfigDir, 'opencode', 'memory-config.jsonc')
mkdirSync(join(testConfigDir, 'opencode'), { recursive: true })
const validConfig = {
embedding: {
@@ -55,8 +63,8 @@ describe('loadPluginConfig', () => {
})
test('returns defaults when file contains invalid JSON', () => {
const configPath = join(testDir, 'opencode', 'memory', 'config.json')
mkdirSync(join(testDir, 'opencode', 'memory'), { recursive: true })
const configPath = join(testConfigDir, 'opencode', 'memory-config.jsonc')
mkdirSync(join(testConfigDir, 'opencode'), { recursive: true })
writeFileSync(configPath, 'invalid json content')
@@ -65,8 +73,8 @@ describe('loadPluginConfig', () => {
})
test('returns defaults when file has wrong structure', () => {
const configPath = join(testDir, 'opencode', 'memory', 'config.json')
mkdirSync(join(testDir, 'opencode', 'memory'), { recursive: true })
const configPath = join(testConfigDir, 'opencode', 'memory-config.jsonc')
mkdirSync(join(testConfigDir, 'opencode'), { recursive: true })
const invalidConfig = {
embedding: {
@@ -81,32 +89,59 @@ describe('loadPluginConfig', () => {
const config = loadPluginConfig()
expect(config.embedding.provider).toBe('local')
})
test('migrates config from old data dir location to new config dir location', () => {
const oldConfigPath = join(testDataDir, 'opencode', 'memory', 'config.json')
const newConfigPath = join(testConfigDir, 'opencode', 'memory-config.jsonc')
mkdirSync(join(testDataDir, 'opencode', 'memory'), { recursive: true })
const oldConfig = {
embedding: {
provider: 'voyage',
model: 'voyage-code-3',
dimensions: 1024,
},
dedupThreshold: 0.35,
}
writeFileSync(oldConfigPath, JSON.stringify(oldConfig))
const config = loadPluginConfig()
expect(config.embedding.provider).toBe('voyage')
expect(config.embedding.model).toBe('voyage-code-3')
expect(config.dedupThreshold).toBe(0.35)
expect(existsSync(newConfigPath)).toBe(true)
})
})
describe('resolveConfigPath', () => {
let testDir: string
let testConfigDir: string
beforeEach(() => {
testDir = TEST_DIR + '-' + Math.random().toString(36).slice(2)
testConfigDir = TEST_DIR + '-configpath-' + Math.random().toString(36).slice(2)
mkdirSync(testConfigDir, { recursive: true })
})
afterEach(() => {
delete process.env['XDG_DATA_HOME']
if (existsSync(testDir)) {
rmSync(testDir, { recursive: true, force: true })
delete process.env['XDG_CONFIG_HOME']
if (existsSync(testConfigDir)) {
rmSync(testConfigDir, { recursive: true, force: true })
}
})
test('returns correct path based on XDG_DATA_HOME', () => {
process.env['XDG_DATA_HOME'] = testDir
test('returns correct path based on XDG_CONFIG_HOME', () => {
process.env['XDG_CONFIG_HOME'] = testConfigDir
const configPath = resolveConfigPath()
expect(configPath).toBe(join(testDir, 'opencode', 'memory', 'config.json'))
expect(configPath).toBe(join(testConfigDir, 'opencode', 'memory-config.jsonc'))
})
test('falls back to ~/.local/share when XDG_DATA_HOME is unset', () => {
delete process.env['XDG_DATA_HOME']
test('falls back to ~/.config when XDG_CONFIG_HOME is unset', () => {
delete process.env['XDG_CONFIG_HOME']
const configPath = resolveConfigPath()
const expectedDefault = join(homedir(), '.local', 'share', 'opencode', 'memory', 'config.json')
const expectedDefault = join(homedir(), '.config', 'opencode', 'memory-config.jsonc')
expect(configPath).toBe(expectedDefault)
})
})
@@ -0,0 +1,56 @@
import { describe, test, expect } from 'vitest'
import { stripPromiseTags } from '../src/utils/strip-promise-tags'
describe('stripPromiseTags', () => {
test('returns unchanged text when no promise tags present', () => {
const text = 'This is a normal plan without any special tags'
const { cleaned, stripped } = stripPromiseTags(text)
expect(cleaned).toBe(text)
expect(stripped).toBe(false)
})
test('strips bare promise tags', () => {
const text = 'Plan text here <promise>All phases of the plan have been completed successfully</promise>'
const { cleaned, stripped } = stripPromiseTags(text)
expect(cleaned).toBe('Plan text here')
expect(stripped).toBe(true)
expect(cleaned).not.toContain('<promise>')
})
test('strips full instruction block with promise tags', () => {
const text = `Plan text here
---
**IMPORTANT - Completion Signal:** When you have completed ALL phases of this plan successfully, you MUST output the following tag exactly: <promise>All phases of the plan have been completed successfully</promise>
Do NOT output this tag until every phase is truly complete. The loop will continue until this signal is detected.`
const { cleaned, stripped } = stripPromiseTags(text)
expect(cleaned).toBe('Plan text here')
expect(stripped).toBe(true)
expect(cleaned).not.toContain('<promise>')
expect(cleaned).not.toContain('Completion Signal')
})
test('preserves plan content before promise tags', () => {
const plan = `## Phase 1
Do something
## Phase 2
Do something else
<promise>DONE</promise>`
const { cleaned, stripped } = stripPromiseTags(plan)
expect(cleaned).toContain('## Phase 1')
expect(cleaned).toContain('## Phase 2')
expect(cleaned).not.toContain('<promise>')
expect(stripped).toBe(true)
})
test('handles promise tags with multiline content', () => {
const text = 'Plan <promise>\nMulti\nLine\nContent\n</promise> end'
const { cleaned, stripped } = stripPromiseTags(text)
expect(cleaned).not.toContain('<promise>')
expect(stripped).toBe(true)
})
})
+154
View File
@@ -0,0 +1,154 @@
import { describe, test, expect, beforeEach, afterEach } from 'bun:test'
import { Database } from 'bun:sqlite'
import { createKvService } from '../src/services/kv'
import { createRalphService } from '../src/services/ralph'
import type { Logger } from '../src/types'
const TEST_DIR = '/tmp/opencode-manager-tool-blocking-test-' + Date.now()
function createTestDb(): Database {
const db = new Database(`${TEST_DIR}-${Math.random().toString(36).slice(2)}.db`)
db.run(`
CREATE TABLE IF NOT EXISTS project_kv (
project_id TEXT NOT NULL,
key TEXT NOT NULL,
data TEXT NOT NULL,
expires_at INTEGER NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
PRIMARY KEY (project_id, key)
)
`)
db.run(`CREATE INDEX IF NOT EXISTS idx_project_kv_expires_at ON project_kv(expires_at)`)
return db
}
function createMockLogger(): Logger {
return {
log: () => {},
error: () => {},
debug: () => {},
}
}
describe('Tool Blocking Logic', () => {
let db: Database
let ralphService: ReturnType<typeof createRalphService>
const projectId = 'test-project'
const sessionID = 'test-session-123'
beforeEach(() => {
db = createTestDb()
const kvService = createKvService(db)
ralphService = createRalphService(kvService, projectId, createMockLogger())
})
afterEach(() => {
db.close()
})
describe('Ralph state lookup', () => {
test('getActiveState returns active state when Ralph loop is active', () => {
const state = {
active: true,
sessionId: sessionID,
worktreeName: 'test-worktree',
worktreeDir: '/test/worktree',
worktreeBranch: 'opencode/ralph-test',
workspaceId: 'wrk-test-worktree',
iteration: 1,
maxIterations: 5,
completionPromise: 'DONE',
startedAt: new Date().toISOString(),
prompt: 'Test prompt',
phase: 'coding' as const,
audit: false,
errorCount: 0,
auditCount: 0,
inPlace: false,
}
ralphService.setState(sessionID, state)
const retrieved = ralphService.getActiveState(sessionID)
expect(retrieved).toEqual(state)
expect(retrieved?.active).toBe(true)
})
test('getActiveState returns null when no Ralph loop exists', () => {
const retrieved = ralphService.getActiveState('non-existent-session')
expect(retrieved).toBeNull()
})
test('getActiveState returns null when Ralph loop is inactive', () => {
const inactiveState = {
active: false,
sessionId: sessionID,
worktreeName: 'test-worktree',
worktreeDir: '/test/worktree',
worktreeBranch: 'opencode/ralph-test',
workspaceId: 'wrk-test-worktree',
iteration: 1,
maxIterations: 5,
completionPromise: 'DONE',
startedAt: new Date().toISOString(),
prompt: 'Test prompt',
phase: 'coding' as const,
audit: false,
errorCount: 0,
auditCount: 0,
inPlace: false,
}
ralphService.setState(sessionID, inactiveState)
const retrieved = ralphService.getActiveState(sessionID)
expect(retrieved).toBeNull()
})
})
describe('Blocked tools list', () => {
test('includes question tool', () => {
const blockedTools = ['question', 'memory-plan-execute', 'memory-plan-ralph']
expect(blockedTools).toContain('question')
})
test('includes memory-plan-execute tool', () => {
const blockedTools = ['question', 'memory-plan-execute', 'memory-plan-ralph']
expect(blockedTools).toContain('memory-plan-execute')
})
test('includes memory-plan-ralph tool', () => {
const blockedTools = ['question', 'memory-plan-execute', 'memory-plan-ralph']
expect(blockedTools).toContain('memory-plan-ralph')
})
test('does not include memory-read tool', () => {
const blockedTools = ['question', 'memory-plan-execute', 'memory-plan-ralph']
expect(blockedTools).not.toContain('memory-read')
})
test('does not include memory-write tool', () => {
const blockedTools = ['question', 'memory-plan-execute', 'memory-plan-ralph']
expect(blockedTools).not.toContain('memory-write')
})
})
describe('Error messages', () => {
test('question tool has appropriate error message', () => {
const messages: 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.',
}
expect(messages['question']).toContain('question tool is not available')
})
test('memory-plan-execute tool has appropriate error message', () => {
const messages: 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.',
}
expect(messages['memory-plan-execute']).toContain('memory-plan-execute tool is not available')
})
})
})
+11
View File
@@ -284,6 +284,12 @@ importers:
'@opencode-ai/plugin':
specifier: ^1.2.16
version: 1.2.16
'@opencode-ai/sdk':
specifier: ^1.2.26
version: 1.2.26
jsonc-parser:
specifier: ^3.3.1
version: 3.3.1
sqlite-vec:
specifier: 0.1.7-alpha.2
version: 0.1.7-alpha.2
@@ -1000,6 +1006,9 @@ packages:
'@opencode-ai/sdk@1.2.16':
resolution: {integrity: sha512-y9ae9VnCcuog0GaI4DveX1HB6DBoZgGN3EuJVlRFbBCPwhzkls6fCfHSb5+VnTS6Fy0OWFUL28VBCmixL/D+/Q==}
'@opencode-ai/sdk@1.2.26':
resolution: {integrity: sha512-HPB+0pfvTMPj2KEjNLF3oqgldKW8koTJ7ssqXwzndazqxS+gUynzvdIKIQP4+QIInNcc5nJMG9JtfLcePGgTLQ==}
'@peculiar/asn1-android@2.6.0':
resolution: {integrity: sha512-cBRCKtYPF7vJGN76/yG8VbxRcHLPF3HnkoHhKOZeHpoVtbMYfY9ROKtH3DtYUY9m8uI1Mh47PRhHf2hSK3xcSQ==}
@@ -4949,6 +4958,8 @@ snapshots:
'@opencode-ai/sdk@1.2.16': {}
'@opencode-ai/sdk@1.2.26': {}
'@peculiar/asn1-android@2.6.0':
dependencies:
'@peculiar/asn1-schema': 2.6.0
+42
View File
@@ -86,6 +86,17 @@ export const MessagesTransformConfigSchema = z.object({
})
export type MessagesTransformConfig = z.infer<typeof MessagesTransformConfigSchema>
export const RalphConfigSchema = z.object({
enabled: z.boolean().optional(),
defaultMaxIterations: z.number().optional(),
cleanupWorktree: z.boolean().optional(),
defaultAudit: z.boolean().optional(),
model: z.string().optional(),
minAudits: z.number().optional(),
stallTimeoutMs: z.number().optional(),
})
export type RalphConfig = z.infer<typeof RalphConfigSchema>
export const PluginConfigSchema = z.object({
dataDir: z.string().optional(),
embedding: EmbeddingConfigSchema,
@@ -95,5 +106,36 @@ export const PluginConfigSchema = z.object({
memoryInjection: MemoryInjectionConfigSchema.optional(),
messagesTransform: MessagesTransformConfigSchema.optional(),
executionModel: z.string().optional(),
auditorModel: z.string().optional(),
ralph: RalphConfigSchema.optional(),
})
export type PluginConfig = z.infer<typeof PluginConfigSchema>
export const KvEntrySchema = z.object({
key: z.string(),
data: z.unknown(),
createdAt: z.number(),
updatedAt: z.number(),
expiresAt: z.number(),
})
export type KvEntry = z.infer<typeof KvEntrySchema>
export const KvListQuerySchema = z.object({
projectId: z.string(),
prefix: z.string().optional(),
})
export type KvListQuery = z.infer<typeof KvListQuerySchema>
export const CreateKvEntryRequestSchema = z.object({
projectId: z.string(),
key: z.string(),
data: z.unknown(),
ttlMs: z.number().optional(),
})
export type CreateKvEntryRequest = z.infer<typeof CreateKvEntryRequestSchema>
export const UpdateKvEntryRequestSchema = z.object({
data: z.unknown(),
ttlMs: z.number().optional(),
})
export type UpdateKvEntryRequest = z.infer<typeof UpdateKvEntryRequestSchema>
+4
View File
@@ -90,4 +90,8 @@ export type {
MemoryInjectionConfig,
MessagesTransformConfig,
PluginConfig,
KvEntry,
KvListQuery,
CreateKvEntryRequest,
UpdateKvEntryRequest,
} from '../schemas/memory'