mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
Update memory plugin (#160)
This commit is contained in:
1 parent
be7e64b07f
commit
1248d0b9e0
50 files changed
+5363
-291
No files matched your search
+255
-67
@@ -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
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
Reference in new issue
Block a user