mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
Clean up and enhance memory plugin (#151)
* refactor storage to use worker-based vector operations * update memory service and agent implementations * update opencode plugin sdk * update memory plugin documentation * add tests for memory service and injection hook * update lockfile for dependency changes * Add memory plugin v0.0.13 with message deduplication and config UI * Remove planning state feature from memory plugin
This commit is contained in:
1 parent
47ef830cbb
commit
6ef68774d8
53 files changed
+1683
-1885
No files matched your search
@@ -97,20 +97,6 @@ export function initializeDatabase(dataDir: string): Database {
|
||||
db.run(`CREATE INDEX IF NOT EXISTS idx_memories_project_id ON memories(project_id)`)
|
||||
db.run(`CREATE INDEX IF NOT EXISTS idx_memories_scope ON memories(scope)`)
|
||||
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS session_state (
|
||||
key TEXT PRIMARY KEY,
|
||||
project_id TEXT NOT NULL,
|
||||
data TEXT NOT NULL,
|
||||
expires_at INTEGER,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
)
|
||||
`)
|
||||
|
||||
db.run(`CREATE INDEX IF NOT EXISTS idx_session_state_project_id ON session_state(project_id)`)
|
||||
db.run(`CREATE INDEX IF NOT EXISTS idx_session_state_expires_at ON session_state(expires_at)`)
|
||||
|
||||
runMigrations(db)
|
||||
|
||||
db.run(`
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
export { initializeDatabase, closeDatabase, resolveDataDir, resolveLogPath } from './database'
|
||||
export { createVecService } from './vec'
|
||||
export { getTableDimensions, recreateVecTable } from './vec-utils'
|
||||
export type { TableDimensionsResult } from './vec-utils'
|
||||
export type { VecService, VecSearchResult } from './vec-types'
|
||||
export type { VecService, VecSearchResult, TableDimensionsResult } from './vec-types'
|
||||
export { createMemoryQuery } from './memory-queries'
|
||||
export { createSessionStateQueries } from './session-state-queries'
|
||||
export { createMetadataQuery } from './metadata-queries'
|
||||
|
||||
export type {
|
||||
@@ -15,8 +12,5 @@ export type {
|
||||
MemorySearchResult,
|
||||
MemoryStats,
|
||||
ListMemoriesFilter,
|
||||
SessionState,
|
||||
PlanningState,
|
||||
PreCompactionSnapshot,
|
||||
CompactionConfig,
|
||||
} from '../types'
|
||||
@@ -36,7 +36,15 @@ interface Logger {
|
||||
export function createMemoryQuery(db: Database, vec: VecService, logger?: Logger) {
|
||||
const logError = (context: string, error?: unknown) => {
|
||||
if (logger) {
|
||||
logger.error(context, error)
|
||||
const errorMessage = error instanceof Error ? error.message : String(error)
|
||||
const errorStack = error instanceof Error ? error.stack : undefined
|
||||
logger.error(context, { message: errorMessage, stack: errorStack })
|
||||
}
|
||||
}
|
||||
|
||||
const logInfo = (message: string) => {
|
||||
if (logger) {
|
||||
logger.log(message)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -227,6 +235,7 @@ export function createMemoryQuery(db: Database, vec: VecService, logger?: Logger
|
||||
: { scope: filters?.scope, limit: filters?.limit }
|
||||
|
||||
const memories = this.listAll(basicFilters)
|
||||
logInfo(`memory-queries: vec unavailable, returning ${memories.length} unranked results`)
|
||||
return memories.map(memory => ({ memory, distance: 1.0 }))
|
||||
}
|
||||
|
||||
@@ -238,6 +247,7 @@ export function createMemoryQuery(db: Database, vec: VecService, logger?: Logger
|
||||
? { projectId, scope: filters?.scope, limit: filters?.limit }
|
||||
: { scope: filters?.scope, limit: filters?.limit }
|
||||
const memories = this.listAll(basicFilters)
|
||||
logInfo(`memory-queries: vec returned 0 results (no embeddings?), returning ${memories.length} unranked results`)
|
||||
return memories.map(memory => ({ memory, distance: 1.0 }))
|
||||
}
|
||||
|
||||
@@ -251,18 +261,23 @@ export function createMemoryQuery(db: Database, vec: VecService, logger?: Logger
|
||||
WHERE id IN (${placeholders})
|
||||
`).all(...memoryIds) as MemoryRow[]
|
||||
|
||||
return rows
|
||||
const results = rows
|
||||
.map(row => ({
|
||||
memory: mapRow(row),
|
||||
distance: distanceMap.get(row.id) ?? 1.0,
|
||||
}))
|
||||
.sort((a, b) => a.distance - b.distance)
|
||||
} catch {
|
||||
|
||||
logInfo(`memory-queries: vec returned ${vecResults.length} ranked results`)
|
||||
return results
|
||||
} catch (error) {
|
||||
logError('memory-queries: vec search error, returning unranked results', error)
|
||||
const basicFilters = projectId
|
||||
? { projectId, scope: filters?.scope, limit: filters?.limit }
|
||||
: { scope: filters?.scope, limit: filters?.limit }
|
||||
|
||||
const memories = this.listAll(basicFilters)
|
||||
logInfo(`memory-queries: returning ${memories.length} unranked results after error`)
|
||||
return memories.map(memory => ({ memory, distance: 1.0 }))
|
||||
}
|
||||
},
|
||||
@@ -312,93 +327,25 @@ export function createMemoryQuery(db: Database, vec: VecService, logger?: Logger
|
||||
return !!result
|
||||
},
|
||||
|
||||
getMemoriesWithoutEmbeddings(
|
||||
async getMemoriesWithoutEmbeddings(
|
||||
projectId?: string,
|
||||
limit: number = 50
|
||||
): Memory[] {
|
||||
const embeddingsTableExists = db.prepare(
|
||||
"SELECT name FROM sqlite_master WHERE type='table' AND name='memory_embeddings'"
|
||||
).get()
|
||||
): Promise<Memory[]> {
|
||||
const rows = await vec.getWithoutEmbeddings(projectId, limit)
|
||||
if (rows.length === 0) return []
|
||||
|
||||
if (!embeddingsTableExists) {
|
||||
const conditions: string[] = []
|
||||
const params: (string | number)[] = []
|
||||
|
||||
if (projectId) {
|
||||
conditions.push('project_id = ?')
|
||||
params.push(projectId)
|
||||
}
|
||||
|
||||
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''
|
||||
const rows = db.prepare(`
|
||||
SELECT id, project_id, scope, content, file_path, access_count, last_accessed_at, created_at, updated_at
|
||||
FROM memories
|
||||
${where}
|
||||
ORDER BY created_at ASC
|
||||
LIMIT ? OFFSET 0
|
||||
`).all(...params, limit) as MemoryRow[]
|
||||
|
||||
return rows.map(mapRow)
|
||||
}
|
||||
|
||||
const conditions: string[] = ['e.memory_id IS NULL']
|
||||
const params: (string | number)[] = []
|
||||
|
||||
if (projectId) {
|
||||
conditions.push('m.project_id = ?')
|
||||
params.push(projectId)
|
||||
}
|
||||
|
||||
const rows = db.prepare(`
|
||||
SELECT m.id, m.project_id, m.scope, m.content, m.file_path, m.access_count, m.last_accessed_at, m.created_at, m.updated_at
|
||||
FROM memories m
|
||||
LEFT JOIN memory_embeddings e ON m.id = e.memory_id
|
||||
WHERE ${conditions.join(' AND ')}
|
||||
ORDER BY m.created_at ASC
|
||||
LIMIT ? OFFSET 0
|
||||
`).all(...params, limit) as MemoryRow[]
|
||||
|
||||
return rows.map(mapRow)
|
||||
const ids = rows.map(r => r.id)
|
||||
const placeholders = ids.map(() => '?').join(',')
|
||||
const memories = db.prepare(`
|
||||
SELECT id, project_id, scope, content, file_path, access_count, last_accessed_at, created_at, updated_at
|
||||
FROM memories WHERE id IN (${placeholders})
|
||||
ORDER BY created_at ASC
|
||||
`).all(...ids) as MemoryRow[]
|
||||
return memories.map(mapRow)
|
||||
},
|
||||
|
||||
countMemoriesWithoutEmbeddings(projectId?: string): number {
|
||||
const embeddingsTableExists = db.prepare(
|
||||
"SELECT name FROM sqlite_master WHERE type='table' AND name='memory_embeddings'"
|
||||
).get()
|
||||
|
||||
if (!embeddingsTableExists) {
|
||||
const conditions: string[] = []
|
||||
const params: (string | number)[] = []
|
||||
|
||||
if (projectId) {
|
||||
conditions.push('project_id = ?')
|
||||
params.push(projectId)
|
||||
}
|
||||
|
||||
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''
|
||||
const result = db.prepare(`
|
||||
SELECT COUNT(*) as count FROM memories ${where}
|
||||
`).get(...params) as { count: number }
|
||||
|
||||
return result.count
|
||||
}
|
||||
|
||||
const conditions: string[] = ['e.memory_id IS NULL']
|
||||
const params: (string | number)[] = []
|
||||
|
||||
if (projectId) {
|
||||
conditions.push('m.project_id = ?')
|
||||
params.push(projectId)
|
||||
}
|
||||
|
||||
const result = db.prepare(`
|
||||
SELECT COUNT(*) as count
|
||||
FROM memories m
|
||||
LEFT JOIN memory_embeddings e ON m.id = e.memory_id
|
||||
WHERE ${conditions.join(' AND ')}
|
||||
`).get(...params) as { count: number }
|
||||
|
||||
return result.count
|
||||
async countMemoriesWithoutEmbeddings(projectId?: string): Promise<number> {
|
||||
return vec.countWithoutEmbeddings(projectId)
|
||||
},
|
||||
|
||||
getByContent(projectId: string, content: string): Memory | undefined {
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
|
||||
export interface SessionStateRow {
|
||||
key: string
|
||||
project_id: string
|
||||
data: string
|
||||
expires_at: number | null
|
||||
created_at: number
|
||||
updated_at: number
|
||||
}
|
||||
|
||||
function mapRow(row: {
|
||||
key: string
|
||||
project_id: string
|
||||
data: string
|
||||
expires_at: number | null
|
||||
created_at: number
|
||||
updated_at: number
|
||||
}): SessionStateRow {
|
||||
return row
|
||||
}
|
||||
|
||||
function escapeLikeWildcards(value: string): string {
|
||||
return value.replace(/\\/g, '\\\\').replace(/%/g, '\\%').replace(/_/g, '\\_')
|
||||
}
|
||||
|
||||
type SessionStateRowRaw = Parameters<typeof mapRow>[0]
|
||||
|
||||
export function createSessionStateQueries(db: Database) {
|
||||
const getStmt = db.prepare(
|
||||
`SELECT key, project_id, data, expires_at, created_at, updated_at
|
||||
FROM session_state
|
||||
WHERE key = ? AND (expires_at IS NULL OR expires_at > ?)`
|
||||
)
|
||||
|
||||
const setStmt = db.prepare(
|
||||
`INSERT INTO session_state (key, project_id, data, expires_at, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(key) DO UPDATE SET
|
||||
data = excluded.data,
|
||||
expires_at = excluded.expires_at,
|
||||
updated_at = excluded.updated_at`
|
||||
)
|
||||
|
||||
const deleteStmt = db.prepare(`DELETE FROM session_state WHERE key = ?`)
|
||||
|
||||
const deleteByPrefixStmt = db.prepare(
|
||||
`DELETE FROM session_state WHERE key LIKE ?`
|
||||
)
|
||||
|
||||
const deleteExpiredStmt = db.prepare(
|
||||
`DELETE FROM session_state WHERE expires_at IS NOT NULL AND expires_at < ?`
|
||||
)
|
||||
|
||||
const listByProjectStmt = db.prepare(
|
||||
`SELECT key, project_id, data, expires_at, created_at, updated_at
|
||||
FROM session_state
|
||||
WHERE project_id = ? AND (expires_at IS NULL OR expires_at > ?)
|
||||
ORDER BY updated_at DESC`
|
||||
)
|
||||
|
||||
const searchByProjectAndPrefixStmt = db.prepare(
|
||||
`SELECT key, project_id, data, expires_at, created_at, updated_at
|
||||
FROM session_state
|
||||
WHERE project_id = ? AND key LIKE ? AND data LIKE ? ESCAPE '\\' AND (expires_at IS NULL OR expires_at > ?)
|
||||
ORDER BY updated_at DESC`
|
||||
)
|
||||
|
||||
const listByProjectAndPrefixStmt = db.prepare(
|
||||
`SELECT key, project_id, data, expires_at, created_at, updated_at
|
||||
FROM session_state
|
||||
WHERE project_id = ? AND key LIKE ? AND (expires_at IS NULL OR expires_at > ?)
|
||||
ORDER BY updated_at DESC`
|
||||
)
|
||||
|
||||
return {
|
||||
get(key: string): SessionStateRow | undefined {
|
||||
const now = Date.now()
|
||||
const row = getStmt.get(key, now) as SessionStateRowRaw | null
|
||||
return row ? mapRow(row) : undefined
|
||||
},
|
||||
|
||||
set(key: string, projectId: string, data: string, expiresAt: number | null): void {
|
||||
const now = Date.now()
|
||||
setStmt.run(key, projectId, data, expiresAt, now, now)
|
||||
},
|
||||
|
||||
delete(key: string): void {
|
||||
deleteStmt.run(key)
|
||||
},
|
||||
|
||||
deleteByPrefix(prefix: string): void {
|
||||
const pattern = prefix.endsWith('*') ? prefix.slice(0, -1) + '%' : `${prefix}%`
|
||||
deleteByPrefixStmt.run(pattern)
|
||||
},
|
||||
|
||||
deleteExpired(): number {
|
||||
const now = Date.now()
|
||||
const result = deleteExpiredStmt.run(now)
|
||||
return result.changes
|
||||
},
|
||||
|
||||
listByProject(projectId: string): SessionStateRow[] {
|
||||
const now = Date.now()
|
||||
const rows = listByProjectStmt.all(projectId, now) as SessionStateRowRaw[]
|
||||
return rows.map(mapRow)
|
||||
},
|
||||
|
||||
searchByProjectAndPrefix(projectId: string, keyPrefix: string, searchTerm: string): SessionStateRow[] {
|
||||
const now = Date.now()
|
||||
const keyPattern = `${escapeLikeWildcards(keyPrefix)}%`
|
||||
const searchPattern = `%${escapeLikeWildcards(searchTerm)}%`
|
||||
const rows = searchByProjectAndPrefixStmt.all(projectId, keyPattern, searchPattern, now) as SessionStateRowRaw[]
|
||||
return rows.map(mapRow)
|
||||
},
|
||||
|
||||
listByProjectAndPrefix(projectId: string, keyPrefix: string): SessionStateRow[] {
|
||||
const now = Date.now()
|
||||
const keyPattern = `${escapeLikeWildcards(keyPrefix)}%`
|
||||
const rows = listByProjectAndPrefixStmt.all(projectId, keyPattern, now) as SessionStateRowRaw[]
|
||||
return rows.map(mapRow)
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -84,7 +84,10 @@ async function startWorker(config: {
|
||||
|
||||
cleanupStale(pidPath, socketPath)
|
||||
|
||||
const workerScript = join(__dirname, 'vec-worker.ts')
|
||||
const workerScriptJs = join(__dirname, 'vec-worker.js')
|
||||
const workerScript = existsSync(workerScriptJs)
|
||||
? workerScriptJs
|
||||
: join(__dirname, 'vec-worker.ts')
|
||||
const proc = spawn('bun', [
|
||||
workerScript,
|
||||
'--db', config.dbPath,
|
||||
@@ -174,6 +177,27 @@ export async function createWorkerVecService(config: {
|
||||
return resp.results as VecSearchResult[]
|
||||
},
|
||||
|
||||
async countWithoutEmbeddings(projectId?: string): Promise<number> {
|
||||
const resp = await req({ action: 'countWithoutEmbeddings', projectId })
|
||||
return (resp?.count as number) ?? 0
|
||||
},
|
||||
|
||||
async getWithoutEmbeddings(projectId?: string, limit: number = 50): Promise<Array<{ id: number; content: string }>> {
|
||||
const resp = await req({ action: 'getWithoutEmbeddings', projectId, limit })
|
||||
if (!resp?.rows) return []
|
||||
return resp.rows as Array<{ id: number; content: string }>
|
||||
},
|
||||
|
||||
async recreateTable(dimensions: number): Promise<void> {
|
||||
await req({ action: 'recreateTable', dimensions })
|
||||
},
|
||||
|
||||
async getDimensions(): Promise<{ exists: boolean; dimensions: number | null }> {
|
||||
const resp = await req({ action: 'getDimensions' })
|
||||
if (!resp) return { exists: false, dimensions: null }
|
||||
return { exists: resp.exists as boolean, dimensions: (resp.dimensions as number | null) ?? null }
|
||||
},
|
||||
|
||||
dispose() {
|
||||
const pidPath = join(config.dataDir, 'vec-worker.pid')
|
||||
if (existsSync(pidPath)) {
|
||||
|
||||
@@ -1,115 +0,0 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { VecService, VecSearchResult } from './vec-types'
|
||||
import { createRequire } from 'node:module'
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
|
||||
export function createDirectVecService(db: Database): VecService {
|
||||
let loaded = false
|
||||
|
||||
try {
|
||||
const { getLoadablePath } = require('sqlite-vec')
|
||||
db.loadExtension(getLoadablePath())
|
||||
loaded = true
|
||||
} catch {
|
||||
loaded = false
|
||||
}
|
||||
|
||||
return {
|
||||
get available() {
|
||||
return loaded
|
||||
},
|
||||
|
||||
async initialize(dimensions: number) {
|
||||
if (!loaded) return
|
||||
|
||||
const exists = db.prepare(
|
||||
"SELECT name FROM sqlite_master WHERE type='table' AND name='memory_embeddings'"
|
||||
).get()
|
||||
|
||||
if (!exists) {
|
||||
db.run(`
|
||||
CREATE VIRTUAL TABLE IF NOT EXISTS memory_embeddings USING vec0(
|
||||
embedding float[${dimensions}],
|
||||
+memory_id INTEGER,
|
||||
+project_id TEXT
|
||||
)
|
||||
`)
|
||||
}
|
||||
},
|
||||
|
||||
async insert(embedding: number[], memoryId: number, projectId: string) {
|
||||
if (!loaded) return
|
||||
db.prepare(
|
||||
'INSERT INTO memory_embeddings (embedding, memory_id, project_id) VALUES (?, ?, ?)'
|
||||
).run(JSON.stringify(embedding), memoryId, projectId)
|
||||
},
|
||||
|
||||
async delete(memoryId: number) {
|
||||
if (!loaded) return
|
||||
db.prepare('DELETE FROM memory_embeddings WHERE memory_id = ?').run(memoryId)
|
||||
},
|
||||
|
||||
async deleteByProject(projectId: string) {
|
||||
if (!loaded) return
|
||||
db.prepare('DELETE FROM memory_embeddings WHERE project_id = ?').run(projectId)
|
||||
},
|
||||
|
||||
async deleteByMemoryIds(memoryIds: number[]) {
|
||||
if (!loaded || memoryIds.length === 0) return
|
||||
const placeholders = memoryIds.map(() => '?').join(',')
|
||||
db.prepare(`DELETE FROM memory_embeddings WHERE memory_id IN (${placeholders})`).run(...memoryIds)
|
||||
},
|
||||
|
||||
async search(embedding: number[], projectId?: string, scope?: string, limit: number = 10): Promise<VecSearchResult[]> {
|
||||
if (!loaded) return []
|
||||
|
||||
const embeddingJson = JSON.stringify(embedding)
|
||||
const conditions: string[] = []
|
||||
const params: (string | number)[] = [embeddingJson]
|
||||
|
||||
if (projectId) {
|
||||
conditions.push('e.project_id = ?')
|
||||
params.push(projectId)
|
||||
}
|
||||
if (scope) {
|
||||
conditions.push('m.scope = ?')
|
||||
params.push(scope)
|
||||
}
|
||||
params.push(limit)
|
||||
|
||||
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''
|
||||
const rows = db.prepare(`
|
||||
SELECT e.memory_id, (e.embedding <=> ?) as distance
|
||||
FROM memory_embeddings e
|
||||
JOIN memories m ON m.id = e.memory_id
|
||||
${whereClause}
|
||||
ORDER BY distance
|
||||
LIMIT ?
|
||||
`).all(...params) as Array<{ memory_id: number; distance: number }>
|
||||
|
||||
return rows.map(r => ({ memoryId: r.memory_id, distance: r.distance }))
|
||||
},
|
||||
|
||||
async findSimilar(embedding: number[], projectId: string, threshold: number, limit: number): Promise<VecSearchResult[]> {
|
||||
if (!loaded) return []
|
||||
|
||||
const embeddingJson = JSON.stringify(embedding)
|
||||
const rows = db.prepare(`
|
||||
SELECT e.memory_id, (e.embedding <=> ?) as distance
|
||||
FROM memory_embeddings e
|
||||
JOIN memories m ON m.id = e.memory_id
|
||||
WHERE m.project_id = ?
|
||||
AND (e.embedding <=> ?) < ?
|
||||
ORDER BY distance LIMIT ?
|
||||
`).all(embeddingJson, projectId, embeddingJson, threshold, limit) as Array<{
|
||||
memory_id: number
|
||||
distance: number
|
||||
}>
|
||||
|
||||
return rows.map(r => ({ memoryId: r.memory_id, distance: r.distance }))
|
||||
},
|
||||
|
||||
dispose() {},
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@ export interface VecSearchResult {
|
||||
distance: number
|
||||
}
|
||||
|
||||
export type TableDimensionsResult = { exists: boolean; dimensions: number | null }
|
||||
|
||||
export interface VecService {
|
||||
readonly available: boolean
|
||||
initialize(dimensions: number): Promise<void>
|
||||
@@ -12,5 +14,9 @@ export interface VecService {
|
||||
deleteByMemoryIds(memoryIds: number[]): Promise<void>
|
||||
search(embedding: number[], projectId?: string, scope?: string, limit?: number): Promise<VecSearchResult[]>
|
||||
findSimilar(embedding: number[], projectId: string, threshold: number, limit: number): Promise<VecSearchResult[]>
|
||||
countWithoutEmbeddings(projectId?: string): Promise<number>
|
||||
getWithoutEmbeddings(projectId?: string, limit?: number): Promise<Array<{ id: number; content: string }>>
|
||||
recreateTable(dimensions: number): Promise<void>
|
||||
getDimensions(): Promise<TableDimensionsResult>
|
||||
dispose(): void
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
|
||||
export type TableDimensionsResult =
|
||||
| { exists: false }
|
||||
| { exists: true; dimensions: number | null }
|
||||
|
||||
export function getTableDimensions(db: Database): TableDimensionsResult {
|
||||
const row = db.prepare(
|
||||
"SELECT sql FROM sqlite_master WHERE type='table' AND name='memory_embeddings'"
|
||||
).get() as { sql: string } | undefined
|
||||
|
||||
if (!row) return { exists: false }
|
||||
|
||||
const match = row.sql.match(/float\[(\d+)\]/i)
|
||||
return { exists: true, dimensions: match ? parseInt(match[1]!, 10) : null }
|
||||
}
|
||||
|
||||
export function recreateVecTable(db: Database, dimensions: number): void {
|
||||
db.run('DROP TABLE IF EXISTS memory_embeddings')
|
||||
db.run(`
|
||||
CREATE VIRTUAL TABLE memory_embeddings USING vec0(
|
||||
embedding float[${dimensions}],
|
||||
+memory_id INTEGER,
|
||||
+project_id TEXT
|
||||
)
|
||||
`)
|
||||
}
|
||||
@@ -57,7 +57,40 @@ class VecWorker {
|
||||
if (!exists) {
|
||||
this.db.run(`
|
||||
CREATE VIRTUAL TABLE IF NOT EXISTS memory_embeddings USING vec0(
|
||||
embedding float[${this.config.dimensions}],
|
||||
embedding float[${this.config.dimensions}] distance_metric=cosine,
|
||||
+memory_id INTEGER,
|
||||
+project_id TEXT
|
||||
)
|
||||
`)
|
||||
return
|
||||
}
|
||||
|
||||
const row = this.db.prepare(
|
||||
"SELECT sql FROM sqlite_master WHERE type='table' AND name='memory_embeddings'"
|
||||
).get() as { sql: string } | undefined
|
||||
|
||||
if (!row) return
|
||||
|
||||
const match = row.sql.match(/float\[(\d+)\]/i)
|
||||
const existingDimensions = match ? parseInt(match[1]!, 10) : null
|
||||
|
||||
if (existingDimensions !== null && existingDimensions !== this.config.dimensions) {
|
||||
this.db.run('DROP TABLE IF EXISTS memory_embeddings')
|
||||
this.db.run(`
|
||||
CREATE VIRTUAL TABLE memory_embeddings USING vec0(
|
||||
embedding float[${this.config.dimensions}] distance_metric=cosine,
|
||||
+memory_id INTEGER,
|
||||
+project_id TEXT
|
||||
)
|
||||
`)
|
||||
return
|
||||
}
|
||||
|
||||
if (!row.sql.includes('distance_metric=cosine')) {
|
||||
this.db.run('DROP TABLE IF EXISTS memory_embeddings')
|
||||
this.db.run(`
|
||||
CREATE VIRTUAL TABLE memory_embeddings USING vec0(
|
||||
embedding float[${this.config.dimensions}] distance_metric=cosine,
|
||||
+memory_id INTEGER,
|
||||
+project_id TEXT
|
||||
)
|
||||
@@ -118,7 +151,7 @@ class VecWorker {
|
||||
if (!exists) {
|
||||
this.db.run(`
|
||||
CREATE VIRTUAL TABLE IF NOT EXISTS memory_embeddings USING vec0(
|
||||
embedding float[${dims}],
|
||||
embedding float[${dims}] distance_metric=cosine,
|
||||
+memory_id INTEGER,
|
||||
+project_id TEXT
|
||||
)
|
||||
@@ -165,32 +198,40 @@ class VecWorker {
|
||||
const scope = req.scope as string | undefined
|
||||
const limit = (req.limit as number) ?? 10
|
||||
const embeddingJson = JSON.stringify(embedding)
|
||||
const needsPostFilter = !!(projectId || scope)
|
||||
const knnLimit = needsPostFilter ? limit * 5 : limit
|
||||
|
||||
const conditions: string[] = []
|
||||
const params: (string | number)[] = [embeddingJson]
|
||||
|
||||
if (projectId) {
|
||||
conditions.push('e.project_id = ?')
|
||||
params.push(projectId)
|
||||
}
|
||||
if (scope) {
|
||||
conditions.push('m.scope = ?')
|
||||
params.push(scope)
|
||||
}
|
||||
|
||||
params.push(limit)
|
||||
|
||||
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''
|
||||
const rows = this.db.prepare(`
|
||||
SELECT e.memory_id, (e.embedding <=> ?) as distance
|
||||
FROM memory_embeddings e
|
||||
JOIN memories m ON m.id = e.memory_id
|
||||
${where}
|
||||
ORDER BY distance
|
||||
let knnRows = this.db.prepare(`
|
||||
SELECT memory_id, distance
|
||||
FROM memory_embeddings
|
||||
WHERE embedding MATCH ?
|
||||
LIMIT ?
|
||||
`).all(...params) as Array<{ memory_id: number; distance: number }>
|
||||
`).all(embeddingJson, knnLimit) as Array<{ memory_id: number; distance: number }>
|
||||
|
||||
return { results: rows.map(r => ({ memoryId: r.memory_id, distance: r.distance })) }
|
||||
if (needsPostFilter && knnRows.length > 0) {
|
||||
const ids = knnRows.map(r => r.memory_id)
|
||||
const placeholders = ids.map(() => '?').join(',')
|
||||
const conditions: string[] = [`id IN (${placeholders})`]
|
||||
const params: (string | number)[] = [...ids]
|
||||
|
||||
if (projectId) {
|
||||
conditions.push('project_id = ?')
|
||||
params.push(projectId)
|
||||
}
|
||||
if (scope) {
|
||||
conditions.push('scope = ?')
|
||||
params.push(scope)
|
||||
}
|
||||
|
||||
const validRows = this.db.prepare(
|
||||
`SELECT id FROM memories WHERE ${conditions.join(' AND ')}`
|
||||
).all(...params) as Array<{ id: number }>
|
||||
const validIds = new Set(validRows.map(r => r.id))
|
||||
knnRows = knnRows.filter(r => validIds.has(r.memory_id))
|
||||
}
|
||||
|
||||
const results = knnRows.slice(0, limit)
|
||||
return { results: results.map(r => ({ memoryId: r.memory_id, distance: r.distance })) }
|
||||
}
|
||||
|
||||
case 'findSimilar': {
|
||||
@@ -200,19 +241,28 @@ class VecWorker {
|
||||
const limit = req.limit as number
|
||||
const embeddingJson = JSON.stringify(embedding)
|
||||
|
||||
const rows = this.db.prepare(`
|
||||
SELECT e.memory_id, (e.embedding <=> ?) as distance
|
||||
FROM memory_embeddings e
|
||||
JOIN memories m ON m.id = e.memory_id
|
||||
WHERE m.project_id = ?
|
||||
AND (e.embedding <=> ?) < ?
|
||||
ORDER BY distance LIMIT ?
|
||||
`).all(embeddingJson, projectId, embeddingJson, threshold, limit) as Array<{
|
||||
memory_id: number
|
||||
distance: number
|
||||
}>
|
||||
const knnRows = this.db.prepare(`
|
||||
SELECT memory_id, distance
|
||||
FROM memory_embeddings
|
||||
WHERE embedding MATCH ?
|
||||
LIMIT ?
|
||||
`).all(embeddingJson, limit * 5) as Array<{ memory_id: number; distance: number }>
|
||||
|
||||
return { results: rows.map(r => ({ memoryId: r.memory_id, distance: r.distance })) }
|
||||
const ids = knnRows.map(r => r.memory_id)
|
||||
if (ids.length === 0) {
|
||||
return { results: [] }
|
||||
}
|
||||
|
||||
const placeholders = ids.map(() => '?').join(',')
|
||||
const projectRows = this.db.prepare(
|
||||
`SELECT id FROM memories WHERE id IN (${placeholders}) AND project_id = ?`
|
||||
).all(...ids, projectId) as Array<{ id: number }>
|
||||
const validIds = new Set(projectRows.map(r => r.id))
|
||||
|
||||
const filtered = knnRows
|
||||
.filter(r => validIds.has(r.memory_id) && r.distance < threshold)
|
||||
.slice(0, limit)
|
||||
return { results: filtered.map(r => ({ memoryId: r.memory_id, distance: r.distance })) }
|
||||
}
|
||||
|
||||
case 'count': {
|
||||
@@ -220,6 +270,99 @@ class VecWorker {
|
||||
return { count: row.count }
|
||||
}
|
||||
|
||||
case 'countWithoutEmbeddings': {
|
||||
const projectId = req.projectId as string | undefined
|
||||
const embeddingsTableExists = this.db.prepare(
|
||||
"SELECT name FROM sqlite_master WHERE type='table' AND name='memory_embeddings'"
|
||||
).get()
|
||||
|
||||
if (!embeddingsTableExists) {
|
||||
const conditions: string[] = []
|
||||
const params: (string | number)[] = []
|
||||
if (projectId) {
|
||||
conditions.push('project_id = ?')
|
||||
params.push(projectId)
|
||||
}
|
||||
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''
|
||||
const result = this.db.prepare(`SELECT COUNT(*) as count FROM memories ${where}`).get(...params) as { count: number }
|
||||
return { count: result.count }
|
||||
}
|
||||
|
||||
const conditions: string[] = ['e.memory_id IS NULL']
|
||||
const params: (string | number)[] = []
|
||||
if (projectId) {
|
||||
conditions.push('m.project_id = ?')
|
||||
params.push(projectId)
|
||||
}
|
||||
const result = this.db.prepare(`
|
||||
SELECT COUNT(*) as count
|
||||
FROM memories m
|
||||
LEFT JOIN memory_embeddings e ON m.id = e.memory_id
|
||||
WHERE ${conditions.join(' AND ')}
|
||||
`).get(...params) as { count: number }
|
||||
return { count: result.count }
|
||||
}
|
||||
|
||||
case 'getWithoutEmbeddings': {
|
||||
const projectId = req.projectId as string | undefined
|
||||
const limit = (req.limit as number) ?? 50
|
||||
const embeddingsTableExists = this.db.prepare(
|
||||
"SELECT name FROM sqlite_master WHERE type='table' AND name='memory_embeddings'"
|
||||
).get()
|
||||
|
||||
if (!embeddingsTableExists) {
|
||||
const conditions: string[] = []
|
||||
const params: (string | number)[] = []
|
||||
if (projectId) {
|
||||
conditions.push('project_id = ?')
|
||||
params.push(projectId)
|
||||
}
|
||||
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''
|
||||
const rows = this.db.prepare(`
|
||||
SELECT id, content FROM memories ${where} ORDER BY created_at ASC LIMIT ?
|
||||
`).all(...params, limit) as Array<{ id: number; content: string }>
|
||||
return { rows }
|
||||
}
|
||||
|
||||
const conditions: string[] = ['e.memory_id IS NULL']
|
||||
const params: (string | number)[] = []
|
||||
if (projectId) {
|
||||
conditions.push('m.project_id = ?')
|
||||
params.push(projectId)
|
||||
}
|
||||
const rows = this.db.prepare(`
|
||||
SELECT m.id, m.content
|
||||
FROM memories m
|
||||
LEFT JOIN memory_embeddings e ON m.id = e.memory_id
|
||||
WHERE ${conditions.join(' AND ')}
|
||||
ORDER BY m.created_at ASC
|
||||
LIMIT ?
|
||||
`).all(...params, limit) as Array<{ id: number; content: string }>
|
||||
return { rows }
|
||||
}
|
||||
|
||||
case 'recreateTable': {
|
||||
const dims = req.dimensions as number
|
||||
this.db.run('DROP TABLE IF EXISTS memory_embeddings')
|
||||
this.db.run(`
|
||||
CREATE VIRTUAL TABLE memory_embeddings USING vec0(
|
||||
embedding float[${dims}] distance_metric=cosine,
|
||||
+memory_id INTEGER,
|
||||
+project_id TEXT
|
||||
)
|
||||
`)
|
||||
return { status: 'ok' }
|
||||
}
|
||||
|
||||
case 'getDimensions': {
|
||||
const row = this.db.prepare(
|
||||
"SELECT sql FROM sqlite_master WHERE type='table' AND name='memory_embeddings'"
|
||||
).get() as { sql: string } | undefined
|
||||
if (!row) return { exists: false, dimensions: null }
|
||||
const match = row.sql.match(/float\[(\d+)\]/i)
|
||||
return { exists: true, dimensions: match ? parseInt(match[1]!, 10) : null }
|
||||
}
|
||||
|
||||
default:
|
||||
return { error: `Unknown action: ${req.action}` }
|
||||
}
|
||||
|
||||
@@ -1,40 +1,25 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { platform } from 'os'
|
||||
import { join } from 'path'
|
||||
import type { VecService } from './vec-types'
|
||||
import { createDirectVecService } from './vec-direct'
|
||||
import type { Logger } from '../types'
|
||||
|
||||
export type { VecService, VecSearchResult } from './vec-types'
|
||||
|
||||
export function initializeVecTables(db: Database, dimensions: number): void {
|
||||
const direct = createDirectVecService(db)
|
||||
if (direct.available) {
|
||||
direct.initialize(dimensions)
|
||||
}
|
||||
}
|
||||
|
||||
export async function createVecService(db: Database, dataDir: string, dimensions: number): Promise<VecService> {
|
||||
const direct = createDirectVecService(db)
|
||||
|
||||
if (direct.available) {
|
||||
await direct.initialize(dimensions)
|
||||
return direct
|
||||
}
|
||||
|
||||
if (platform() === 'darwin') {
|
||||
try {
|
||||
const { createWorkerVecService } = await import('./vec-client')
|
||||
const dbPath = join(dataDir, 'memory.db')
|
||||
const worker = await createWorkerVecService({ dbPath, dataDir, dimensions })
|
||||
if (worker.available) {
|
||||
await worker.initialize(dimensions)
|
||||
return worker
|
||||
}
|
||||
} catch {
|
||||
// Worker fallback unavailable
|
||||
export async function createVecService(_db: Database, dataDir: string, dimensions: number, logger?: Logger): Promise<VecService> {
|
||||
try {
|
||||
const { createWorkerVecService } = await import('./vec-client')
|
||||
const dbPath = join(dataDir, 'memory.db')
|
||||
const worker = await createWorkerVecService({ dbPath, dataDir, dimensions })
|
||||
if (worker.available) {
|
||||
await worker.initialize(dimensions)
|
||||
return worker
|
||||
}
|
||||
logger?.error('Vec worker started but not available')
|
||||
} catch (err) {
|
||||
logger?.error('Vec worker failed to start', err)
|
||||
}
|
||||
|
||||
logger?.log('Vec worker unavailable, using noop service')
|
||||
return createNoopVecService()
|
||||
}
|
||||
|
||||
@@ -48,6 +33,10 @@ export function createNoopVecService(): VecService {
|
||||
async deleteByMemoryIds() {},
|
||||
async search() { return [] },
|
||||
async findSimilar() { return [] },
|
||||
async countWithoutEmbeddings() { return 0 },
|
||||
async getWithoutEmbeddings() { return [] },
|
||||
async recreateTable() {},
|
||||
async getDimensions() { return { exists: false, dimensions: null } },
|
||||
dispose() {},
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user