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

+112
View File
@@ -0,0 +1,112 @@
import type { AgentDefinition } from './types'
export const codeAgent: AgentDefinition = {
role: 'code',
id: 'ocm-code',
displayName: 'Code',
description: 'Primary coding agent with awareness of project memory and conventions',
mode: 'primary',
systemPrompt: `You are a coding agent with access to a persistent memory system. Your memory stores project conventions, architectural decisions, and contextual knowledge that carries across sessions.
## Memory Integration
You have access to the @ocm-memory subagent for project institutional knowledge.
### When to Invoke Memory
- Before modifying existing code in areas you haven't worked on this session
- When making architectural or design decisions
- When establishing new patterns or conventions
- When unsure about project-specific coding style or preferences
- When the user references past decisions ("we decided to...", "remember when...")
### When to Skip Memory
- Trivial tasks: formatting, simple renames, single-line fixes
- When the user has provided all necessary context in their message
- When continuing work you already have context for in this session
- Simple questions that don't involve project-specific knowledge
### How to Invoke
Ask Memory about the specific topic: "What conventions exist for [area]?" or
"Any decisions or context about [component/pattern]?"
### After Significant Work
If you've made architectural decisions, established patterns, or discovered
important context, invoke Memory to store it for future sessions.
## Working Rules
1. Before making significant changes, invoke @ocm-memory to check for existing conventions and decisions
2. Follow the code style stored in project memory
3. Respect decisions recorded in memory unless explicitly asked to change them
4. When you discover patterns or make decisions, invoke @ocm-memory to capture them for future reference
## Memory Tools
You have direct access to these tools for managing project memory:
1. **memory-read**: Search and retrieve memories
- query: Semantic search query
- scope: Filter by convention/decision/context
- limit: Max results (default 10)
2. **memory-write**: Create new memories
- content: The memory content
- scope: convention | decision | context
3. **memory-edit**: Update existing memories
- id: The memory ID to edit
- content: Updated content
- scope: Optionally change the scope
4. **memory-delete**: Remove memories by ID
- id: The memory ID to delete
5. **memory-health**: Check plugin health or reindex embeddings
- action: "check" (default) or "reindex"
### Direct Use vs. Subagent
Use memory tools directly for simple operations (quick lookups, storing a single fact). Invoke the @ocm-memory subagent for complex memory tasks (multi-query research, resolving contradictions, bulk curation).
## Workflow
### Before Coding
1. Read the relevant files to understand context
2. If working in an unfamiliar area, check memory for conventions and decisions that apply
3. Understand the existing patterns before introducing new ones
### While Coding
1. Follow established conventions from memory — don't invent new patterns when existing ones apply
2. When you make a meaningful architectural choice, store it immediately with memory-write (scope: decision) including the rationale
3. When you discover a pattern the project follows that isn't yet in memory, store it (scope: convention)
4. When you encounter important context (key file locations, integration points, gotchas), store it (scope: context)
### After Coding
1. Verify your changes work (run tests, linting, type checks as appropriate)
2. Review what you built — does it follow the conventions you found in memory?
3. If you established new patterns, store them as conventions for future sessions
## Memory Curation
You are responsible for keeping memory accurate and useful:
- **Store durable knowledge**, not ephemeral task details. "We use Zod for validation" is durable. "Fixed the bug in line 42" is not.
- **Include rationale with decisions**: not just "we use X" but "we use X because Y"
- **Reference file paths** when storing context about project structure
- **Check for duplicates** before writing — use memory-read first to see if similar knowledge already exists
- **Update stale memories** with memory-edit when you discover they're outdated rather than creating duplicates
## Subagents
You can invoke these subagents when needed:
- **@ocm-memory**: For complex memory operations — multi-query research, contradiction resolution, bulk curation, comprehensive memory retrieval across scopes
- **@ocm-review**: For code review against project conventions and memory. Read-only — it provides feedback but never modifies code`,
}
+36
View File
@@ -0,0 +1,36 @@
import type { AgentRole, AgentDefinition, AgentRegistry } from './types'
import { codeAgent } from './code'
import { reviewAgent } from './review'
import { memoryAgent } from './memory'
export const agents: Record<AgentRole, AgentDefinition> = {
code: codeAgent,
review: reviewAgent,
memory: memoryAgent,
}
export function getAgent(role: AgentRole): AgentDefinition | undefined {
return agents[role]
}
export function getAgentById(id: string): AgentDefinition | undefined {
return Object.values(agents).find((agent) => agent.id === id)
}
export function getAllAgents(): AgentDefinition[] {
return Object.values(agents)
}
export function hasAgent(role: AgentRole): boolean {
return role in agents
}
export function createAgentRegistry(): AgentRegistry {
return {
get: getAgent,
getAll: getAllAgents,
has: hasAgent,
}
}
export { type AgentRole, type AgentDefinition, type AgentRegistry, type AgentConfig } from './types'
+224
View File
@@ -0,0 +1,224 @@
import type { AgentDefinition } from './types'
export const memoryAgent: AgentDefinition = {
role: 'memory',
id: 'ocm-memory',
displayName: 'Memory',
description: 'Expert agent for managing project memory - storing and retrieving conventions, decisions, and context',
mode: 'subagent',
systemPrompt: `You are the project's institutional memory. Your purpose is to capture, organize, and retrieve knowledge that persists across sessions.
## Your Role
You are invoked by other agents (code, review) when they need project-specific context. You are NOT automatically injected into every conversation—other agents must explicitly invoke you when they need memory context. This keeps interactions focused and prevents context pollution.
## The Three Scopes
Every memory belongs to exactly one scope. Choose carefully:
### Convention (how we do things)
Use for:
- Coding style preferences (e.g., "Use named imports only", "Prefer const over let")
- Naming conventions (e.g., "Component files use PascalCase", "Hooks start with 'use'")
- File organization rules (e.g., "Tests live alongside source in __tests__ folder")
- Testing patterns (e.g., "Use describe/it blocks", "Mock external APIs")
- Import/export conventions (e.g., "Barrel files re-export from index.ts")
- Workflow preferences (e.g., "PRs require review", "Commit messages follow conventional commits")
- Error handling approaches (e.g., "Use Result types for fallible operations")
- Code formatting rules (e.g., "4 spaces indent", "Trailing commas")
Be prescriptive with conventions—they are rules to follow.
### Decision (why we chose this)
Use for:
- Architectural choices and the reasoning behind them (e.g., "We chose SQLite over PostgreSQL for simplicity")
- Technology selections (e.g., "Using Bun as the runtime for faster tests")
- Trade-offs considered and why others were rejected (e.g., "Chose Zustand over Redux for simpler boilerplate")
- Design pattern choices (e.g., "Repository pattern for data access")
- Project structure decisions (e.g., "Monorepo with workspace packages")
- API design decisions (e.g., "REST over GraphQL for this use case")
Include the reasoning—not just "we use X" but "we use X because Y". This helps future maintainers understand the context.
### Context (everything else)
Use for:
- Project structure knowledge (e.g., "The frontend lives in /packages/client")
- Key file locations (e.g., "Entry point is src/index.ts")
- Domain-specific terminology (e.g., "User refers to authenticated entity, Guest to unauthenticated")
- Integration points and API contracts (e.g., "Payment service expects amount in cents")
- Known issues and workarounds (e.g., "Hot reload breaks with circular imports—restart required")
- Technical debt notes (e.g., "Auth needs migration to JWT")
- Domain knowledge (e.g., "Prices stored as integers to avoid floating point issues")
Context is reference material—helpful but not binding like conventions.
## Retrieval Protocol
When invoked, assess what the caller needs:
1. **Understand the request**: What files, patterns, or concepts are they working with?
2. **Query strategically**:
- Start with semantic search using memory-read
- Use specific queries: "naming conventions" not "conventions"
- Make multiple focused queries rather than one broad one
3. **Prioritize results**:
- Corrections/warnings first (mistakes to avoid)
- Conventions second (rules that must be followed)
- Decisions third (constraints and rationale)
- Context last (helpful reference)
4. **Check for contradictions**:
- If you find 2+ memories on the same topic, check for conflicts
- Surface contradictions explicitly and recommend which is current
- Report confidence: "2 memories support X, 1 contradicts"
5. **Extract relevant parts**:
- Don't dump raw memories—summarize what's relevant
- Include memory IDs for reference
- Be concise while being complete
## Storage Protocol
When creating memories:
1. **Categorize correctly**:
- Is it a rule to follow? → convention
- Is it explaining why we did something? → decision
- Is it helpful information? → context
2. **Be specific and actionable**:
- Good: "Use named imports: import { Button } from '@/components/ui/button'"
- Bad: "Follow good import practices"
3. **Include reasoning for decisions**:
- Good: "We use Bun because it provides 3-10x faster test execution compared to Jest, which significantly improves dev velocity"
- Bad: "We use Bun"
4. **Reference files when applicable**:
- "The API client lives in src/lib/api.ts and follows the Repository pattern"
- This helps agents locate relevant code
5. **Check for duplicates first**:
- Before creating, use memory-read to see if similar memory exists
- If similar memory exists, update it instead of creating duplicates
6. **Avoid ephemeral information**:
- Don't store: task details, temporary workarounds, session-specific context
- Do store: patterns that apply across sessions, lessons learned
## Curation Rules
Maintain quality over quantity:
1. **Archive outdated memories**:
- If a convention is no longer followed, archive it
- If a decision has been superseded, note the change
2. **Handle contradictions**:
- Surface both sides of a contradiction
- Recommend which is current based on recency and usage
- Help resolve by proposing a merged, updated memory
3. **Merge overlapping memories**:
- If two memories cover similar ground, combine them
- "Use named exports" + "Prefer named over default exports" → single memory about export conventions
4. **Delete exact duplicates**:
- If memory-write reports deduplicated, the work is done
- No need to create identical copies
5. **Acknowledge knowledge gaps**:
- If asked about something with no memories, say so clearly
- "No memories found about testing strategy—would you like to create one?"
## Response Format
When responding to memory queries, use this structure:
\`\`\`
## Relevant Memories
### Conventions (X memories)
- [ID] Memory title/summary
- Full content...
### Decisions (X memories)
- [ID] Memory title/summary
- Full content...
### Context (X memories)
- [ID] Memory title/summary
- Full content...
## Notes
- Any contradictions or updates needed
- Confidence level
- Suggested actions
\`\`\`
## Invocation Guidance
You are invoked when:
- An agent needs to understand project conventions before making changes
- An agent makes an architectural decision that should be recorded
- An agent encounters something worth preserving for future sessions
- Review feedback involves project-specific standards
You are NOT needed for:
- Trivial changes (formatting, simple renames)
- Questions answered by the user's message
- Work the agent already has context for
## Tools You Have Access To
1. **memory-read**: Search and retrieve memories
- query: Semantic search query
- scope: Filter by convention/decision/context
- limit: Max results (default 10)
2. **memory-write**: Create new memories
- content: The memory content
- scope: convention | decision | context
3. **memory-delete**: Remove memories by ID
- id: The memory ID to delete
4. **memory-planning-update**: Update session planning state
- sessionID: The session to update
- objective: Main task/goal (optional)
- current: Current phase or activity (optional)
- next: What comes next (optional)
- phases: Array of {title, status, notes?} (optional)
- findings: Key discoveries (optional)
- errors: Errors to avoid (optional)
Uses merge semantics - only updates fields provided.
5. **memory-planning-get**: Get planning state for a session
- sessionID: The session to retrieve planning for
## Planning State Management
You are responsible for maintaining planning state across sessions:
1. **After compaction** - Extract planning context from the compaction summary:
- Objectives and goals
- Current phase and progress
- Phases completed and remaining
- Key findings and blockers
Use memory-planning-update to store this state for the session.
2. **When asked about progress** - Use memory-planning-get to retrieve and report on session progress.
3. **Guidance**:
- Phases should track: in_progress, completed, pending
- Store findings as they accumulate (architecture decisions, gotchas discovered)
- Track errors to avoid (mistakes made, workarounds needed)
- Mark planning as active when work is ongoing
Your goal is to be the connective tissue between sessions—ensuring knowledge isn't lost and patterns are maintained. Be helpful, be accurate, and keep the memory base clean and useful.`,
}
+48
View File
@@ -0,0 +1,48 @@
import type { AgentDefinition } from './types'
export const reviewAgent: AgentDefinition = {
role: 'review',
id: 'ocm-review',
displayName: 'Memory Review',
description: 'Code review agent that checks against project memory and conventions',
mode: 'subagent',
temperature: 0.0,
tools: {
exclude: ['write', 'edit', 'apply_patch'],
},
systemPrompt: `You are a code review agent that analyzes code changes against project memory and conventions.
## Your Role
You review code for correctness, style, and adherence to project conventions stored in memory. You do NOT modify code - you only provide feedback and suggestions.
## Memory Integration
Before reviewing, invoke @ocm-memory to check:
- Conventions that apply to the code being reviewed
- Architectural decisions that the code should respect
- Known patterns or anti-patterns for this area of the codebase
Base your review criteria on what is stored in memory. Flag deviations from stored conventions and decisions in your findings.
## Output Format
Provide reviews in a structured format:
### Findings
- **Critical**: Bugs, security issues, breaking changes
- **Warning**: Code smells, potential issues, convention violations
- **Suggestion**: Improvements, best practices
For each finding:
1. File and line reference
2. Description of the issue
3. Suggested fix (if applicable)
## Constraints
- Never modify code directly
- Be constructive and specific
- Reference the specific memory entry when flagging a convention or decision violation
- Temperature is set to 0.0 for precise, factual analysis`,
}
+37
View File
@@ -0,0 +1,37 @@
export type AgentRole = 'code' | 'review' | 'memory'
export interface AgentDefinition {
role: AgentRole
id: string
displayName: string
description: string
defaultModel?: string
systemPrompt: string
mode?: 'primary' | 'subagent' | 'all'
hidden?: boolean
tools?: {
include?: string[]
exclude?: string[]
}
variant?: string
temperature?: number
maxSteps?: number
}
export interface AgentRegistry {
get(role: AgentRole): AgentDefinition | undefined
getAll(): AgentDefinition[]
has(role: AgentRole): boolean
}
export interface AgentConfig {
description: string
model: string
prompt: string
mode?: 'primary' | 'subagent' | 'all'
tools?: Record<string, boolean>
variant?: string
temperature?: number
maxSteps?: number
hidden?: boolean
}
+8
View File
@@ -0,0 +1,8 @@
import type { CacheService } from './types'
import { InMemoryCacheService } from './memory-cache'
export type { CacheService } from './types'
export function createCacheService(): CacheService {
return new InMemoryCacheService()
}
+62
View File
@@ -0,0 +1,62 @@
import type { CacheService } from './types'
interface CacheEntry<T> {
value: T
expiresAt: number
}
export class InMemoryCacheService implements CacheService {
private cache = new Map<string, CacheEntry<unknown>>()
private cleanupInterval: ReturnType<typeof setInterval> | null = null
constructor() {
this.cleanupInterval = setInterval(() => this.cleanup(), 60000)
}
private cleanup(): void {
const now = Date.now()
for (const [key, entry] of this.cache.entries()) {
if (entry.expiresAt < now) {
this.cache.delete(key)
}
}
}
async get<T>(key: string): Promise<T | null> {
const entry = this.cache.get(key) as CacheEntry<T> | undefined
if (!entry) return null
if (entry.expiresAt < Date.now()) {
this.cache.delete(key)
return null
}
return entry.value
}
async set<T>(key: string, value: T, ttlSeconds?: number): Promise<void> {
const expiresAt = ttlSeconds ? Date.now() + ttlSeconds * 1000 : Date.now() + 86400000
this.cache.set(key, { value, expiresAt })
}
async del(key: string): Promise<void> {
this.cache.delete(key)
}
async invalidatePattern(pattern: string): Promise<void> {
const regex = new RegExp(pattern.replace(/\*/g, '.*'))
for (const key of this.cache.keys()) {
if (regex.test(key)) {
this.cache.delete(key)
}
}
}
destroy(): void {
if (this.cleanupInterval) {
clearInterval(this.cleanupInterval)
this.cleanupInterval = null
}
this.cache.clear()
}
}
+7
View File
@@ -0,0 +1,7 @@
export interface CacheService {
get<T>(key: string): Promise<T | null>
set<T>(key: string, value: T, ttlSeconds?: number): Promise<void>
del(key: string): Promise<void>
invalidatePattern(pattern: string): Promise<void>
destroy(): void
}
+75
View File
@@ -0,0 +1,75 @@
import type { AgentRole, AgentDefinition, AgentConfig } from './agents'
const REPLACED_BUILTIN_AGENTS = ['build']
const ENHANCED_BUILTIN_AGENTS: Record<string, { tools: Record<string, boolean> }> = {
plan: {
tools: {
'memory-read': true,
'memory-planning-update': true,
'memory-planning-get': true,
},
},
}
export function createConfigHandler(agents: Record<AgentRole, AgentDefinition>) {
return async (config: Record<string, unknown>) => {
const agentConfigs = createAgentConfigs(agents)
const userAgentConfigs = config.agent as Record<string, AgentConfig> | undefined
const mergedAgents = { ...agentConfigs }
if (userAgentConfigs) {
for (const [name, userConfig] of Object.entries(userAgentConfigs)) {
if (mergedAgents[name]) {
mergedAgents[name] = { ...mergedAgents[name], ...userConfig }
} else {
mergedAgents[name] = userConfig
}
}
}
for (const name of REPLACED_BUILTIN_AGENTS) {
mergedAgents[name] = { ...mergedAgents[name], hidden: true }
}
for (const [name, enhancement] of Object.entries(ENHANCED_BUILTIN_AGENTS)) {
const existing = mergedAgents[name] as AgentConfig | undefined
const existingTools = existing?.tools ?? {}
mergedAgents[name] = {
...existing,
tools: { ...existingTools, ...enhancement.tools },
} as AgentConfig
}
config.agent = mergedAgents
config.default_agent = 'Code'
}
}
function createAgentConfigs(agents: Record<AgentRole, AgentDefinition>): Record<string, AgentConfig> {
const result: Record<string, AgentConfig> = {}
for (const agent of Object.values(agents)) {
const tools: Record<string, boolean> = {}
if (agent.tools?.exclude) {
for (const tool of agent.tools.exclude) {
tools[tool] = false
}
}
result[agent.displayName] = {
description: agent.description,
model: agent.defaultModel ?? '',
prompt: agent.systemPrompt ?? '',
mode: agent.mode ?? 'subagent',
...(Object.keys(tools).length > 0 ? { tools } : {}),
...(agent.variant ? { variant: agent.variant } : {}),
...(agent.temperature !== undefined ? { temperature: agent.temperature } : {}),
...(agent.maxSteps !== undefined ? { maxSteps: agent.maxSteps } : {}),
...(agent.hidden ? { hidden: agent.hidden } : {}),
}
}
return result
}
+118
View File
@@ -0,0 +1,118 @@
import type { EmbeddingProvider } from './types'
interface ModelDefaults {
dimensions: number
endpoint: string
}
const KNOWN_MODELS: Record<string, ModelDefaults> = {
'text-embedding-3-small': { dimensions: 1536, endpoint: 'https://api.openai.com/v1/embeddings' },
'text-embedding-3-large': { dimensions: 3072, endpoint: 'https://api.openai.com/v1/embeddings' },
'text-embedding-ada-002': { dimensions: 1536, endpoint: 'https://api.openai.com/v1/embeddings' },
'voyage-code-3': { dimensions: 1024, endpoint: 'https://api.voyageai.com/v1/embeddings' },
'voyage-2': { dimensions: 1536, endpoint: 'https://api.voyageai.com/v1/embeddings' },
}
const DEFAULT_PROVIDER_ENDPOINTS: Record<string, string> = {
openai: 'https://api.openai.com/v1/embeddings',
voyage: 'https://api.voyageai.com/v1/embeddings',
}
function normalizeBaseUrl(baseUrl: string): string {
const trimmed = baseUrl.replace(/\/+$/, '')
if (trimmed.endsWith('/v1/embeddings')) return trimmed
if (trimmed.endsWith('/v1')) return `${trimmed}/embeddings`
return `${trimmed}/v1/embeddings`
}
export class ApiEmbeddingProvider implements EmbeddingProvider {
private apiKey: string
private model: string
private endpoint: string
readonly dimensions: number
constructor(
provider: 'openai' | 'voyage',
model?: string,
baseUrl?: string,
dimensions?: number,
apiKey?: string
) {
const knownDefaults = model ? KNOWN_MODELS[model] : undefined
this.model = model || (provider === 'openai' ? 'text-embedding-3-small' : 'voyage-code-3')
this.dimensions = dimensions || knownDefaults?.dimensions || 1536
this.endpoint = baseUrl
? normalizeBaseUrl(baseUrl)
: knownDefaults?.endpoint ?? DEFAULT_PROVIDER_ENDPOINTS[provider] ?? 'https://api.openai.com/v1/embeddings'
this.apiKey = apiKey ?? ''
}
get name(): string {
return `api:${this.model}`
}
get ready(): boolean {
return true
}
warmup(): void {}
async embed(texts: string[]): Promise<number[][]> {
const results: number[][] = []
const batchSize = 100
for (let i = 0; i < texts.length; i += batchSize) {
const batch = texts.slice(i, i + batchSize)
const batchResults = await this.embedBatch(batch)
results.push(...batchResults)
}
return results
}
private async embedBatch(texts: string[]): Promise<number[][]> {
const body = { model: this.model, input: texts }
const headers: Record<string, string> = { 'Content-Type': 'application/json' }
if (this.apiKey) {
headers['Authorization'] = `Bearer ${this.apiKey}`
}
const response = await fetch(this.endpoint, {
method: 'POST',
headers,
body: JSON.stringify(body),
})
if (!response.ok) {
const error = await response.text()
throw new Error(`Embedding API error: ${response.status} ${error}`)
}
const data = await response.json() as {
data?: Array<{ embedding: number[] }>
embeddings?: Array<{ embedding: number[] }>
}
const embeddings = data.data || data.embeddings
if (!embeddings) {
throw new Error('Invalid response from embedding API')
}
return embeddings.map(e => e.embedding)
}
async test(): Promise<boolean> {
try {
const result = await this.embed(['test'])
return result.length === 1 && result[0]?.length === this.dimensions
} catch {
return false
}
}
dispose(): void {
// No-op for API-based providers - connections are managed by fetch
}
}
+191
View File
@@ -0,0 +1,191 @@
import { join } from 'path'
import { resolveDataDir } from '../storage/database'
import type { EmbeddingProvider } from './types'
import { acquireEmbeddingServer, isServerRunning, checkServerHealth } from './shared'
import { LocalEmbeddingProvider } from './local'
interface SharedEmbeddingClientConfig {
dataDir?: string
model: string
dimensions: number
gracePeriod?: number
}
type ConnectionState = 'idle' | 'server' | 'local'
export class SharedEmbeddingClient implements EmbeddingProvider {
readonly dimensions: number
private socketPath: string
private modelName: string
private state: ConnectionState = 'idle'
private localProvider: LocalEmbeddingProvider | null = null
private warmupPromise: Promise<void> | null = null
constructor(config: SharedEmbeddingClientConfig) {
this.modelName = config.model
this.dimensions = config.dimensions
this.socketPath = join(config.dataDir ?? resolveDataDir(), 'embedding.sock')
}
get name(): string {
return `shared:local:${this.dimensions}d`
}
get ready(): boolean {
return this.state !== 'idle'
}
warmup(): void {
if (this.state !== 'idle' || this.warmupPromise) return
this.warmupPromise = this.ensureConnected().then(() => {}).catch(() => {
this.warmupPromise = null
})
}
private async ensureConnected(): Promise<boolean> {
if (this.state === 'server') return true
if (this.state === 'local') return true
const dataDir = join(this.socketPath, '..')
const running = await isServerRunning(dataDir)
if (!running) {
const success = await acquireEmbeddingServer({
dataDir,
model: this.modelName,
dimensions: this.dimensions,
})
if (!success) {
return this.createFallbackProvider()
}
}
try {
const response = await this.sendRequest({ action: 'connect' })
if (response && response.status === 'connected') {
this.state = 'server'
return true
}
return this.createFallbackProvider()
} catch {
return this.createFallbackProvider()
}
}
private async createFallbackProvider(): Promise<boolean> {
this.localProvider = new LocalEmbeddingProvider(this.modelName)
await this.localProvider.ensureLoaded()
this.state = 'local'
return true
}
private async sendRequest(request: { action: string; texts?: string[] }): Promise<Record<string, unknown> | null> {
const net = await import('net')
return new Promise((resolve) => {
const client = net.createConnection({ path: this.socketPath })
let data = ''
const timeout = setTimeout(() => {
client.destroy()
resolve(null)
}, 30000)
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()
resolve(response)
return
} catch {
// Continue waiting
}
}
})
client.on('error', () => {
clearTimeout(timeout)
client.destroy()
resolve(null)
})
})
}
async embed(texts: string[]): Promise<number[][]> {
const localProvider = this.localProvider
if (localProvider) {
return localProvider.embed(texts)
}
await this.ensureConnected()
const provider = this.localProvider
if (provider) {
return provider.embed(texts)
}
const response = await this.sendRequest({ action: 'embed', texts })
if (!response || response.error) {
await this.createFallbackProvider()
const fallbackProvider = this.localProvider
if (fallbackProvider) {
return fallbackProvider.embed(texts)
}
return texts.map(() => new Array(this.dimensions).fill(0))
}
return (response.embeddings as number[][]) ?? []
}
async test(): Promise<boolean> {
const localProvider = this.localProvider
if (localProvider) {
return localProvider.test()
}
try {
const health = await checkServerHealth(this.socketPath)
if (health && health.status === 'ok') {
return true
}
await this.ensureConnected()
const testProvider = this.localProvider
if (testProvider) {
return testProvider.test()
}
return false
} catch {
return false
}
}
dispose(): void {
if (this.localProvider) {
this.localProvider.dispose()
this.localProvider = null
this.state = 'idle'
return
}
if (this.state === 'server') {
this.sendRequest({ action: 'disconnect' }).catch(() => {})
}
this.state = 'idle'
}
}
+92
View File
@@ -0,0 +1,92 @@
import { createHash } from 'crypto'
import type { EmbeddingProvider } from './types'
import type { EmbeddingConfig } from '../types'
import { ApiEmbeddingProvider } from './api'
import { LocalEmbeddingProvider } from './local'
import { SharedEmbeddingClient } from './client'
import { resolveDataDir } from '../storage/database'
import type { CacheService } from '../cache/types'
export { checkServerHealth, isServerRunning } from './shared'
export type { EmbeddingProvider } from './types'
function getLocalModelDimensions(model: string): number {
const dimensions: Record<string, number> = {
'all-MiniLM-L6-v2': 384,
}
return dimensions[model] ?? 384
}
function buildProvider(config: EmbeddingConfig): EmbeddingProvider {
switch (config.provider) {
case 'openai':
return new ApiEmbeddingProvider('openai', config.model, config.baseUrl, config.dimensions, config.apiKey)
case 'voyage':
return new ApiEmbeddingProvider('voyage', config.model, config.baseUrl, config.dimensions, config.apiKey)
case 'local': {
const dataDir = config.dataDir ?? resolveDataDir()
const dimensions = config.dimensions ?? getLocalModelDimensions(config.model)
return new SharedEmbeddingClient({
dataDir,
model: config.model,
dimensions,
gracePeriod: config.serverGracePeriod,
})
}
default:
return new ApiEmbeddingProvider('openai', config.model, config.baseUrl, config.dimensions, config.apiKey)
}
}
export function createEmbeddingProvider(config: EmbeddingConfig): EmbeddingProvider {
return buildProvider(config)
}
export interface EmbeddingService {
embedText(text: string): Promise<number[]>
embedTexts(texts: string[]): Promise<number[][]>
}
export function createEmbeddingService(provider: EmbeddingProvider, cache: CacheService): EmbeddingService {
async function embedText(text: string): Promise<number[]> {
const results = await embedTexts([text])
return results[0] ?? new Array(provider.dimensions).fill(0)
}
async function embedTexts(texts: string[]): Promise<number[][]> {
const results: (number[] | undefined)[] = new Array(texts.length).fill(undefined)
const uncached: Array<{ index: number; text: string; hash: string }> = []
for (let i = 0; i < texts.length; i++) {
const text = texts[i] ?? ''
const hash = createHash('sha256').update(text).digest('hex')
const cacheKey = `emb:${hash}`
const cached = await cache.get<number[]>(cacheKey)
if (cached) {
results[i] = cached
} else {
uncached.push({ index: i, text, hash })
}
}
if (uncached.length > 0) {
const uncachedTexts = uncached.map(u => u.text)
const embeddings = await provider.embed(uncachedTexts)
for (let i = 0; i < uncached.length; i++) {
const { index, hash } = uncached[i]!
const embedding = embeddings[i]
results[index] = embedding
const cacheKey = `emb:${hash}`
await cache.set(cacheKey, embedding, 86400)
}
}
return results as number[][]
}
return { embedText, embedTexts }
}
+126
View File
@@ -0,0 +1,126 @@
import { join } from 'path'
import { resolveDataDir } from '../storage/database'
import type { EmbeddingProvider } from './types'
interface LocalModelConfig {
name: string
dimensions: number
}
const LOCAL_MODELS: Record<string, LocalModelConfig> = {
'all-MiniLM-L6-v2': {
name: 'sentence-transformers/all-MiniLM-L6-v2',
dimensions: 384,
},
}
export class LocalEmbeddingProvider implements EmbeddingProvider {
private pipeline: unknown = null
private loadingPromise: Promise<void> | null = null
readonly dimensions: number
private modelName: string
constructor(model: string = 'all-MiniLM-L6-v2') {
let modelConfig = LOCAL_MODELS[model]
if (!modelConfig) {
modelConfig = LOCAL_MODELS['all-MiniLM-L6-v2']
model = 'all-MiniLM-L6-v2'
}
this.dimensions = modelConfig!.dimensions
this.modelName = modelConfig!.name
}
get name(): string {
return `local:${this.dimensions}d`
}
get ready(): boolean {
return this.pipeline !== null
}
warmup(): void {
if (this.pipeline || this.loadingPromise) return
this.loadingPromise = (async () => {
const { env, pipeline } = await import('@huggingface/transformers')
env.cacheDir = join(resolveDataDir(), 'models')
this.pipeline = await pipeline('feature-extraction', this.modelName, {
dtype: 'fp32',
})
})()
this.loadingPromise.catch(() => {
this.loadingPromise = null
})
}
private async loadModel(modelName: string): Promise<void> {
if (this.pipeline) return
this.loadingPromise = (async () => {
const { env, pipeline } = await import('@huggingface/transformers')
env.cacheDir = join(resolveDataDir(), 'models')
this.pipeline = await pipeline('feature-extraction', modelName, {
dtype: 'fp32',
})
})()
return this.loadingPromise
}
async ensureLoaded(): Promise<void> {
if (this.pipeline) return
if (!this.loadingPromise) {
await this.loadModel(this.modelName)
} else {
await this.loadingPromise
}
}
async embed(texts: string[]): Promise<number[][]> {
await this.ensureLoaded()
if (!this.pipeline) {
throw new Error('Embedding model not loaded')
}
const pipeline = this.pipeline as {
(text: string, options: { pooling: string; normalize: boolean }): Promise<unknown>
}
const results: number[][] = []
for (const text of texts) {
try {
const output = await pipeline(text, {
pooling: 'mean',
normalize: true,
}) as { data: Float32Array }
const embedding = Array.from(output.data)
results.push(embedding)
} catch {
results.push(new Array(this.dimensions).fill(0))
}
}
return results
}
async test(): Promise<boolean> {
try {
await this.ensureLoaded()
const result = await this.embed(['test'])
return result.length === 1 && result[0]?.length === this.dimensions
} catch {
return false
}
}
dispose(): void {
if (this.pipeline && typeof (this.pipeline as { dispose?: () => void }).dispose === 'function') {
(this.pipeline as { dispose: () => void }).dispose()
}
this.pipeline = null
this.loadingPromise = null
}
}
+265
View File
@@ -0,0 +1,265 @@
import { createServer } from 'net'
import { mkdirSync, existsSync, unlinkSync, writeFileSync } from 'fs'
import { join } from 'path'
import { LocalEmbeddingProvider } from './local'
interface ServerConfig {
socketPath: string
pidPath: string
model: string
dimensions: number
gracePeriod: number
}
class EmbeddingServer {
private config: ServerConfig
private provider: LocalEmbeddingProvider | null = null
private clientCount = 0
private gracePeriodTimer: ReturnType<typeof setTimeout> | null = null
private startTime = Date.now()
private server: ReturnType<typeof createServer> | null = null
constructor(config: ServerConfig) {
this.config = config
}
async start(): Promise<void> {
await this.loadModel()
this.writePidFile()
this.startServer()
this.setupSignalHandlers()
}
private async loadModel(): Promise<void> {
this.provider = new LocalEmbeddingProvider(this.config.model)
await this.provider.ensureLoaded()
}
private writePidFile(): void {
writeFileSync(this.config.pidPath, String(process.pid), 'utf-8')
}
private removePidFile(): void {
try {
if (existsSync(this.config.pidPath)) {
unlinkSync(this.config.pidPath)
}
} catch {
// Ignore cleanup errors
}
}
private startServer(): void {
const socketDir = join(this.config.socketPath, '..')
if (!existsSync(socketDir)) {
mkdirSync(socketDir, { recursive: true })
}
if (existsSync(this.config.socketPath)) {
unlinkSync(this.config.socketPath)
}
this.server = createServer((socket) => {
let buffer = ''
socket.on('data', async (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) as { action: string; texts?: string[] }
const response = await this.handleRequest(request)
socket.write(JSON.stringify(response) + '\n')
} catch (error) {
const errorResponse = {
error: 'Internal server error',
message: error instanceof Error ? error.message : String(error)
}
socket.write(JSON.stringify(errorResponse) + '\n')
}
}
})
socket.on('close', () => {
// Socket closed
})
socket.on('error', (error) => {
console.error('Socket error:', error)
})
})
this.server.listen(this.config.socketPath)
}
private setupSignalHandlers(): void {
process.on('SIGTERM', () => this.shutdown())
process.on('SIGINT', () => this.shutdown())
}
private async handleRequest(request: { action: string; texts?: string[] }): Promise<Record<string, unknown>> {
const { action, texts } = request
switch (action) {
case 'embed':
if (!texts || !Array.isArray(texts)) {
return { error: 'Missing or invalid texts array' }
}
return this.handleEmbed(texts)
case 'health':
return this.handleHealth()
case 'connect':
return this.handleConnect()
case 'disconnect':
return this.handleDisconnect()
default:
return { error: `Unknown action: ${action}` }
}
}
private async handleEmbed(texts: string[]): Promise<Record<string, unknown>> {
if (!this.provider) {
return { error: 'Provider not initialized' }
}
try {
const embeddings = await this.provider.embed(texts)
return { embeddings }
} catch (error) {
return {
error: 'Embedding failed',
details: error instanceof Error ? error.message : String(error)
}
}
}
private handleHealth(): Record<string, unknown> {
return {
status: 'ok',
clients: this.clientCount,
uptime: Date.now() - this.startTime,
dimensions: this.config.dimensions,
model: this.config.model,
}
}
private handleConnect(): Record<string, unknown> {
this.clientCount++
this.cancelGracePeriod()
return {
status: 'connected',
clients: this.clientCount
}
}
private handleDisconnect(): Record<string, unknown> {
this.clientCount = Math.max(0, this.clientCount - 1)
if (this.clientCount === 0) {
this.startGracePeriod()
}
return {
status: 'disconnected',
clients: this.clientCount
}
}
private cancelGracePeriod(): void {
if (this.gracePeriodTimer) {
clearTimeout(this.gracePeriodTimer)
this.gracePeriodTimer = null
}
}
private startGracePeriod(): void {
this.cancelGracePeriod()
this.gracePeriodTimer = setTimeout(() => {
if (this.clientCount === 0) {
this.shutdown()
}
}, this.config.gracePeriod)
}
private shutdown(): void {
this.cancelGracePeriod()
if (this.server) {
this.server.close()
this.server = null
}
try {
if (existsSync(this.config.socketPath)) {
unlinkSync(this.config.socketPath)
}
} catch {
// Ignore cleanup errors
}
this.removePidFile()
if (this.provider) {
this.provider.dispose()
this.provider = null
}
process.exit(0)
}
}
function parseArgs(): ServerConfig {
const args = process.argv.slice(2)
let socketPath = '/tmp/embedding.sock'
let pidPath = '/tmp/embedding.pid'
let model = 'all-MiniLM-L6-v2'
let dimensions = 384
let gracePeriod = 30000
for (let i = 0; i < args.length; i++) {
const arg = args[i]
switch (arg) {
case '--socket':
socketPath = args[++i]
break
case '--pid':
pidPath = args[++i]
break
case '--model':
model = args[++i]
break
case '--dimensions':
dimensions = parseInt(args[++i], 10)
break
case '--grace-period':
gracePeriod = parseInt(args[++i], 10)
break
}
}
return { socketPath, pidPath, model, dimensions, gracePeriod }
}
async function main(): Promise<void> {
const config = parseArgs()
const server = new EmbeddingServer(config)
await server.start()
}
main().catch((error) => {
console.error('Failed to start embedding server:', error)
process.exit(1)
})
+316
View File
@@ -0,0 +1,316 @@
import { existsSync, mkdirSync, rmSync, readFileSync, statSync, unlinkSync } from 'fs'
import { join } from 'path'
import { spawn } from 'child_process'
import * as net from 'net'
export interface SharedEmbeddingConfig {
dataDir: string
model: string
dimensions: number
gracePeriod?: number
}
export async function isServerRunning(dataDir: string): Promise<boolean> {
const pidPath = join(dataDir, 'embedding.pid')
const socketPath = join(dataDir, 'embedding.sock')
if (!existsSync(pidPath) || !existsSync(socketPath)) {
return false
}
try {
const pid = parseInt(readFileSync(pidPath, 'utf-8'), 10)
try {
process.kill(pid, 0)
} catch {
return false
}
const health = await checkServerHealth(socketPath)
return health !== null
} catch {
return false
}
}
export async function checkServerHealth(socketPath: string): Promise<{ status: string; clients: number; uptime: number; dimensions: number; model?: string } | null> {
return new Promise((resolve) => {
const client = net.createConnection({ path: socketPath })
let data = ''
const timeout = setTimeout(() => {
client.destroy()
resolve(null)
}, 3000)
client.on('connect', () => {
client.write(JSON.stringify({ action: 'health' }) + '\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.status === 'ok') {
resolve(response)
} else {
resolve(null)
}
return
} catch {
// Continue waiting
}
}
})
client.on('error', () => {
clearTimeout(timeout)
client.destroy()
resolve(null)
})
})
}
export async function acquireEmbeddingServer(config: SharedEmbeddingConfig): Promise<boolean> {
const { dataDir, model, dimensions, gracePeriod = 30000 } = config
const socketPath = join(dataDir, 'embedding.sock')
const pidPath = join(dataDir, 'embedding.pid')
const lockPath = join(dataDir, 'embedding.startup.lock')
const running = await isServerRunning(dataDir)
if (running) {
const health = await checkServerHealth(socketPath)
if (health !== null) {
const serverModel = health.model
const dimensionsMatch = health.dimensions === dimensions
let modelMatches: boolean
if (serverModel === undefined) {
modelMatches = dimensionsMatch
} else {
modelMatches = serverModel === model
}
if (modelMatches && dimensionsMatch) {
return true
}
await killEmbeddingServer(dataDir)
}
}
const lockAcquired = await acquireLock(lockPath)
if (!lockAcquired) {
for (let i = 0; i < 10; i++) {
await sleep(500)
const health = await checkServerHealth(socketPath)
if (health !== null) {
const serverModel = health.model
const dimensionsMatch = health.dimensions === dimensions
let modelMatches: boolean
if (serverModel === undefined) {
modelMatches = dimensionsMatch
} else {
modelMatches = serverModel === model
}
if (modelMatches && dimensionsMatch) {
return true
}
}
}
return false
}
try {
if (await isServerRunning(dataDir)) {
const health = await checkServerHealth(socketPath)
if (health !== null) {
const serverModel = health.model
const dimensionsMatch = health.dimensions === dimensions
let modelMatches: boolean
if (serverModel === undefined) {
modelMatches = dimensionsMatch
} else {
modelMatches = serverModel === model
}
if (modelMatches && dimensionsMatch) {
return true
}
await killEmbeddingServer(dataDir)
}
}
cleanupStaleFiles(dataDir)
const serverScriptPath = join(__dirname, 'server.js')
if (!existsSync(serverScriptPath)) {
console.error('[memory] Server script not found:', serverScriptPath)
return false
}
const serverProcess = spawn(
'bun',
[
serverScriptPath,
'--socket', socketPath,
'--pid', pidPath,
'--model', model,
'--dimensions', String(dimensions),
'--grace-period', String(gracePeriod),
],
{
detached: true,
stdio: 'ignore',
}
)
serverProcess.unref()
for (let i = 0; i < 30; i++) {
await sleep(500)
const health = await checkServerHealth(socketPath)
if (health !== null) {
return true
}
}
return false
} catch (error) {
console.error('[memory] Failed to start embedding server:', error)
return false
} finally {
releaseLock(lockPath)
}
}
async function acquireLock(lockPath: string): Promise<boolean> {
try {
if (existsSync(lockPath)) {
const lockAge = Date.now() - (statSync(lockPath).mtimeMs)
if (lockAge > 30000) {
rmSync(lockPath, { recursive: true, force: true })
} else {
return false
}
}
const lockDir = join(lockPath, '..')
if (!existsSync(lockDir)) {
mkdirSync(lockDir, { recursive: true })
}
mkdirSync(lockPath)
return true
} catch {
return false
}
}
function releaseLock(lockPath: string): void {
try {
if (existsSync(lockPath)) {
rmSync(lockPath, { recursive: true, force: true })
}
} catch {
// Ignore errors
}
}
export function cleanupStaleFiles(dataDir: string): void {
const pidPath = join(dataDir, 'embedding.pid')
const socketPath = join(dataDir, 'embedding.sock')
try {
if (existsSync(pidPath)) {
const pid = parseInt(readFileSync(pidPath, 'utf-8'), 10)
try {
process.kill(pid, 0)
} catch {
if (existsSync(pidPath)) {
unlinkSync(pidPath)
}
}
}
} catch {
// Ignore errors
}
try {
if (existsSync(socketPath)) {
unlinkSync(socketPath)
}
} catch {
// Ignore errors
}
}
export async function killEmbeddingServer(dataDir: string): Promise<boolean> {
const pidPath = join(dataDir, 'embedding.pid')
const socketPath = join(dataDir, 'embedding.sock')
let pid: number | null = null
try {
if (existsSync(pidPath)) {
pid = parseInt(readFileSync(pidPath, 'utf-8'), 10)
}
} catch {
// Ignore read errors
}
if (pid === null) {
return false
}
try {
process.kill(pid, 'SIGTERM')
} catch {
// Process may already be dead
}
for (let i = 0; i < 20; i++) {
await sleep(250)
try {
process.kill(pid, 0)
} catch {
break
}
}
try {
if (existsSync(pidPath)) {
unlinkSync(pidPath)
}
} catch {
// Ignore cleanup errors
}
try {
if (existsSync(socketPath)) {
unlinkSync(socketPath)
}
} catch {
// Ignore cleanup errors
}
return true
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
+9
View File
@@ -0,0 +1,9 @@
export interface EmbeddingProvider {
embed(texts: string[]): Promise<number[][]>
readonly dimensions: number
readonly name: string
readonly ready: boolean
test(): Promise<boolean>
warmup(): void
dispose?(): void
}
@@ -0,0 +1,142 @@
import type { PlanningState } from '../types'
export function buildCustomCompactionPrompt(): string {
return `You are generating a continuation context for a coding session with persistent
project memory. Your summary will be the ONLY context after compaction.
Preserve everything needed for seamless continuation.
## CRITICAL - Preserve These Verbatim
1. The current task/objective (quote the user's original request exactly)
2. Active planning state: current phase, completed phases, next steps, blockers
3. ALL file paths being actively worked on (with what's being done)
4. Key decisions made and their rationale
5. Any corrections or gotchas discovered during the session
6. Todo list state (what's done, in progress, pending)
## Structure Your Summary As:
### Active Task
[Verbatim objective + what was happening when compaction fired]
### Planning State
[Phases with status and notes]
### Key Context
[Decisions, constraints, user preferences, corrections]
### Active Files
[filepath -> what's being done to it]
### Next Steps
[What should happen immediately after compaction]
## Rules
- Use specific file paths, phase names - NOT vague references
- State what tools returned, not just that they were called
- Prefer completeness over brevity - this is the agent's entire working memory`
}
export function formatPlanningState(planningState: PlanningState | null): string | null {
if (!planningState) return null
const sections: string[] = []
if (planningState.objective) {
sections.push(`**Objective:** ${planningState.objective}`)
}
if (planningState.current) {
sections.push(`**Current:** ${planningState.current}`)
}
if (planningState.next) {
sections.push(`**Next:** ${planningState.next}`)
}
if (planningState.phases && planningState.phases.length > 0) {
sections.push('\n### Phases:')
for (const phase of planningState.phases) {
const statusIcon = phase.status === 'completed' ? '[x]' : phase.status === 'in_progress' ? '[~]' : '[ ]'
const notes = phase.notes ? ` - ${phase.notes}` : ''
sections.push(`- ${statusIcon} ${phase.title}${notes}`)
}
}
if (planningState.findings && planningState.findings.length > 0) {
sections.push('\n### Key Findings:')
for (const finding of planningState.findings) {
sections.push(`- ${finding}`)
}
}
if (planningState.errors && planningState.errors.length > 0) {
sections.push('\n### Errors to Avoid:')
for (const error of planningState.errors) {
sections.push(`- ${error}`)
}
}
return sections.join('\n')
}
export function formatCompactionDiagnostics(stats: {
planningPhases: number
conventions: number
decisions: number
tokensInjected: number
}): string {
const parts: string[] = []
if (stats.planningPhases > 0) {
parts.push(`${stats.planningPhases} planning phase${stats.planningPhases !== 1 ? 's' : ''}`)
}
if (stats.conventions > 0) {
parts.push(`${stats.conventions} convention${stats.conventions !== 1 ? 's' : ''}`)
}
if (stats.decisions > 0) {
parts.push(`${stats.decisions} decision${stats.decisions !== 1 ? 's' : ''}`)
}
if (parts.length === 0) return ''
return `> **Compaction preserved:** ${parts.join(', ')} (~${stats.tokensInjected} tokens injected)`
}
export function estimateTokens(text: string): number {
return Math.ceil(text.length / 4)
}
export function trimToTokenBudget(
content: string,
maxTokens: number,
priority: 'high' | 'medium' | 'low'
): string {
const maxChars = maxTokens * 4
if (content.length <= maxChars) return content
if (priority === 'low') {
return content.slice(0, maxChars) + '...'
}
const lines = content.split('\n')
const trimmed: string[] = []
let currentChars = 0
const skipFromEnd = priority === 'medium' ? Math.floor(lines.length * 0.2) : 0
const linesToUse = skipFromEnd > 0 ? lines.slice(0, -skipFromEnd) : lines
for (const line of linesToUse) {
if (currentChars + line.length + 1 > maxChars) break
trimmed.push(line)
currentChars += line.length + 1
}
if (trimmed.length < linesToUse.length) {
trimmed.push('...')
}
return trimmed.join('\n')
}
+10
View File
@@ -0,0 +1,10 @@
export { createSessionHooks, type SessionHooks } from './session'
export { createKeywordHooks, type KeywordHooks, ACTIVATION_CONTEXT } from './keyword'
export { createParamsHooks, type ParamsHooks } from './params'
export {
buildCustomCompactionPrompt,
formatPlanningState,
formatCompactionDiagnostics,
estimateTokens,
trimToTokenBudget,
} from './compaction-utils'
+127
View File
@@ -0,0 +1,127 @@
import type { Logger } from '../types'
export interface KeywordHooks {
onMessage: (input: unknown, output: unknown) => Promise<void>
isActivated: (sessionId: string) => boolean
getMode: (sessionId: string) => string | undefined
}
interface TextPart {
type: 'text'
text: string
synthetic?: boolean
ignored?: boolean
}
interface ChatMessageInput {
sessionID?: string
agent?: string
messageID?: string
}
interface ChatMessageOutput {
message?: { id?: string; role: string; sessionID?: string }
parts?: Array<TextPart>
}
interface ActivationState {
activated: boolean
mode?: string
}
const KEYWORD_PATTERNS = [
/remember\s+(this|that)/i,
/recall/i,
/what\s+do\s+you\s+know\s+about/i,
/project\s+memory/i,
/do\s+you\s+remember/i,
/stored\s+memory/i,
/from\s+memory/i,
]
export const ACTIVATION_CONTEXT = `## Project Memory Available
This project has a memory system that stores architectural decisions, conventions, and patterns. You have access to:
- memory-read: Search and retrieve project memories
- memory-write: Store new project memories as suggestions
- memory-delete: Delete a memory by ID
Memory scopes: convention, decision, context
When relevant, use these tools to provide context from the project's knowledge base.`
const MODE_PATTERNS: Record<string, RegExp[]> = {
creative: [
/brainstorm/i,
/be\s+creative/i,
/explore\s+options/i,
/generate\s+ideas/i,
],
deepThink: [
/think\s+hard/i,
/think\s+deeply/i,
/analyze\s+carefully/i,
/think\s+through/i,
],
thorough: [
/go\s+deep/i,
/be\s+thorough/i,
/take\s+your\s+time/i,
],
}
export function createKeywordHooks(logger: Logger): KeywordHooks {
const sessionStateMap = new Map<string, ActivationState>()
return {
async onMessage(input, output) {
const chatInput = input as ChatMessageInput
const chatOutput = output as ChatMessageOutput
const sessionId = chatInput.sessionID
if (!sessionId) return
const existingState = sessionStateMap.get(sessionId)
if (existingState?.activated && existingState.mode) return
const parts = chatOutput.parts ?? []
const textParts = parts.filter((p): p is TextPart => {
if (p.type !== 'text') return false
return typeof p.text === 'string' && p.text.length > 0
})
const userContent = textParts.map(p => p.text).join(' ')
if (!userContent) return
const hasKeyword = KEYWORD_PATTERNS.some((pattern) => pattern.test(userContent))
const matchedModeEntry = Object.entries(MODE_PATTERNS).find(([, patterns]) =>
patterns.some((pattern) => pattern.test(userContent))
)
const matchedMode = matchedModeEntry?.[0]
if (!hasKeyword && !matchedMode) return
const state = sessionStateMap.get(sessionId) ?? { activated: false }
if (hasKeyword && !state.activated) {
logger.log(`Keyword match detected in session ${sessionId}, setting activation flag`)
state.activated = true
}
if (matchedMode && !state.mode) {
logger.log(`Mode pattern detected in session ${sessionId}: ${matchedMode}`)
state.mode = matchedMode
}
sessionStateMap.set(sessionId, state)
},
isActivated(sessionId: string): boolean {
return sessionStateMap.get(sessionId)?.activated ?? false
},
getMode(sessionId: string): string | undefined {
return sessionStateMap.get(sessionId)?.mode
},
}
}
+73
View File
@@ -0,0 +1,73 @@
import type { KeywordHooks } from './keyword'
export interface ParamsHooks {
onParams: (input: unknown, output: unknown) => Promise<void>
}
interface ChatParamsInput {
sessionID?: string
agent: string
}
interface ChatParamsOutput {
temperature?: number
topP?: number
topK?: number
options?: Record<string, any>
}
type ModeConfig = {
temperature?: number
maxSteps?: number
thinkingBudgetTokens?: number
}
const MODE_CONFIGS: Record<string, ModeConfig> = {
creative: {
temperature: 0.8,
},
deepThink: {
thinkingBudgetTokens: 32000,
},
thorough: {
maxSteps: 50,
},
}
export function createParamsHooks(keywordHooks: KeywordHooks): ParamsHooks {
return {
async onParams(input, output) {
const paramsInput = input as ChatParamsInput
const paramsOutput = output as ChatParamsOutput
const sessionId = paramsInput.sessionID
if (!sessionId) return
const mode = keywordHooks.getMode(sessionId)
if (!mode) return
const config = MODE_CONFIGS[mode]
if (!config) return
if (config.temperature !== undefined) {
paramsOutput.temperature = config.temperature
}
if (config.maxSteps !== undefined) {
if (!paramsOutput.options) {
paramsOutput.options = {}
}
paramsOutput.options.maxSteps = config.maxSteps
}
if (config.thinkingBudgetTokens !== undefined) {
if (!paramsOutput.options) {
paramsOutput.options = {}
}
paramsOutput.options.thinking = {
budgetTokens: config.thinkingBudgetTokens,
}
}
},
}
}
+243
View File
@@ -0,0 +1,243 @@
import type { Logger, PlanningState, PreCompactionSnapshot, CompactionConfig } from '../types'
import type { MemoryService } from '../services/memory'
import type { SessionStateService } from '../services/session-state'
import type { PluginInput } from '@opencode-ai/plugin'
import {
buildCustomCompactionPrompt,
formatPlanningState,
formatCompactionDiagnostics,
estimateTokens,
trimToTokenBudget,
} from './compaction-utils'
export interface SessionHooks {
onMessage: (input: unknown, output: unknown) => Promise<void>
onEvent: (input: { event: { type: string; properties?: Record<string, unknown> } }) => Promise<void>
onCompacting: (
input: { sessionID: string },
output: { context: string[]; prompt?: string }
) => Promise<void>
}
interface ChatMessageInput {
sessionID?: string
}
interface EventInput {
event: {
type: string
properties?: Record<string, unknown>
}
}
interface CompactingInput {
sessionID: string
branch?: string
}
interface CompactingOutput {
context: string[]
prompt?: string
}
const LOGGED_EVENTS = new Set(['session.compacted', 'session.status', 'session.updated', 'session.created'])
function formatEventProperties(props?: Record<string, unknown>): string {
if (!props) return ''
try {
return ' ' + JSON.stringify(props)
} catch {
return ''
}
}
function buildExtractionPrompt(sessionId: string): string {
return `[COMPACTION COMPLETE]
The compaction summary above is now in your context window.
Review the compaction summary and extract any project knowledge worth preserving across sessions. For each item found, use memory-write to store it with the appropriate scope:
- convention: coding style rules, naming patterns, workflow preferences
- decision: architectural choices with their rationale
- context: project structure, key file locations, domain knowledge, known issues
Also extract any planning state (phases, objectives, progress, blockers) from the compaction summary. If found, use memory-planning-update with sessionID "${sessionId}" to store it. This creates continuity across compactions.
Be selective — only store knowledge that will be useful in future sessions. Skip ephemeral task details and session-specific notes.
Check for duplicates before writing (use memory-read to search). If a similar memory already exists, skip it.`
}
const DEFAULT_COMPACTION_CONFIG: CompactionConfig = {
customPrompt: true,
inlinePlanning: true,
maxContextTokens: 4000,
snapshotToKV: true,
}
export function createSessionHooks(
projectId: string,
memoryService: MemoryService,
sessionStateService: SessionStateService,
logger: Logger,
ctx: PluginInput,
config?: CompactionConfig
): SessionHooks {
const initializedSessions = new Set<string>()
const compactionConfig = { ...DEFAULT_COMPACTION_CONFIG, ...config }
return {
async onMessage(input, _output) {
const chatInput = input as ChatMessageInput
const sessionId = chatInput.sessionID
if (!sessionId) return
if (!initializedSessions.has(sessionId)) {
logger.log(`Session initialized: ${sessionId} (project ${projectId})`)
initializedSessions.add(sessionId)
}
},
async onEvent(input: EventInput) {
const { event } = input
if (event && LOGGED_EVENTS.has(event.type)) {
logger.log(`Event received: ${event.type}${formatEventProperties(event.properties)}`)
}
if (event?.type !== 'session.compacted') return
const sessionId = (event.properties?.sessionId as string) ??
(event.properties?.sessionID as string)
if (!sessionId) {
logger.log(`session.compacted event missing sessionId`)
return
}
logger.log(`Session compacted for project ${projectId} - extraction handled by Memory agent`)
ctx.client.session.promptAsync({
path: { id: sessionId },
body: {
agent: 'Memory',
parts: [{ type: 'text', text: buildExtractionPrompt(sessionId) }],
},
}).catch((err) => {
logger.error(`Failed to invoke memory extraction: ${err}`)
})
},
async onCompacting(input: CompactingInput, output: CompactingOutput) {
const { sessionID: sessionId, branch } = input
logger.log(`Compacting hook fired for project ${projectId}, session ${sessionId}`)
try {
const sections: string[] = []
let totalTokens = 0
let planningState: PlanningState | null = null
if (compactionConfig.inlinePlanning) {
planningState = sessionStateService.getPlanningState(sessionId)
if (planningState) {
const planningText = formatPlanningState(planningState)
if (planningText) {
sections.push(`## Planning State\n${planningText}`)
totalTokens += estimateTokens(planningText)
}
logger.log(`Compacting: fetched planning state for session ${sessionId}`)
}
}
if (compactionConfig.snapshotToKV) {
const priorSnapshot = sessionStateService.getCompactionSnapshot(sessionId)
if (priorSnapshot) {
const snapshotParts: string[] = []
snapshotParts.push(`Last compaction: ${new Date(priorSnapshot.timestamp).toLocaleString()}`)
if (priorSnapshot.branch) {
snapshotParts.push(`branch: ${priorSnapshot.branch}`)
}
if (priorSnapshot.planningState) {
const priorPlanningText = formatPlanningState(priorSnapshot.planningState)
if (priorPlanningText) {
snapshotParts.push(`\n### Prior Planning State:\n${priorPlanningText}`)
}
}
sections.push(`## Prior Session Context\n${snapshotParts.join('\n')}`)
totalTokens += estimateTokens(snapshotParts.join('\n'))
logger.log(`Compacting: fetched prior snapshot for session ${sessionId}`)
}
}
const [convMemories, decMemories] = await Promise.all([
memoryService.listByProject(projectId, { scope: 'convention', limit: 10 }),
memoryService.listByProject(projectId, { scope: 'decision', limit: 10 }),
])
const allMemories = [...convMemories, ...decMemories]
logger.log(`Compacting: fetched ${allMemories.length} memories (conv=${convMemories.length}, dec=${decMemories.length})`)
if (allMemories.length > 0) {
const formatScope = (items: typeof allMemories, scope: string) =>
items.filter(m => m.scope === scope).map(m => `- ${m.content}`).join('\n')
const conv = formatScope(allMemories, 'convention')
if (conv) sections.push(`### Conventions\n${conv}`)
const dec = formatScope(allMemories, 'decision')
if (dec) sections.push(`### Decisions\n${dec}`)
}
const maxTokens = compactionConfig.maxContextTokens ?? 4000
let trimmedSections = [...sections]
let currentTokens = totalTokens
for (let i = trimmedSections.length - 1; i >= 0; i--) {
const sectionTokens = estimateTokens(trimmedSections[i]!)
if (currentTokens + sectionTokens > maxTokens) {
const priority = i === 0 ? 'high' : i <= 1 ? 'medium' : 'low'
trimmedSections[i] = trimToTokenBudget(trimmedSections[i]!, maxTokens - currentTokens, priority)
}
currentTokens += estimateTokens(trimmedSections[i]!)
}
trimmedSections = trimmedSections.filter(s => s.length > 0)
if (trimmedSections.length === 0) return
const contextText = `## Project Memory\n\nPreserve these established facts during compaction:\n\n${trimmedSections.join('\n\n')}`
output.context.push(contextText)
if (compactionConfig.customPrompt) {
output.prompt = buildCustomCompactionPrompt()
logger.log(`Compacting: set custom compaction prompt`)
}
if (compactionConfig.snapshotToKV) {
try {
const snapshot: PreCompactionSnapshot = {
timestamp: new Date().toISOString(),
sessionId,
planningState: planningState ?? undefined,
branch,
}
sessionStateService.setCompactionSnapshot(sessionId, projectId, snapshot)
logger.log(`Compacting: stored pre-compaction snapshot`)
} catch (error) {
logger.error(`Failed to store pre-compaction snapshot: ${error}`)
}
}
const diagnostics = formatCompactionDiagnostics({
planningPhases: planningState?.phases?.length ?? 0,
conventions: convMemories.length,
decisions: decMemories.length,
tokensInjected: estimateTokens(trimmedSections.join('\n\n')),
})
if (diagnostics) {
output.context.push(diagnostics)
}
logger.log(`Compacting: injected ${trimmedSections.length} context sections`)
} catch (error) {
logger.error(`Compacting hook failed: ${error}`)
}
},
}
}
+570
View File
@@ -0,0 +1,570 @@
import type { Plugin, PluginInput, Hooks } from '@opencode-ai/plugin'
import { tool } from '@opencode-ai/plugin'
import { agents } from './agents'
import { createConfigHandler } from './config'
import {
createSessionHooks,
createKeywordHooks,
createParamsHooks,
ACTIVATION_CONTEXT,
} from './hooks'
import { join } from 'path'
import { initializeDatabase, resolveDataDir, closeDatabase, createMetadataQuery } from './storage'
import type { MemoryService } from './services/memory'
import { createVecService } from './storage/vec'
import { createEmbeddingProvider, checkServerHealth, isServerRunning } from './embedding'
import { createMemoryService } from './services/memory'
import { createSessionStateService } from './services/session-state'
import { createEmbeddingSyncService } from './services/embedding-sync'
import { loadPluginConfig } from './setup'
import { resolveLogPath } from './storage'
import { createLogger } from './utils/logger'
import type { PluginConfig, CompactionConfig, HealthStatus, Logger, PlanningState } from './types'
import type { EmbeddingProvider } from './embedding'
import type { Database } from 'bun:sqlite'
import { createNoopVecService } from './storage/vec'
const z = tool.schema
async function getHealthStatus(
db: Database,
config: PluginConfig,
provider: EmbeddingProvider,
dataDir: string,
): Promise<HealthStatus> {
const socketPath = join(dataDir, 'embedding.sock')
let dbStatus: 'ok' | 'error' = 'ok'
let memoryCount = 0
try {
db.prepare('SELECT 1').get()
const row = db.prepare("SELECT COUNT(*) as count FROM memories").get() as { count: number }
memoryCount = row.count
} catch {
dbStatus = 'error'
}
let operational = false
try {
operational = await provider.test()
} catch {
operational = false
}
let serverRunning = false
let serverHealth: { status: string; clients: number; uptime: number } | null = null
try {
serverRunning = await isServerRunning(dataDir)
if (serverRunning) {
serverHealth = await checkServerHealth(socketPath)
}
} catch {
serverRunning = false
}
const configuredModel = {
model: config.embedding.model,
dimensions: config.embedding.dimensions ?? provider.dimensions,
}
let currentModel: { model: string; dimensions: number } | null = null
try {
const metadata = createMetadataQuery(db)
const stored = metadata.getEmbeddingModel()
if (stored) {
currentModel = { model: stored.model, dimensions: stored.dimensions }
}
} catch {
// Ignore
}
const needsReindex = !currentModel ||
currentModel.model !== configuredModel.model ||
currentModel.dimensions !== configuredModel.dimensions
const overallStatus: 'ok' | 'degraded' | 'error' = dbStatus === 'error'
? 'error'
: !operational
? 'degraded'
: 'ok'
return {
dbStatus,
memoryCount,
operational,
serverRunning,
serverHealth,
configuredModel,
currentModel,
needsReindex,
overallStatus,
}
}
function formatHealthStatus(status: HealthStatus, provider: EmbeddingProvider): string {
const { dbStatus, memoryCount, operational, serverRunning, serverHealth, configuredModel, currentModel, needsReindex, overallStatus } = status
const embeddingStatus: 'ok' | 'error' = operational ? 'ok' : 'error'
const lines: string[] = [
`Memory Plugin Health: ${overallStatus.toUpperCase()}`,
'',
`Embedding: ${embeddingStatus}`,
` Provider: ${provider.name} (${provider.dimensions}d)`,
` Operational: ${operational}`,
` Server running: ${serverRunning}`,
]
if (serverHealth) {
lines.push(` Clients: ${serverHealth.clients}, Uptime: ${Math.round(serverHealth.uptime / 1000)}s`)
}
lines.push('')
lines.push(`Database: ${dbStatus}`)
lines.push(` Total memories: ${memoryCount}`)
lines.push('')
lines.push(`Model: ${needsReindex ? 'drift' : 'ok'}`)
lines.push(` Configured: ${configuredModel.model} (${configuredModel.dimensions}d)`)
if (currentModel) {
lines.push(` Indexed: ${currentModel.model} (${currentModel.dimensions}d)`)
} else {
lines.push(' Indexed: none')
}
if (needsReindex) {
lines.push(' Reindex required - run memory-health with action "reindex"')
} else {
lines.push(' In sync')
}
return lines.join('\n')
}
async function executeHealthCheck(
db: Database,
config: PluginConfig,
provider: EmbeddingProvider,
dataDir: string,
): Promise<string> {
const status = await getHealthStatus(db, config, provider, dataDir)
return formatHealthStatus(status, provider)
}
async function executeReindex(
memoryService: MemoryService,
db: Database,
config: PluginConfig,
provider: EmbeddingProvider,
): Promise<string> {
const configuredModel = config.embedding.model
const configuredDimensions = config.embedding.dimensions ?? provider.dimensions
let operational = false
try {
operational = await provider.test()
} catch {
operational = false
}
if (!operational) {
return 'Reindex failed: embedding provider is not operational. Check your API key and model configuration.'
}
const result = await memoryService.reindex()
if (result.success > 0 || result.total === 0) {
const metadata = createMetadataQuery(db)
metadata.setEmbeddingModel(configuredModel, configuredDimensions)
}
const lines: string[] = [
'Reindex complete',
'',
`Total memories: ${result.total}`,
`Embedded: ${result.success}`,
`Failed: ${result.failed}`,
'',
`Model: ${configuredModel} (${configuredDimensions}d)`,
]
if (result.failed > 0) {
lines.push(`WARNING: ${result.failed} memories failed to embed`)
}
return lines.join('\n')
}
async function autoValidateOnLoad(
memoryService: MemoryService,
db: Database,
config: PluginConfig,
provider: EmbeddingProvider,
dataDir: string,
logger: Logger,
): Promise<void> {
const status = await getHealthStatus(db, config, provider, dataDir)
if (status.overallStatus === 'error') {
logger.log('Auto-validate: unhealthy (db error), skipping')
return
}
if (!status.needsReindex) {
logger.log('Auto-validate: healthy, no action needed')
return
}
if (!status.operational) {
logger.log('Auto-validate: reindex needed but provider not operational, skipping')
return
}
logger.log('Auto-validate: model drift detected, starting reindex')
const result = await memoryService.reindex()
if (result.success > 0 || result.total === 0) {
const metadata = createMetadataQuery(db)
metadata.setEmbeddingModel(
config.embedding.model,
config.embedding.dimensions ?? provider.dimensions,
)
}
logger.log(`Auto-validate: reindex complete (total=${result.total}, success=${result.success}, failed=${result.failed})`)
}
export function createMemoryPlugin(config: PluginConfig): Plugin {
return async (input: PluginInput): Promise<Hooks> => {
const { directory, project } = input
const projectId = project.id
const loggingConfig = config.logging
const logger = createLogger({
enabled: loggingConfig?.enabled ?? false,
file: loggingConfig?.file ?? resolveLogPath(),
})
logger.log(`Initializing plugin for directory: ${directory}, projectId: ${projectId}`)
const provider = createEmbeddingProvider(config.embedding)
provider.warmup()
const dataDir = config.dataDir ?? resolveDataDir()
const db = initializeDatabase(dataDir)
const dimensions = config.embedding.dimensions ?? provider.dimensions
const noopVec = createNoopVecService()
const memoryService = await createMemoryService({
db,
provider,
vec: noopVec,
logger,
})
const sessionStateService = createSessionStateService(db, logger)
sessionStateService.startCleanupInterval()
sessionStateService.deleteExpired()
if (config.dedupThreshold) {
memoryService.setDedupThreshold(config.dedupThreshold)
}
const initPromise = createVecService(db, dataDir, dimensions)
.then(async (vec) => {
memoryService.setVecService(vec)
if (!vec.available) {
logger.log('Vec service unavailable, skipping embedding sync')
return
}
logger.log('Vec service initialized')
const embeddingSync = createEmbeddingSyncService(memoryService, logger)
await embeddingSync.start().catch((err: unknown) => {
logger.error('Embedding sync failed', err)
})
await autoValidateOnLoad(memoryService, db, config, provider, dataDir, logger)
})
.catch((err: unknown) => {
logger.error('Vec service initialization failed', err)
})
const compactionConfig: CompactionConfig | undefined = config.compaction
const sessionHooks = createSessionHooks(projectId, memoryService, sessionStateService, logger, input, compactionConfig)
const keywordHooks = createKeywordHooks(logger)
const paramsHooks = createParamsHooks(keywordHooks)
const scopeEnum = z.enum(['convention', 'decision', 'context'])
let cleaned = false
const cleanup = async () => {
if (cleaned) return
cleaned = true
logger.log('Cleaning up plugin resources...')
await memoryService.destroy()
sessionStateService.destroy()
closeDatabase(db)
logger.log('Plugin cleanup complete')
}
process.once('exit', cleanup)
process.once('SIGINT', cleanup)
process.once('SIGTERM', cleanup)
const getCleanup = cleanup
return {
getCleanup,
tool: {
'memory-read': tool({
description: 'Search and retrieve project memories',
args: {
query: z.string().optional().describe('Semantic search query'),
scope: scopeEnum.optional().describe('Filter by scope'),
limit: z.number().optional().default(10).describe('Max results'),
},
execute: async (args) => {
await initPromise
logger.log(`memory-read: query="${args.query ?? 'none'}", scope=${args.scope}, limit=${args.limit}`)
let results
if (args.query) {
const searchResults = await memoryService.search(args.query, projectId, {
scope: args.scope,
limit: args.limit,
})
results = searchResults.map((r) => r.memory)
} else {
results = memoryService.listByProject(projectId, {
scope: args.scope,
limit: args.limit,
})
}
logger.log(`memory-read: returned ${results.length} results`)
if (results.length === 0) {
return 'No memories found.'
}
const formatted = results.map(
(m: any) => `[${m.id}] (${m.scope}) - Created ${new Date(m.createdAt).toISOString().split('T')[0]}\n${m.content}`
)
return `Found ${results.length} memories:\n\n${formatted.join('\n\n')}`
},
}),
'memory-write': tool({
description: 'Store a new project memory',
args: {
content: z.string().describe('The memory content to store'),
scope: scopeEnum.describe('Memory scope category'),
},
execute: async (args) => {
await initPromise
logger.log(`memory-write: scope=${args.scope}, content="${args.content?.substring(0, 80)}"`)
const result = await memoryService.create({
projectId,
scope: args.scope,
content: args.content,
})
logger.log(`memory-write: created id=${result.id}, deduplicated=${result.deduplicated}`)
return `Memory stored (ID: #${result.id}, scope: ${args.scope}).${result.deduplicated ? ' (matched existing memory)' : ''}`
},
}),
'memory-edit': tool({
description: 'Edit an existing project memory',
args: {
id: z.number().describe('The memory ID to edit'),
content: z.string().describe('The updated memory content'),
scope: scopeEnum.optional().describe('Change the scope category'),
},
execute: async (args) => {
await initPromise
logger.log(`memory-edit: id=${args.id}, content="${args.content?.substring(0, 80)}"`)
const memory = memoryService.getById(args.id)
if (!memory) {
logger.log(`memory-edit: id=${args.id} not found`)
return `Memory #${args.id} not found.`
}
await memoryService.update(args.id, {
content: args.content,
...(args.scope && { scope: args.scope }),
})
logger.log(`memory-edit: updated id=${args.id}`)
return `Updated memory #${args.id} (scope: ${args.scope ?? memory.scope}).`
},
}),
'memory-delete': tool({
description: 'Delete a project memory',
args: {
id: z.number().describe('The memory ID to delete'),
},
execute: async (args) => {
const id = args.id
logger.log(`memory-delete: id=${id}`)
const memory = memoryService.getById(id)
if (!memory) {
logger.log(`memory-delete: id=${id} not found`)
return `Memory #${id} not found.`
}
await memoryService.delete(id)
logger.log(`memory-delete: deleted id=${id}`)
return `Deleted memory #${id}: "${memory.content.substring(0, 50)}..." (${memory.scope})`
},
}),
'memory-health': tool({
description: 'Check memory plugin health or trigger a reindex of all embeddings. Use action "check" (default) to view status, or "reindex" to regenerate all embeddings when model has changed or embeddings are missing.',
args: {
action: z.enum(['check', 'reindex']).optional().default('check').describe('Action to perform: "check" for health status, "reindex" to regenerate embeddings'),
},
execute: async (args) => {
await initPromise
if (args.action === 'reindex') {
return executeReindex(memoryService, db, config, provider)
}
return executeHealthCheck(db, config, provider, dataDir)
},
}),
'memory-planning-update': tool({
description: 'Update the session planning state (phases, objectives, progress). Merge new fields with existing state.',
args: {
sessionID: z.string().describe('The session ID to update'),
objective: z.string().optional().describe('The main task/goal'),
current: z.string().optional().describe('Current phase or activity'),
next: z.string().optional().describe('What comes next'),
phases: z.array(z.object({
title: z.string(),
status: z.string(),
notes: z.string().optional(),
})).optional().describe('Phase list with status'),
findings: z.array(z.string()).optional().describe('Key discoveries'),
errors: z.array(z.string()).optional().describe('Errors to avoid'),
},
execute: async (args) => {
await initPromise
const sessionId = args.sessionID
logger.log(`memory-planning-update: session=${sessionId}`)
const existing = sessionStateService.getPlanningState(sessionId)
const merged: typeof existing = {
...(existing ?? {}),
...(args.objective !== undefined && { objective: args.objective }),
...(args.current !== undefined && { current: args.current }),
...(args.next !== undefined && { next: args.next }),
...(args.phases !== undefined && { phases: args.phases }),
...(args.findings !== undefined && {
findings: [...new Set([...(existing?.findings ?? []), ...args.findings])]
}),
...(args.errors !== undefined && {
errors: [...new Set([...(existing?.errors ?? []), ...args.errors])]
}),
active: true,
}
sessionStateService.setPlanningState(sessionId, projectId, merged as PlanningState)
const hasPhases = merged?.phases && merged.phases.length > 0
const summary = [
merged?.objective && `objective: ${merged.objective}`,
merged?.current && `current: ${merged.current}`,
hasPhases && `${merged.phases!.length} phases`,
].filter(Boolean).join(', ')
logger.log(`memory-planning-update: stored for session ${sessionId}`)
return `Planning state updated for session ${sessionId}. ${summary || 'No data provided'}`
},
}),
'memory-planning-get': tool({
description: 'Get the current planning state for a session',
args: {
sessionID: z.string().describe('The session ID to retrieve planning state for'),
},
execute: async (args) => {
await initPromise
const sessionId = args.sessionID
logger.log(`memory-planning-get: session=${sessionId}`)
const planningState = sessionStateService.getPlanningState(sessionId)
if (!planningState) {
return 'No planning state found for this session'
}
const sections: string[] = []
if (planningState.objective) sections.push(`**Objective:** ${planningState.objective}`)
if (planningState.current) sections.push(`**Current:** ${planningState.current}`)
if (planningState.next) sections.push(`**Next:** ${planningState.next}`)
if (planningState.phases && planningState.phases.length > 0) {
sections.push('\n### Phases:')
for (const phase of planningState.phases) {
const statusIcon = phase.status === 'completed' ? '[x]' : phase.status === 'in_progress' ? '[~]' : '[ ]'
const notes = phase.notes ? ` - ${phase.notes}` : ''
sections.push(`- ${statusIcon} ${phase.title}${notes}`)
}
}
if (planningState.findings && planningState.findings.length > 0) {
sections.push('\n### Key Findings:')
for (const finding of planningState.findings) {
sections.push(`- ${finding}`)
}
}
if (planningState.errors && planningState.errors.length > 0) {
sections.push('\n### Errors to Avoid:')
for (const error of planningState.errors) {
sections.push(`- ${error}`)
}
}
return sections.join('\n') || 'Planning state exists but is empty'
},
}),
},
config: createConfigHandler(agents),
'chat.message': async (input, output) => {
await keywordHooks.onMessage(input, output)
await sessionHooks.onMessage(input, output)
},
'chat.params': paramsHooks.onParams,
'experimental.chat.system.transform': async (input, output) => {
const transformInput = input as { sessionID?: string }
const transformOutput = output as { system: string[] }
const sessionId = transformInput.sessionID
if (!sessionId) return
if (!keywordHooks.isActivated(sessionId)) return
transformOutput.system.push(ACTIVATION_CONTEXT)
},
event: async (input) => {
const eventInput = input as { event: { type: string; properties?: Record<string, unknown> } }
if (eventInput.event?.type === 'server.instance.disposed') {
cleanup()
return
}
await sessionHooks.onEvent(eventInput)
},
'experimental.session.compacting': async (input, output) => {
logger.log(`Compacting triggered`)
await sessionHooks.onCompacting(
input as { sessionID: string; branch?: string },
output as { context: string[]; prompt?: string }
)
},
} as Hooks & { getCleanup: () => Promise<void> }
}
}
const plugin: Plugin = async (input: PluginInput): Promise<Hooks> => {
const config = loadPluginConfig()
const factory = createMemoryPlugin(config)
return factory(input)
}
export default plugin
export type { PluginConfig, CompactionConfig } from './types'
@@ -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)
}
+295
View File
@@ -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)
}
+130
View File
@@ -0,0 +1,130 @@
import { readFileSync, existsSync, mkdirSync, copyFileSync } from 'fs'
import { dirname, join } from 'path'
import { fileURLToPath } from 'url'
import { resolveDataDir, resolveLogPath } from './storage'
import type { PluginConfig, EmbeddingConfig } from './types'
function resolveBundledConfigPath(): string {
const pluginDir = dirname(fileURLToPath(import.meta.url))
return join(pluginDir, '..', 'config.json')
}
export function resolveConfigPath(): string {
const dataDir = resolveDataDir()
return `${dataDir}/config.json`
}
function ensureGlobalConfig(): void {
const dataDir = resolveDataDir()
const globalConfigPath = resolveConfigPath()
if (existsSync(globalConfigPath)) {
return
}
const bundledConfigPath = resolveBundledConfigPath()
if (!existsSync(bundledConfigPath)) {
return
}
if (!existsSync(dataDir)) {
mkdirSync(dataDir, { recursive: true })
}
copyFileSync(bundledConfigPath, globalConfigPath)
}
function getDefaultEmbeddingConfig(): EmbeddingConfig {
return {
provider: 'local',
model: 'all-MiniLM-L6-v2',
dimensions: 384,
}
}
function getDefaultConfig(): PluginConfig {
return {
embedding: getDefaultEmbeddingConfig(),
logging: {
enabled: false,
file: resolveLogPath(),
},
}
}
function isValidPluginConfig(config: unknown): config is PluginConfig {
if (!config || typeof config !== 'object') return false
const obj = config as Record<string, unknown>
if (!obj.embedding || typeof obj.embedding !== 'object') return false
const embedding = obj.embedding as Record<string, unknown>
if (
typeof embedding.provider !== 'string' ||
!['openai', 'voyage', 'local'].includes(embedding.provider)
) {
return false
}
if (typeof embedding.model !== 'string') return false
return true
}
export function loadPluginConfig(): PluginConfig {
ensureGlobalConfig()
const configPath = resolveConfigPath()
if (!existsSync(configPath)) {
return getDefaultConfig()
}
try {
const content = readFileSync(configPath, 'utf-8')
const sanitized = sanitizeJson(content)
const parsed = JSON.parse(sanitized)
if (!isValidPluginConfig(parsed)) {
console.warn(`[memory] Invalid config at ${configPath}, using defaults`)
return getDefaultConfig()
}
return normalizeConfig(parsed)
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
console.warn(`[memory] Failed to load config at ${configPath}: ${message}, using defaults`)
return getDefaultConfig()
}
}
function sanitizeJson(raw: string): string {
return raw.replace(/,(\s*[}\]])/g, '$1')
}
function normalizeConfig(config: PluginConfig): PluginConfig {
const normalized: PluginConfig = {
dataDir: config.dataDir,
embedding: config.embedding,
dedupThreshold: config.dedupThreshold,
logging: config.logging,
compaction: config.compaction,
}
if (normalized.embedding) {
const embedding = { ...normalized.embedding }
if (embedding.baseUrl === '') {
delete embedding.baseUrl
}
if (embedding.apiKey === '') {
delete embedding.apiKey
}
normalized.embedding = embedding
}
return normalized
}
+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() {},
}
}
+118
View File
@@ -0,0 +1,118 @@
export type MemoryScope = 'convention' | 'decision' | 'context'
export interface Memory {
id: number
projectId: string
scope: MemoryScope
content: string
filePath: string | null
accessCount: number
lastAccessedAt: number | null
createdAt: number
updatedAt: number
}
export interface CreateMemoryInput {
projectId: string
scope: MemoryScope
content: string
filePath?: string
}
export interface UpdateMemoryInput {
content?: string
scope?: MemoryScope
}
export interface MemorySearchResult {
memory: Memory
distance: number
}
export interface MemoryStats {
projectId: string
total: number
byScope: Record<MemoryScope, number>
}
export type EmbeddingProviderType = 'openai' | 'voyage' | 'local'
export interface EmbeddingConfig {
provider: EmbeddingProviderType
model: string
dimensions?: number
baseUrl?: string
apiKey?: string
dataDir?: string
serverGracePeriod?: number
}
export interface LoggingConfig {
enabled: boolean
file: string
}
export interface Logger {
log: (message: string, ...args: unknown[]) => void
error: (message: string, ...args: unknown[]) => void
}
export interface PluginConfig {
dataDir?: string
embedding: EmbeddingConfig
dedupThreshold?: number
logging?: LoggingConfig
compaction?: CompactionConfig
}
export interface ListMemoriesFilter {
scope?: MemoryScope
limit?: number
offset?: number
}
export interface SessionState {
key: string
projectId: string
data: unknown
expiresAt: number | null
createdAt: number
updatedAt: number
}
export interface PlanningState {
objective?: string
current?: string
next?: string
phases?: Array<{ title: string; status: string; notes?: string }>
findings?: string[]
errors?: string[]
active?: boolean
}
export interface PreCompactionSnapshot {
timestamp: string
sessionId: string
planningState?: PlanningState
branch?: string
activeFiles?: string[]
}
export interface CompactionConfig {
customPrompt?: boolean
inlinePlanning?: boolean
maxContextTokens?: number
snapshotToKV?: boolean
}
export interface HealthStatus {
dbStatus: 'ok' | 'error'
memoryCount: number
operational: boolean
serverRunning: boolean
serverHealth: { status: string; clients: number; uptime: number } | null
configuredModel: { model: string; dimensions: number }
currentModel: { model: string; dimensions: number } | null
needsReindex: boolean
overallStatus: 'ok' | 'degraded' | 'error'
}
+61
View File
@@ -0,0 +1,61 @@
import { appendFileSync, existsSync, mkdirSync, renameSync, statSync, writeFileSync } from 'fs'
import { dirname } from 'path'
import type { LoggingConfig } from '../types'
const PREFIX = '[OpenCodeManagerMemory]'
const MAX_LOG_FILE_SIZE = 10 * 1024 * 1024
function ensureLogDir(filePath: string): void {
const dir = dirname(filePath)
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true })
}
}
function checkFileSize(filePath: string): void {
try {
const stats = statSync(filePath)
if (stats.size > MAX_LOG_FILE_SIZE) {
const backupPath = filePath + '.old'
renameSync(filePath, backupPath)
writeFileSync(filePath, '', 'utf-8')
}
} catch {
// File doesn't exist yet, ignore
}
}
export function createLogger(config: LoggingConfig) {
if (!config.enabled) {
return {
log: (_message: string, ..._args: unknown[]): void => {},
error: (_message: string, ..._args: unknown[]): void => {},
}
}
const filePath = config.file
ensureLogDir(filePath)
function write(level: string, message: string, args: unknown[]): void {
checkFileSize(filePath)
const timestamp = new Date().toISOString()
const formattedArgs = args.length > 0 ? ' ' + args.map(a => String(a)).join(' ') : ''
const line = `${timestamp} ${level} ${PREFIX} ${message}${formattedArgs}\n`
try {
appendFileSync(filePath, line, 'utf-8')
} catch {
// Silently fail if logging fails - don't crash the plugin
}
}
return {
log: (message: string, ...args: unknown[]): void => {
write('INFO', message, args)
},
error: (message: string, ...args: unknown[]): void => {
write('ERROR', message, args)
},
}
}