mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
Add memory plugin with semantic search and session planning (#145)
* Add memory plugin with semantic search and session planning * Clarify Memory Plugin is optional in docs
This commit is contained in:
1 parent
da283a82cf
commit
3461f86556
132 files changed
+11448
-2834
No files matched your search
@@ -0,0 +1,175 @@
|
||||
import type { MemoryService } from './memory'
|
||||
import type { Logger } from '../types'
|
||||
|
||||
export interface EmbeddingSyncOptions {
|
||||
batchSize?: number
|
||||
maxRetries?: number
|
||||
}
|
||||
|
||||
export interface EmbeddingSyncResult {
|
||||
total: number
|
||||
embedded: number
|
||||
failed: number
|
||||
}
|
||||
|
||||
export class EmbeddingSyncService {
|
||||
private memoryService: MemoryService
|
||||
private logger?: Logger
|
||||
private batchSize: number
|
||||
private maxRetries: number
|
||||
private syncInProgress: boolean = false
|
||||
private static readonly MAX_ITERATIONS = 100
|
||||
|
||||
constructor(memoryService: MemoryService, logger?: Logger, options: EmbeddingSyncOptions = {}) {
|
||||
this.memoryService = memoryService
|
||||
this.logger = logger
|
||||
this.batchSize = options.batchSize ?? 50
|
||||
this.maxRetries = options.maxRetries ?? 3
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
this.logger?.log('[embedding-sync] Starting initial sync...')
|
||||
await this.syncAll()
|
||||
}
|
||||
|
||||
async syncAll(): Promise<EmbeddingSyncResult> {
|
||||
if (this.syncInProgress) {
|
||||
this.logger?.log('[embedding-sync] Sync already in progress, skipping')
|
||||
return { total: 0, embedded: 0, failed: 0 }
|
||||
}
|
||||
|
||||
this.syncInProgress = true
|
||||
let total = 0
|
||||
let embedded = 0
|
||||
let failed = 0
|
||||
|
||||
try {
|
||||
let pending = this.memoryService.countMemoriesWithoutEmbeddings()
|
||||
let iterations = 0
|
||||
|
||||
while (pending > 0 && iterations < EmbeddingSyncService.MAX_ITERATIONS) {
|
||||
iterations++
|
||||
const memories = this.memoryService.getMemoriesWithoutEmbeddings(undefined, this.batchSize)
|
||||
let batchSuccess = 0
|
||||
let batchFailed = 0
|
||||
|
||||
for (const memory of memories) {
|
||||
let success = false
|
||||
let attempts = 0
|
||||
|
||||
while (!success && attempts < this.maxRetries) {
|
||||
success = await this.memoryService.embedMemory(memory.id, memory.content)
|
||||
attempts++
|
||||
|
||||
if (!success && attempts < this.maxRetries) {
|
||||
this.logger?.log(`[embedding-sync] Retrying memory ${memory.id} (attempt ${attempts + 1}/${this.maxRetries})`)
|
||||
}
|
||||
}
|
||||
|
||||
total++
|
||||
|
||||
if (success) {
|
||||
embedded++
|
||||
batchSuccess++
|
||||
} else {
|
||||
failed++
|
||||
batchFailed++
|
||||
this.logger?.error(`[embedding-sync] Failed to embed memory ${memory.id} after ${this.maxRetries} attempts`)
|
||||
}
|
||||
}
|
||||
|
||||
if (batchSuccess === 0 && batchFailed > 0) {
|
||||
this.logger?.error('[embedding-sync] No memories embedded in this batch, stopping to prevent infinite loop')
|
||||
break
|
||||
}
|
||||
|
||||
pending = this.memoryService.countMemoriesWithoutEmbeddings()
|
||||
|
||||
if (pending > 0) {
|
||||
this.logger?.log(`[embedding-sync] Progress: ${embedded} embedded, ${failed} failed, ${pending} remaining`)
|
||||
}
|
||||
}
|
||||
|
||||
if (iterations >= EmbeddingSyncService.MAX_ITERATIONS) {
|
||||
this.logger?.error('[embedding-sync] Reached max iterations, stopping sync')
|
||||
}
|
||||
|
||||
this.logger?.log(`[embedding-sync] Complete: ${embedded} embedded, ${failed} failed`)
|
||||
} catch (error) {
|
||||
this.logger?.error('[embedding-sync] Sync error', error)
|
||||
} finally {
|
||||
this.syncInProgress = false
|
||||
}
|
||||
|
||||
return { total, embedded, failed }
|
||||
}
|
||||
|
||||
async syncProject(projectId: string): Promise<EmbeddingSyncResult> {
|
||||
let total = 0
|
||||
let embedded = 0
|
||||
let failed = 0
|
||||
|
||||
try {
|
||||
let pending = this.memoryService.countMemoriesWithoutEmbeddings(projectId)
|
||||
let iterations = 0
|
||||
|
||||
while (pending > 0 && iterations < EmbeddingSyncService.MAX_ITERATIONS) {
|
||||
iterations++
|
||||
const memories = this.memoryService.getMemoriesWithoutEmbeddings(projectId, this.batchSize)
|
||||
let batchSuccess = 0
|
||||
let batchFailed = 0
|
||||
|
||||
for (const memory of memories) {
|
||||
let success = false
|
||||
let attempts = 0
|
||||
|
||||
while (!success && attempts < this.maxRetries) {
|
||||
success = await this.memoryService.embedMemory(memory.id, memory.content)
|
||||
attempts++
|
||||
|
||||
if (!success && attempts < this.maxRetries) {
|
||||
await new Promise(resolve => setTimeout(resolve, 100))
|
||||
}
|
||||
}
|
||||
|
||||
total++
|
||||
|
||||
if (success) {
|
||||
embedded++
|
||||
batchSuccess++
|
||||
} else {
|
||||
failed++
|
||||
batchFailed++
|
||||
}
|
||||
}
|
||||
|
||||
if (batchSuccess === 0 && batchFailed > 0) {
|
||||
this.logger?.error('[embedding-sync] No memories embedded in this batch, stopping to prevent infinite loop')
|
||||
break
|
||||
}
|
||||
|
||||
pending = this.memoryService.countMemoriesWithoutEmbeddings(projectId)
|
||||
}
|
||||
|
||||
if (iterations >= EmbeddingSyncService.MAX_ITERATIONS) {
|
||||
this.logger?.error('[embedding-sync] Reached max iterations, stopping sync')
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger?.error(`[embedding-sync] Sync error for project ${projectId}`, error)
|
||||
}
|
||||
|
||||
return { total, embedded, failed }
|
||||
}
|
||||
|
||||
isSyncInProgress(): boolean {
|
||||
return this.syncInProgress
|
||||
}
|
||||
}
|
||||
|
||||
export function createEmbeddingSyncService(
|
||||
memoryService: MemoryService,
|
||||
logger?: Logger,
|
||||
options?: EmbeddingSyncOptions
|
||||
): EmbeddingSyncService {
|
||||
return new EmbeddingSyncService(memoryService, logger, options)
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { createMemoryQuery, type CreateMemoryInput, type UpdateMemoryInput, type MemorySearchResult } from '../storage'
|
||||
import type { VecService } from '../storage/vec-types'
|
||||
import { createNoopVecService } from '../storage/vec'
|
||||
import { type EmbeddingService, type EmbeddingProvider, createEmbeddingService } from '../embedding'
|
||||
import { type CacheService, createCacheService } from '../cache'
|
||||
import type { Memory, MemoryScope, MemoryStats, Logger } from '../types'
|
||||
|
||||
const DEFAULT_DEDUP_THRESHOLD = 0.25
|
||||
|
||||
function createNoopEmbeddingProvider(): EmbeddingProvider {
|
||||
return {
|
||||
dimensions: 0,
|
||||
name: 'noop',
|
||||
ready: false,
|
||||
embed: async () => [],
|
||||
test: async () => false,
|
||||
warmup: () => {},
|
||||
}
|
||||
}
|
||||
|
||||
export interface MemoryServiceDeps {
|
||||
db: Database
|
||||
provider?: EmbeddingProvider
|
||||
embeddingService: EmbeddingService
|
||||
cache: CacheService
|
||||
vec?: VecService
|
||||
logger?: Logger
|
||||
}
|
||||
|
||||
export class MemoryService {
|
||||
private queries: ReturnType<typeof createMemoryQuery>
|
||||
private dedupThreshold: number = DEFAULT_DEDUP_THRESHOLD
|
||||
private embeddingService: EmbeddingService
|
||||
private provider: EmbeddingProvider
|
||||
private cache: CacheService
|
||||
private vec: VecService
|
||||
private db: Database
|
||||
private logger?: Logger
|
||||
|
||||
constructor(deps: MemoryServiceDeps) {
|
||||
this.db = deps.db
|
||||
this.provider = deps.provider ?? createNoopEmbeddingProvider()
|
||||
this.embeddingService = deps.embeddingService
|
||||
this.cache = deps.cache
|
||||
this.vec = deps.vec ?? createNoopVecService()
|
||||
this.logger = deps.logger
|
||||
this.queries = createMemoryQuery(this.db, this.vec, deps.logger)
|
||||
}
|
||||
|
||||
setDedupThreshold(threshold: number): void {
|
||||
this.dedupThreshold = Math.max(0.05, Math.min(0.40, threshold))
|
||||
}
|
||||
|
||||
setVecService(vec: VecService): void {
|
||||
this.vec = vec
|
||||
this.queries = createMemoryQuery(this.db, this.vec, this.logger)
|
||||
}
|
||||
|
||||
async create(input: CreateMemoryInput): Promise<{ id: number; deduplicated: boolean }> {
|
||||
const existingMemory = this.queries.getByContent(input.projectId, input.content)
|
||||
if (existingMemory) {
|
||||
return { id: existingMemory.id, deduplicated: true }
|
||||
}
|
||||
|
||||
const embedding = await this.embeddingService.embedText(input.content)
|
||||
const similar = await this.queries.findSimilar(embedding, input.projectId, this.dedupThreshold, 1)
|
||||
if (similar.length > 0) {
|
||||
return { id: similar[0]!.id, deduplicated: true }
|
||||
}
|
||||
|
||||
try {
|
||||
this.db.exec('BEGIN IMMEDIATE')
|
||||
const duplicateCheck = this.queries.getByContent(input.projectId, input.content)
|
||||
if (duplicateCheck) {
|
||||
this.db.exec('COMMIT')
|
||||
return { id: duplicateCheck.id, deduplicated: true }
|
||||
}
|
||||
|
||||
const memoryId = this.queries.createInDb(input)
|
||||
this.db.exec('COMMIT')
|
||||
|
||||
if (this.vec.available && embedding.length > 0) {
|
||||
try {
|
||||
await this.vec.insert(embedding, memoryId, input.projectId)
|
||||
} catch (error) {
|
||||
this.queries.logError?.('Failed to insert embedding for memory', error)
|
||||
}
|
||||
}
|
||||
|
||||
await this.invalidateCache(input.projectId)
|
||||
return { id: memoryId, deduplicated: false }
|
||||
} catch (error) {
|
||||
try {
|
||||
this.db.exec('ROLLBACK')
|
||||
} catch {
|
||||
// Ignore rollback errors
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async update(id: number, input: UpdateMemoryInput): Promise<void> {
|
||||
const existing = this.queries.getById(id)
|
||||
if (!existing) {
|
||||
throw new Error(`Memory ${id} not found`)
|
||||
}
|
||||
|
||||
this.queries.update(id, input)
|
||||
|
||||
if (input.content !== undefined) {
|
||||
const embedding = await this.embeddingService.embedText(input.content)
|
||||
await this.queries.updateEmbedding(id, embedding)
|
||||
}
|
||||
|
||||
await this.invalidateCache(existing.projectId)
|
||||
}
|
||||
|
||||
async delete(id: number): Promise<void> {
|
||||
const existing = this.queries.getById(id)
|
||||
if (!existing) {
|
||||
throw new Error(`Memory ${id} not found`)
|
||||
}
|
||||
|
||||
await this.queries.delete(id)
|
||||
await this.invalidateCache(existing.projectId)
|
||||
}
|
||||
|
||||
getById(id: number): Memory | undefined {
|
||||
const memory = this.queries.getById(id)
|
||||
if (memory) {
|
||||
this.queries.trackAccess(id)
|
||||
}
|
||||
return memory
|
||||
}
|
||||
|
||||
listByProject(
|
||||
projectId: string,
|
||||
filters?: {
|
||||
scope?: MemoryScope
|
||||
limit?: number
|
||||
offset?: number
|
||||
}
|
||||
): Memory[] {
|
||||
const memories = this.queries.listByProject(projectId, filters)
|
||||
memories.forEach((m: Memory) => this.queries.trackAccess(m.id))
|
||||
return memories
|
||||
}
|
||||
|
||||
listAll(
|
||||
filters?: {
|
||||
projectId?: string
|
||||
scope?: MemoryScope
|
||||
limit?: number
|
||||
offset?: number
|
||||
}
|
||||
): Memory[] {
|
||||
const memories = this.queries.listAll(filters)
|
||||
memories.forEach((m: Memory) => this.queries.trackAccess(m.id))
|
||||
return memories
|
||||
}
|
||||
|
||||
async search(
|
||||
query: string,
|
||||
projectId?: string,
|
||||
filters?: {
|
||||
scope?: MemoryScope
|
||||
limit?: number
|
||||
}
|
||||
): Promise<MemorySearchResult[]> {
|
||||
const embedding = await this.embeddingService.embedText(query)
|
||||
const results = await this.queries.search(embedding, projectId, filters)
|
||||
results.forEach((r) => this.queries.trackAccess(r.memory.id))
|
||||
return results
|
||||
}
|
||||
|
||||
getStats(projectId: string): MemoryStats {
|
||||
const stats = this.queries.getStats(projectId)
|
||||
return {
|
||||
projectId,
|
||||
total: stats.total,
|
||||
byScope: stats.byScope,
|
||||
}
|
||||
}
|
||||
|
||||
async deleteByProject(projectId: string): Promise<void> {
|
||||
await this.queries.deleteByProject(projectId)
|
||||
await this.invalidateCache(projectId)
|
||||
}
|
||||
|
||||
async deleteByFilePath(projectId: string, filePath: string): Promise<void> {
|
||||
await this.queries.deleteByFilePath(projectId, filePath)
|
||||
await this.invalidateCache(projectId)
|
||||
}
|
||||
|
||||
countByProject(projectId: string): number {
|
||||
return this.queries.countByProject(projectId)
|
||||
}
|
||||
|
||||
getMemoriesWithoutEmbeddings(projectId?: string, limit: number = 50): Memory[] {
|
||||
return this.queries.getMemoriesWithoutEmbeddings(projectId, limit)
|
||||
}
|
||||
|
||||
countMemoriesWithoutEmbeddings(projectId?: string): number {
|
||||
return this.queries.countMemoriesWithoutEmbeddings(projectId)
|
||||
}
|
||||
|
||||
async embedMemory(memoryId: number, content: string): Promise<boolean> {
|
||||
try {
|
||||
const embedding = await this.embeddingService.embedText(content)
|
||||
if (embedding.length > 0) {
|
||||
await this.queries.updateEmbedding(memoryId, embedding)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
async reindex(projectId?: string): Promise<{ total: number; success: number; failed: number }> {
|
||||
const allMemories = projectId
|
||||
? this.queries.listByProject(projectId, { limit: 10000 })
|
||||
: this.queries.listAll({ limit: 10000 })
|
||||
|
||||
let success = 0
|
||||
let failed = 0
|
||||
const batchSize = 50
|
||||
|
||||
for (let i = 0; i < allMemories.length; i += batchSize) {
|
||||
const batch = allMemories.slice(i, i + batchSize)
|
||||
const texts = batch.map(m => m.content)
|
||||
|
||||
try {
|
||||
const embeddings = await this.embeddingService.embedTexts(texts)
|
||||
|
||||
for (let j = 0; j < batch.length; j++) {
|
||||
try {
|
||||
await this.queries.updateEmbedding(batch[j]!.id, embeddings[j]!)
|
||||
success++
|
||||
} catch {
|
||||
failed++
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
failed += batch.length
|
||||
}
|
||||
}
|
||||
|
||||
if (projectId) {
|
||||
await this.invalidateCache(projectId)
|
||||
} else {
|
||||
await this.invalidateCache('*')
|
||||
}
|
||||
|
||||
return { total: allMemories.length, success, failed }
|
||||
}
|
||||
|
||||
private async invalidateCache(projectId: string): Promise<void> {
|
||||
try {
|
||||
await this.cache.invalidatePattern(`mem:project:${projectId}:*`)
|
||||
} catch {
|
||||
// Silent failure
|
||||
}
|
||||
}
|
||||
|
||||
async destroy(): Promise<void> {
|
||||
this.vec.dispose()
|
||||
this.cache.destroy()
|
||||
if (this.provider.dispose) {
|
||||
await this.provider.dispose()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export interface CreateMemoryServiceOptions {
|
||||
db: Database
|
||||
provider: EmbeddingProvider
|
||||
vec: VecService
|
||||
logger?: Logger
|
||||
}
|
||||
|
||||
export async function createMemoryService(options: CreateMemoryServiceOptions): Promise<MemoryService> {
|
||||
const cache = createCacheService()
|
||||
const embeddingService = createEmbeddingService(options.provider, cache)
|
||||
|
||||
return new MemoryService({
|
||||
db: options.db,
|
||||
provider: options.provider,
|
||||
embeddingService,
|
||||
cache,
|
||||
vec: options.vec,
|
||||
logger: options.logger,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { createSessionStateQueries } from '../storage/session-state-queries'
|
||||
import type { SessionState, PlanningState, PreCompactionSnapshot } from '../types'
|
||||
|
||||
const DEFAULT_SESSION_TTL = 7 * 24 * 60 * 60 * 1000
|
||||
const DEFAULT_SNAPSHOT_TTL = 24 * 60 * 60 * 1000
|
||||
|
||||
export class SessionStateService {
|
||||
private queries: ReturnType<typeof createSessionStateQueries>
|
||||
private cleanupInterval: ReturnType<typeof setInterval> | null = null
|
||||
private logger?: { log: (msg: string, ...args: unknown[]) => void; error: (msg: string, ...args: unknown[]) => void }
|
||||
|
||||
constructor(db: Database, logger?: { log: (msg: string, ...args: unknown[]) => void; error: (msg: string, ...args: unknown[]) => void }) {
|
||||
this.queries = createSessionStateQueries(db)
|
||||
this.logger = logger
|
||||
}
|
||||
|
||||
get<T>(key: string): T | null {
|
||||
const row = this.queries.get(key)
|
||||
if (!row) return null
|
||||
try {
|
||||
return JSON.parse(row.data) as T
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
set<T>(key: string, projectId: string, data: T, ttlMs?: number): void {
|
||||
const expiresAt = ttlMs ? Date.now() + ttlMs : null
|
||||
const jsonData = JSON.stringify(data)
|
||||
this.queries.set(key, projectId, jsonData, expiresAt)
|
||||
}
|
||||
|
||||
delete(key: string): void {
|
||||
this.queries.delete(key)
|
||||
}
|
||||
|
||||
deleteByPrefix(prefix: string): void {
|
||||
this.queries.deleteByPrefix(prefix)
|
||||
}
|
||||
|
||||
deleteExpired(): number {
|
||||
return this.queries.deleteExpired()
|
||||
}
|
||||
|
||||
listByProject(projectId: string): SessionState[] {
|
||||
const rows = this.queries.listByProject(projectId)
|
||||
return rows.map((row): SessionState => ({
|
||||
key: row.key,
|
||||
projectId: row.project_id,
|
||||
data: JSON.parse(row.data),
|
||||
expiresAt: row.expires_at,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
}))
|
||||
}
|
||||
|
||||
startCleanupInterval(intervalMs: number = 30 * 60 * 1000): void {
|
||||
if (this.cleanupInterval) return
|
||||
this.cleanupInterval = setInterval(() => {
|
||||
try {
|
||||
const deleted = this.deleteExpired()
|
||||
if (deleted > 0 && this.logger) {
|
||||
this.logger.log(`Cleaned up ${deleted} expired session state entries`)
|
||||
}
|
||||
} catch (error) {
|
||||
if (this.logger) {
|
||||
this.logger.error('Failed to clean up expired session state', error)
|
||||
}
|
||||
}
|
||||
}, intervalMs)
|
||||
}
|
||||
|
||||
stopCleanupInterval(): void {
|
||||
if (this.cleanupInterval) {
|
||||
clearInterval(this.cleanupInterval)
|
||||
this.cleanupInterval = null
|
||||
}
|
||||
}
|
||||
|
||||
destroy(): void {
|
||||
this.stopCleanupInterval()
|
||||
}
|
||||
|
||||
setPlanningState(sessionId: string, projectId: string, planningState: PlanningState): void {
|
||||
const key = `session:${sessionId}`
|
||||
this.set(key, projectId, planningState, DEFAULT_SESSION_TTL)
|
||||
}
|
||||
|
||||
getPlanningState(sessionId: string): PlanningState | null {
|
||||
const key = `session:${sessionId}`
|
||||
return this.get<PlanningState>(key)
|
||||
}
|
||||
|
||||
setCompactionSnapshot(sessionId: string, projectId: string, snapshot: PreCompactionSnapshot): void {
|
||||
const key = `compaction:snapshot:${sessionId}`
|
||||
this.set(key, projectId, snapshot, DEFAULT_SNAPSHOT_TTL)
|
||||
}
|
||||
|
||||
getCompactionSnapshot(sessionId: string): PreCompactionSnapshot | null {
|
||||
const key = `compaction:snapshot:${sessionId}`
|
||||
return this.get<PreCompactionSnapshot>(key)
|
||||
}
|
||||
}
|
||||
|
||||
export function createSessionStateService(
|
||||
db: Database,
|
||||
logger?: { log: (msg: string, ...args: unknown[]) => void; error: (msg: string, ...args: unknown[]) => void }
|
||||
): SessionStateService {
|
||||
return new SessionStateService(db, logger)
|
||||
}
|
||||
Reference in new issue
Block a user