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:
Chris Scott authored and GitHub committed 2026-02-23 15:08:56 -05:00
1 parent da283a82cf
commit 3461f86556
132 files changed
+11448 -2834

No files matched your search

+129
View File
@@ -0,0 +1,129 @@
import { Database } from 'bun:sqlite'
import { mkdirSync, existsSync } from 'fs'
import { homedir, platform } from 'os'
import { join } from 'path'
interface Migration {
id: string
description: string
apply: (db: Database) => void
}
const migrations: Migration[] = [
{
id: '001',
description: 'Remove status column from memories table',
apply: (db: Database) => {
const tableInfo = db.prepare('PRAGMA table_info(memories)').all() as Array<{ name: string }>
const hasStatusColumn = tableInfo.some((col) => col.name === 'status')
if (!hasStatusColumn) {
return
}
try {
db.run('ALTER TABLE memories DROP COLUMN status')
} catch {
const indexes = db.prepare("SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='memories'").all() as Array<{ name: string }>
for (const idx of indexes) {
if (idx.name.includes('status')) {
db.run(`DROP INDEX IF EXISTS ${idx.name}`)
}
}
db.run('ALTER TABLE memories DROP COLUMN status')
}
},
},
]
function runMigrations(db: Database): void {
db.run(`
CREATE TABLE IF NOT EXISTS migrations (
id TEXT PRIMARY KEY,
description TEXT NOT NULL,
applied_at INTEGER NOT NULL
)
`)
for (const migration of migrations) {
const existing = db.prepare('SELECT id FROM migrations WHERE id = ?').get(migration.id)
if (!existing) {
migration.apply(db)
db.prepare('INSERT INTO migrations (id, description, applied_at) VALUES (?, ?, ?)').run(
migration.id,
migration.description,
Date.now()
)
}
}
}
export function resolveDataDir(): string {
const defaultBase = join(homedir(), platform() === 'win32' ? 'AppData' : '.local', 'share')
const xdgDataHome = process.env['XDG_DATA_HOME'] || defaultBase
return join(xdgDataHome, 'opencode', 'memory')
}
export function resolveLogPath(): string {
return join(resolveDataDir(), 'logs', 'memory.log')
}
export function initializeDatabase(dataDir: string): Database {
if (!existsSync(dataDir)) {
mkdirSync(dataDir, { recursive: true })
}
const dbPath = `${dataDir}/memory.db`
const db = new Database(dbPath)
db.run('PRAGMA journal_mode=WAL')
db.run('PRAGMA busy_timeout=5000')
db.run('PRAGMA synchronous=NORMAL')
db.run(`
CREATE TABLE IF NOT EXISTS memories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id TEXT NOT NULL,
scope TEXT NOT NULL,
content TEXT NOT NULL,
file_path TEXT,
access_count INTEGER NOT NULL DEFAULT 0,
last_accessed_at INTEGER,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
)
`)
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(`
CREATE TABLE IF NOT EXISTS plugin_metadata (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
updated_at INTEGER NOT NULL
)
`)
return db
}
export function closeDatabase(db: Database): void {
db.close()
}
+20
View File
@@ -0,0 +1,20 @@
export { initializeDatabase, closeDatabase, resolveDataDir, resolveLogPath } from './database'
export { createVecService } from './vec'
export type { VecService, VecSearchResult } from './vec-types'
export { createMemoryQuery } from './memory-queries'
export { createSessionStateQueries } from './session-state-queries'
export { createMetadataQuery } from './metadata-queries'
export type {
Memory,
MemoryScope,
CreateMemoryInput,
UpdateMemoryInput,
MemorySearchResult,
MemoryStats,
ListMemoriesFilter,
SessionState,
PlanningState,
PreCompactionSnapshot,
CompactionConfig,
} from '../types'
@@ -0,0 +1,457 @@
import type { Database } from 'bun:sqlite'
import type { Memory, MemoryScope, CreateMemoryInput, UpdateMemoryInput, MemorySearchResult } from '../types'
import type { VecService } from './vec-types'
function mapRow(row: {
id: number
project_id: string
scope: string
content: string
file_path: string | null
access_count: number
last_accessed_at: number | null
created_at: number
updated_at: number
}): Memory {
return {
id: row.id,
projectId: row.project_id,
scope: row.scope as MemoryScope,
content: row.content,
filePath: row.file_path,
accessCount: row.access_count,
lastAccessedAt: row.last_accessed_at,
createdAt: row.created_at,
updatedAt: row.updated_at,
}
}
type MemoryRow = Parameters<typeof mapRow>[0]
interface Logger {
log: (message: string, ...args: unknown[]) => void
error: (message: string, ...args: unknown[]) => void
}
export function createMemoryQuery(db: Database, vec: VecService, logger?: Logger) {
const logError = (context: string, error?: unknown) => {
if (logger) {
logger.error(context, error)
}
}
const createInDb = (input: CreateMemoryInput): number => {
const now = Date.now()
const result = insertMemory.run(
input.projectId,
input.scope,
input.content,
input.filePath ?? null,
now,
now
)
return Number(result.lastInsertRowid)
}
const insertMemory = db.prepare(`
INSERT INTO memories (project_id, scope, content, file_path, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?)
`)
const trackAccessStmt = db.prepare(`
UPDATE memories SET access_count = access_count + 1, last_accessed_at = ? WHERE id = ?
`)
return {
createInDb,
logError,
async create(input: CreateMemoryInput, embedding: number[]): Promise<number> {
const now = Date.now()
const result = insertMemory.run(
input.projectId,
input.scope,
input.content,
input.filePath ?? null,
now,
now
)
const memoryId = Number(result.lastInsertRowid)
if (vec.available && embedding.length > 0) {
try {
await vec.insert(embedding, memoryId, input.projectId)
} catch (error) {
logError('Failed to insert embedding for memory', error)
}
}
return memoryId
},
update(id: number, input: UpdateMemoryInput): void {
const updates: string[] = []
const values: (string | number | null)[] = []
if (input.content !== undefined) {
updates.push('content = ?')
values.push(input.content)
}
if (input.scope !== undefined) {
updates.push('scope = ?')
values.push(input.scope)
}
if (updates.length === 0) return
updates.push('updated_at = ?')
values.push(Date.now())
values.push(id)
db.prepare(`UPDATE memories SET ${updates.join(', ')} WHERE id = ?`).run(...values)
},
async updateEmbedding(memoryId: number, embedding: number[]): Promise<void> {
if (!vec.available) return
await vec.delete(memoryId)
if (embedding.length > 0) {
const projectId = db.prepare('SELECT project_id FROM memories WHERE id = ?').get(memoryId) as { project_id: string } | undefined
if (projectId) {
await vec.insert(embedding, memoryId, projectId.project_id)
}
}
},
async delete(id: number): Promise<void> {
if (vec.available) {
await vec.delete(id)
}
db.prepare('DELETE FROM memories WHERE id = ?').run(id)
},
getById(id: number): Memory | undefined {
const row = db.prepare(`
SELECT id, project_id, scope, content, file_path, access_count, last_accessed_at, created_at, updated_at
FROM memories WHERE id = ?
`).get(id) as MemoryRow | undefined
if (!row) return undefined
return mapRow(row)
},
trackAccess(id: number): void {
trackAccessStmt.run(Date.now(), id)
},
listByProject(
projectId: string,
filters?: {
scope?: MemoryScope
limit?: number
offset?: number
}
): Memory[] {
const conditions: string[] = ['project_id = ?']
const params: (string | number)[] = [projectId]
if (filters?.scope) {
conditions.push('scope = ?')
params.push(filters.scope)
}
const limit = filters?.limit ?? 20
const offset = filters?.offset ?? 0
const rows = db.prepare(`
SELECT id, project_id, scope, content, file_path, access_count, last_accessed_at, created_at, updated_at
FROM memories
WHERE ${conditions.join(' AND ')}
ORDER BY updated_at DESC
LIMIT ? OFFSET ?
`).all(...params, limit, offset) as MemoryRow[]
return rows.map(mapRow)
},
listAll(
filters?: {
projectId?: string
scope?: MemoryScope
limit?: number
offset?: number
}
): Memory[] {
const conditions: string[] = []
const params: (string | number)[] = []
if (filters?.projectId) {
conditions.push('project_id = ?')
params.push(filters.projectId)
}
if (filters?.scope) {
conditions.push('scope = ?')
params.push(filters.scope)
}
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''
const limit = filters?.limit ?? 20
const offset = filters?.offset ?? 0
const rows = db.prepare(`
SELECT id, project_id, scope, content, file_path, access_count, last_accessed_at, created_at, updated_at
FROM memories
${whereClause}
ORDER BY updated_at DESC
LIMIT ? OFFSET ?
`).all(...params, limit, offset) as MemoryRow[]
return rows.map(mapRow)
},
async search(
embedding: number[],
projectId?: string,
filters?: {
scope?: MemoryScope
limit?: number
}
): Promise<MemorySearchResult[]> {
if (!vec.available) {
const basicFilters = projectId
? { projectId, scope: filters?.scope, limit: filters?.limit }
: { scope: filters?.scope, limit: filters?.limit }
const memories = this.listAll(basicFilters)
return memories.map(memory => ({ memory, distance: 1.0 }))
}
try {
const vecResults = await vec.search(embedding, projectId, filters?.scope, filters?.limit ?? 10)
if (vecResults.length === 0) {
const basicFilters = projectId
? { projectId, scope: filters?.scope, limit: filters?.limit }
: { scope: filters?.scope, limit: filters?.limit }
const memories = this.listAll(basicFilters)
return memories.map(memory => ({ memory, distance: 1.0 }))
}
const memoryIds = vecResults.map(r => r.memoryId)
const distanceMap = new Map(vecResults.map(r => [r.memoryId, r.distance]))
const placeholders = memoryIds.map(() => '?').join(',')
const rows = 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})
`).all(...memoryIds) as MemoryRow[]
return rows
.map(row => ({
memory: mapRow(row),
distance: distanceMap.get(row.id) ?? 1.0,
}))
.sort((a, b) => a.distance - b.distance)
} catch {
const basicFilters = projectId
? { projectId, scope: filters?.scope, limit: filters?.limit }
: { scope: filters?.scope, limit: filters?.limit }
const memories = this.listAll(basicFilters)
return memories.map(memory => ({ memory, distance: 1.0 }))
}
},
getStats(projectId: string): {
total: number
byScope: Record<MemoryScope, number>
} {
const scopeRows = db.prepare(`
SELECT scope, COUNT(*) as count FROM memories WHERE project_id = ? GROUP BY scope
`).all(projectId) as Array<{ scope: string; count: number }>
const totalResult = db.prepare(`
SELECT COUNT(*) as count FROM memories WHERE project_id = ?
`).get(projectId) as { count: number }
const byScope: Record<string, number> = {}
for (const row of scopeRows) {
byScope[row.scope] = row.count
}
return {
total: totalResult.count,
byScope: byScope as Record<MemoryScope, number>,
}
},
async deleteByProject(projectId: string): Promise<void> {
if (vec.available) {
await vec.deleteByProject(projectId)
}
db.prepare('DELETE FROM memories WHERE project_id = ?').run(projectId)
},
countByProject(projectId: string): number {
const result = db.prepare(`
SELECT COUNT(*) as count FROM memories WHERE project_id = ?
`).get(projectId) as { count: number }
return result.count
},
existsByContent(projectId: string, content: string): boolean {
const result = db.prepare(`
SELECT 1 FROM memories WHERE project_id = ? AND content = ? LIMIT 1
`).get(projectId, content)
return !!result
},
getMemoriesWithoutEmbeddings(
projectId?: string,
limit: number = 50
): Memory[] {
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 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)
},
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
},
getByContent(projectId: string, content: string): Memory | undefined {
const row = db.prepare(`
SELECT * FROM memories WHERE project_id = ? AND content = ? LIMIT 1
`).get(projectId, content) as MemoryRow | undefined
return row ? mapRow(row) : undefined
},
async findSimilar(
embedding: number[],
projectId: string,
threshold: number = 0.15,
limit: number = 5
): Promise<Array<{ id: number; content: string; distance: number }>> {
if (!vec.available) return []
try {
const vecResults = await vec.findSimilar(embedding, projectId, threshold, limit)
if (vecResults.length === 0) return []
const memoryIds = vecResults.map(r => r.memoryId)
const distanceMap = new Map(vecResults.map(r => [r.memoryId, r.distance]))
const placeholders = memoryIds.map(() => '?').join(',')
const rows = db.prepare(`
SELECT id, content FROM memories WHERE id IN (${placeholders})
`).all(...memoryIds) as Array<{ id: number; content: string }>
return rows
.map(row => ({
id: row.id,
content: row.content,
distance: distanceMap.get(row.id) ?? 1.0,
}))
.sort((a, b) => a.distance - b.distance)
} catch {
return []
}
},
async deleteByFilePath(projectId: string, filePath: string): Promise<void> {
if (vec.available) {
const rows = db.prepare(
'SELECT id FROM memories WHERE project_id = ? AND file_path = ?'
).all(projectId, filePath) as Array<{ id: number }>
const ids = rows.map(r => r.id)
if (ids.length > 0) {
await vec.deleteByMemoryIds(ids)
}
}
db.prepare('DELETE FROM memories WHERE project_id = ? AND file_path = ?').run(projectId, filePath)
},
}
}
@@ -0,0 +1,46 @@
import type { Database } from 'bun:sqlite'
export interface PluginMetadata {
key: string
value: string
updatedAt: number
}
export function createMetadataQuery(db: Database) {
const getStmt = db.prepare('SELECT key, value, updated_at FROM plugin_metadata WHERE key = ?')
const setStmt = db.prepare(`
INSERT INTO plugin_metadata (key, value, updated_at)
VALUES (?, ?, ?)
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at
`)
return {
get(key: string): PluginMetadata | undefined {
const row = getStmt.get(key) as { key: string; value: string; updated_at: number } | undefined
if (!row) return undefined
return {
key: row.key,
value: row.value,
updatedAt: row.updated_at,
}
},
set(key: string, value: string): void {
setStmt.run(key, value, Date.now())
},
getEmbeddingModel(): { model: string; dimensions: number } | undefined {
const row = this.get('embedding_model')
if (!row) return undefined
try {
return JSON.parse(row.value)
} catch {
return undefined
}
},
setEmbeddingModel(model: string, dimensions: number): void {
this.set('embedding_model', JSON.stringify({ model, dimensions }))
},
}
}
@@ -0,0 +1,91 @@
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
}
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`
)
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)
},
}
}
+187
View File
@@ -0,0 +1,187 @@
import { spawn } from 'child_process'
import { existsSync, readFileSync, unlinkSync } from 'fs'
import { join } from 'path'
import { createConnection } from 'net'
import type { VecService, VecSearchResult } from './vec-types'
function sendRequest(socketPath: string, request: Record<string, unknown>): Promise<Record<string, unknown>> {
return new Promise((resolve, reject) => {
const client = createConnection({ path: socketPath })
let data = ''
const timeout = setTimeout(() => {
client.destroy()
reject(new Error('Vec worker timeout'))
}, 10000)
client.on('connect', () => {
client.write(JSON.stringify(request) + '\n')
})
client.on('data', (chunk: Buffer) => {
data += chunk.toString()
const lines = data.split('\n')
for (const line of lines) {
if (!line.trim()) continue
try {
const response = JSON.parse(line)
clearTimeout(timeout)
client.end()
if (response.error) {
reject(new Error(response.error))
} else {
resolve(response)
}
return
} catch {
// keep reading
}
}
})
client.on('error', (err: Error) => {
clearTimeout(timeout)
client.destroy()
reject(err)
})
})
}
function isWorkerRunning(pidPath: string, socketPath: string): boolean {
if (!existsSync(pidPath) || !existsSync(socketPath)) return false
try {
const pid = parseInt(readFileSync(pidPath, 'utf-8'), 10)
process.kill(pid, 0)
return true
} catch {
return false
}
}
function cleanupStale(pidPath: string, socketPath: string): void {
try {
if (existsSync(pidPath)) {
const pid = parseInt(readFileSync(pidPath, 'utf-8'), 10)
try { process.kill(pid, 0) } catch { unlinkSync(pidPath) }
}
} catch {}
try {
if (existsSync(socketPath)) unlinkSync(socketPath)
} catch {}
}
async function startWorker(config: {
dbPath: string
dataDir: string
dimensions: number
}): Promise<string> {
const socketPath = join(config.dataDir, 'vec-worker.sock')
const pidPath = join(config.dataDir, 'vec-worker.pid')
if (isWorkerRunning(pidPath, socketPath)) {
return socketPath
}
cleanupStale(pidPath, socketPath)
const workerScript = join(__dirname, 'vec-worker.ts')
const proc = spawn('bun', [
workerScript,
'--db', config.dbPath,
'--socket', socketPath,
'--pid', pidPath,
'--dimensions', String(config.dimensions),
], {
detached: true,
stdio: 'ignore',
})
proc.unref()
for (let i = 0; i < 20; i++) {
await new Promise(r => setTimeout(r, 250))
if (existsSync(socketPath)) {
try {
const resp = await sendRequest(socketPath, { action: 'health' })
if (resp.status === 'ok') return socketPath
} catch {
// keep waiting
}
}
}
throw new Error('Failed to start vec worker')
}
export async function createWorkerVecService(config: {
dbPath: string
dataDir: string
dimensions: number
}): Promise<VecService> {
let socketPath: string
let isAvailable = false
try {
socketPath = await startWorker(config)
isAvailable = true
} catch {
socketPath = ''
isAvailable = false
}
async function req(action: Record<string, unknown>): Promise<Record<string, unknown> | null> {
if (!isAvailable) return null
try {
return await sendRequest(socketPath, action)
} catch {
return null
}
}
return {
get available() {
return isAvailable
},
async initialize(dimensions: number) {
await req({ action: 'init', dimensions })
},
async insert(embedding: number[], memoryId: number, projectId: string) {
await req({ action: 'insert', embedding, memoryId, projectId })
},
async delete(memoryId: number) {
await req({ action: 'delete', memoryId })
},
async deleteByProject(projectId: string) {
await req({ action: 'deleteByProject', projectId })
},
async deleteByMemoryIds(memoryIds: number[]) {
await req({ action: 'deleteByMemoryIds', memoryIds })
},
async search(embedding: number[], projectId?: string, scope?: string, limit: number = 10): Promise<VecSearchResult[]> {
const resp = await req({ action: 'search', embedding, projectId, scope, limit })
if (!resp?.results) return []
return resp.results as VecSearchResult[]
},
async findSimilar(embedding: number[], projectId: string, threshold: number, limit: number): Promise<VecSearchResult[]> {
const resp = await req({ action: 'findSimilar', embedding, projectId, threshold, limit })
if (!resp?.results) return []
return resp.results as VecSearchResult[]
},
dispose() {
const pidPath = join(config.dataDir, 'vec-worker.pid')
if (existsSync(pidPath)) {
try {
const pid = parseInt(readFileSync(pidPath, 'utf-8'), 10)
process.kill(pid, 'SIGTERM')
} catch {}
}
},
}
}
+115
View File
@@ -0,0 +1,115 @@
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() {},
}
}
+16
View File
@@ -0,0 +1,16 @@
export interface VecSearchResult {
memoryId: number
distance: number
}
export interface VecService {
readonly available: boolean
initialize(dimensions: number): Promise<void>
insert(embedding: number[], memoryId: number, projectId: string): Promise<void>
delete(memoryId: number): Promise<void>
deleteByProject(projectId: string): Promise<void>
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[]>
dispose(): void
}
+265
View File
@@ -0,0 +1,265 @@
import { Database } from 'bun:sqlite'
import { createServer } from 'net'
import { existsSync, unlinkSync, writeFileSync, mkdirSync } from 'fs'
import { join } from 'path'
import { createRequire } from 'node:module'
import { platform } from 'os'
interface WorkerConfig {
dbPath: string
socketPath: string
pidPath: string
dimensions: number
}
const require = createRequire(import.meta.url)
function resolveHomebrewSqlitePath(): string | null {
const candidates = [
'/opt/homebrew/opt/sqlite/lib/libsqlite3.dylib',
'/usr/local/opt/sqlite/lib/libsqlite3.dylib',
]
for (const c of candidates) {
if (existsSync(c)) return c
}
return null
}
if (platform() === 'darwin') {
const sqlitePath = resolveHomebrewSqlitePath()
if (sqlitePath) {
Database.setCustomSQLite(sqlitePath)
}
}
class VecWorker {
private db: Database
private server: ReturnType<typeof createServer> | null = null
private config: WorkerConfig
constructor(config: WorkerConfig) {
this.config = config
this.db = new Database(config.dbPath)
this.db.run('PRAGMA journal_mode=WAL')
this.db.run('PRAGMA busy_timeout=5000')
const { getLoadablePath } = require('sqlite-vec')
this.db.loadExtension(getLoadablePath())
this.initTables()
}
private initTables(): void {
const exists = this.db.prepare(
"SELECT name FROM sqlite_master WHERE type='table' AND name='memory_embeddings'"
).get()
if (!exists) {
this.db.run(`
CREATE VIRTUAL TABLE IF NOT EXISTS memory_embeddings USING vec0(
embedding float[${this.config.dimensions}],
+memory_id INTEGER,
+project_id TEXT
)
`)
}
}
start(): void {
const { socketPath, pidPath } = this.config
const socketDir = join(socketPath, '..')
if (!existsSync(socketDir)) {
mkdirSync(socketDir, { recursive: true })
}
if (existsSync(socketPath)) {
unlinkSync(socketPath)
}
writeFileSync(pidPath, String(process.pid), 'utf-8')
this.server = createServer((socket) => {
let buffer = ''
socket.on('data', (data) => {
buffer += data.toString()
const lines = buffer.split('\n')
buffer = lines.pop() || ''
for (const line of lines) {
if (!line.trim()) continue
try {
const request = JSON.parse(line)
const response = this.handle(request)
socket.write(JSON.stringify(response) + '\n')
} catch (error) {
socket.write(JSON.stringify({
error: error instanceof Error ? error.message : String(error)
}) + '\n')
}
}
})
socket.on('error', () => {})
})
this.server.listen(socketPath)
process.on('SIGTERM', () => this.shutdown())
process.on('SIGINT', () => this.shutdown())
}
private handle(req: Record<string, unknown>): Record<string, unknown> {
switch (req.action) {
case 'health':
return { status: 'ok' }
case 'init': {
const dims = req.dimensions as number
if (dims) {
const exists = this.db.prepare(
"SELECT name FROM sqlite_master WHERE type='table' AND name='memory_embeddings'"
).get()
if (!exists) {
this.db.run(`
CREATE VIRTUAL TABLE IF NOT EXISTS memory_embeddings USING vec0(
embedding float[${dims}],
+memory_id INTEGER,
+project_id TEXT
)
`)
}
}
return { status: 'ok' }
}
case 'insert': {
const embedding = req.embedding as number[]
const memoryId = req.memoryId as number
const projectId = req.projectId as string
this.db.prepare(
'INSERT INTO memory_embeddings (embedding, memory_id, project_id) VALUES (?, ?, ?)'
).run(JSON.stringify(embedding), memoryId, projectId)
return { status: 'ok' }
}
case 'delete': {
const memoryId = req.memoryId as number
this.db.prepare('DELETE FROM memory_embeddings WHERE memory_id = ?').run(memoryId)
return { status: 'ok' }
}
case 'deleteByProject': {
const projectId = req.projectId as string
this.db.prepare('DELETE FROM memory_embeddings WHERE project_id = ?').run(projectId)
return { status: 'ok' }
}
case 'deleteByMemoryIds': {
const ids = req.memoryIds as number[]
if (ids.length > 0) {
const placeholders = ids.map(() => '?').join(',')
this.db.prepare(`DELETE FROM memory_embeddings WHERE memory_id IN (${placeholders})`).run(...ids)
}
return { status: 'ok' }
}
case 'search': {
const embedding = req.embedding as number[]
const projectId = req.projectId as string | undefined
const scope = req.scope as string | undefined
const limit = (req.limit as number) ?? 10
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 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
LIMIT ?
`).all(...params) as Array<{ memory_id: number; distance: number }>
return { results: rows.map(r => ({ memoryId: r.memory_id, distance: r.distance })) }
}
case 'findSimilar': {
const embedding = req.embedding as number[]
const projectId = req.projectId as string
const threshold = req.threshold as number
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
}>
return { results: rows.map(r => ({ memoryId: r.memory_id, distance: r.distance })) }
}
case 'count': {
const row = this.db.prepare('SELECT COUNT(*) as count FROM memory_embeddings').get() as { count: number }
return { count: row.count }
}
default:
return { error: `Unknown action: ${req.action}` }
}
}
private shutdown(): void {
if (this.server) {
this.server.close()
this.server = null
}
try {
if (existsSync(this.config.socketPath)) unlinkSync(this.config.socketPath)
} catch {}
try {
if (existsSync(this.config.pidPath)) unlinkSync(this.config.pidPath)
} catch {}
this.db.close()
process.exit(0)
}
}
function parseArgs(): WorkerConfig {
const args = process.argv.slice(2)
let dbPath = ''
let socketPath = ''
let pidPath = ''
let dimensions = 384
for (let i = 0; i < args.length; i++) {
switch (args[i]) {
case '--db': dbPath = args[++i]; break
case '--socket': socketPath = args[++i]; break
case '--pid': pidPath = args[++i]; break
case '--dimensions': dimensions = parseInt(args[++i], 10); break
}
}
return { dbPath, socketPath, pidPath, dimensions }
}
const config = parseArgs()
const worker = new VecWorker(config)
worker.start()
+53
View File
@@ -0,0 +1,53 @@
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'
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
}
}
return createNoopVecService()
}
export function createNoopVecService(): VecService {
return {
get available() { return false },
async initialize() {},
async insert() {},
async delete() {},
async deleteByProject() {},
async deleteByMemoryIds() {},
async search() { return [] },
async findSimilar() { return [] },
dispose() {},
}
}