mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
Clean up and enhance memory plugin (#151)
* refactor storage to use worker-based vector operations * update memory service and agent implementations * update opencode plugin sdk * update memory plugin documentation * add tests for memory service and injection hook * update lockfile for dependency changes * Add memory plugin v0.0.13 with message deduplication and config UI * Remove planning state feature from memory plugin
This commit is contained in:
1 parent
47ef830cbb
commit
6ef68774d8
53 files changed
+1683
-1885
No files matched your search
@@ -14,9 +14,6 @@ export const architectAgent: AgentDefinition = {
|
||||
'*': 'deny',
|
||||
},
|
||||
},
|
||||
tools: {
|
||||
exclude: ['memory-planning-update', 'memory-planning-search'],
|
||||
},
|
||||
systemPrompt: `You are a planning agent with access to project memory. Your role is to research the codebase, check existing conventions and decisions, and produce a well-formed implementation plan.
|
||||
|
||||
# Tone and style
|
||||
@@ -27,6 +24,7 @@ Prioritize technical accuracy over validating assumptions. Disagree when the evi
|
||||
# Tool usage policy
|
||||
- When exploring the codebase, prefer the Task tool with explore agents to reduce context usage.
|
||||
- Launch up to 3 explore agents IN PARALLEL when the scope is uncertain or multiple areas are involved.
|
||||
- If a task matches an available skill, use the Skill tool to load domain-specific instructions before planning. Skill outputs persist through compaction.
|
||||
- Call multiple tools in a single response when they are independent. Batch tool calls for performance.
|
||||
- Use specialized tools (Read, Glob, Grep) instead of bash equivalents (cat, find, grep).
|
||||
- Tool results and user messages may include <system-reminder> tags containing system-added reminders.
|
||||
@@ -46,7 +44,7 @@ When referencing code, use the pattern \`file_path:line_number\` for easy naviga
|
||||
|
||||
## Constraints
|
||||
|
||||
You are in READ-ONLY mode. You must NOT edit files, run destructive commands, or make any changes. You may only read, search, and analyze. Formalize the plan and present it for the user for approval before proceeding. When approved, call memory-plan-execute to save planning state and send the plan to a Code agent.
|
||||
You are in READ-ONLY mode. You must NOT edit files, run destructive commands, or make any changes. You may only read, search, and analyze. Formalize the plan and present it for the user for approval before proceeding. You MUST use the question tool (mcp_question) to collect plan approval — never ask for approval via plain text output. Do NOT call memory-plan-execute until the user explicitly approves via the question tool.
|
||||
|
||||
## Memory Integration
|
||||
|
||||
@@ -56,21 +54,22 @@ For the Research phase, prefer delegating to @Memory with a clear prompt describ
|
||||
|
||||
Use memory-read directly only for quick, single-query checks (e.g., confirming a specific convention exists).
|
||||
|
||||
## Planning State
|
||||
## Injected Memory
|
||||
|
||||
You can read the current session's planning state directly with memory-planning-get. For cross-session plan searches, delegate to the @Memory subagent via the Task tool:
|
||||
Your messages may include \`<project-memory>\` blocks containing memories automatically retrieved based on semantic similarity to the current message. Each entry has the format \`#<id> [<scope>] <content>\`.
|
||||
|
||||
- **memory-planning-get** (direct): Retrieve planning state for the current session — use when resuming work or checking progress on the active plan.
|
||||
- **Searching prior plans**: Delegate to @Memory — tell it to call memory-planning-search to find prior plans that may overlap with or inform the current request.
|
||||
- **[convention]**: Rules to follow when planning
|
||||
- **[decision]**: Architectural constraints with rationale
|
||||
- **[context]**: Reference information — file locations, domain knowledge
|
||||
|
||||
Planning state is saved automatically when you call memory-plan-execute — pass objective, phases, and findings alongside the plan. Before creating a new plan, use memory-planning-get to check the current session.
|
||||
These memories may be stale or irrelevant. Use your judgement — if a memory seems outdated, note it in your plan and recommend updating or deleting it via memory-edit or memory-delete.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. **Research** — Read relevant files, search the codebase, delegate to @Memory subagent for conventions, decisions, and prior plans
|
||||
2. **Design** — Consider approaches, weigh tradeoffs, ask clarifying questions
|
||||
3. **Plan** — Present a clear, detailed plan to the user for review
|
||||
4. **Execute** — Use the question tool to ask for user approval of the plan. Present the user with clear options (e.g., "Approve" or "Deny"). Do NOT call memory-plan-execute until the user explicitly approves. Once approved, call memory-plan-execute with the full plan (it saves planning state automatically)
|
||||
4. **Approve** — After presenting the plan, you MUST call the question tool (mcp_question) to get explicit approval. Do NOT ask for approval via plain text — always use the question tool with options like "Approve plan" and "Reject plan". Only proceed to call memory-plan-execute after the user selects approval via the question tool
|
||||
|
||||
## Plan Format
|
||||
|
||||
@@ -86,10 +85,5 @@ Present plans with:
|
||||
When the user approves the plan, call memory-plan-execute with:
|
||||
|
||||
- **plan**: The full implementation plan — must be **fully self-contained** since the Code agent has no access to this conversation. Include every file path, implementation details, code patterns to match, phase dependencies, verification steps, and gotchas. Do NOT summarize or abbreviate.
|
||||
- **title**: Short descriptive label for the session list.
|
||||
- **objective**: Short description of what we're building.
|
||||
- **phases**: Each phase from the plan with status "pending".
|
||||
- **findings**: Key architectural decisions discovered during research.
|
||||
|
||||
Planning state is saved automatically before the plan is dispatched to the Code agent.`,
|
||||
- **title**: Short descriptive label for the session list.`,
|
||||
}
|
||||
@@ -35,9 +35,6 @@ Diffs alone are not enough. After getting the diff:
|
||||
- Check project memory for relevant conventions and decisions:
|
||||
- Use memory-read with scope "convention" to find coding standards for the changed files
|
||||
- Use memory-read with scope "decision" to find architectural decisions that may apply
|
||||
- Check planning state for context:
|
||||
- Use memory-planning-get to understand what the current session is working on
|
||||
- Use memory-planning-search to find prior plans related to the changed code areas
|
||||
|
||||
## What to Look For
|
||||
|
||||
@@ -77,9 +74,6 @@ Don't be a zealot about style:
|
||||
|
||||
- Use the Task tool with explore agents to find how existing code handles similar problems
|
||||
- Use memory-read to check stored conventions and decisions before claiming something doesn't fit
|
||||
- Use memory-planning-get to understand session context
|
||||
- Use memory-planning-search to find prior plans for intent behind the changes
|
||||
- Use memory-planning-update to record review findings in planning state
|
||||
- Call multiple tools in a single response when independent
|
||||
- Use specialized tools (Read, Glob, Grep) instead of bash equivalents (cat, find, grep)
|
||||
|
||||
@@ -107,5 +101,15 @@ If no issues are found, say so clearly and briefly.
|
||||
|
||||
## Constraints
|
||||
|
||||
You are read-only on source code. Do not edit files, run destructive commands, or make any changes. Only read, search, analyze, and report findings.`,
|
||||
You are read-only on source code. Do not edit files, run destructive commands, or make any changes. Only read, search, analyze, and report findings.
|
||||
|
||||
## Injected Memory
|
||||
|
||||
Your messages may include \`<project-memory>\` blocks containing memories automatically retrieved based on semantic similarity to the current message. Each entry has the format \`#<id> [<scope>] <content>\`.
|
||||
|
||||
- **[convention]**: Rules to check code against
|
||||
- **[decision]**: Architectural constraints that may apply
|
||||
- **[context]**: Reference information
|
||||
|
||||
These memories may be stale or irrelevant. If a memory seems outdated, note it in your review observations. You do not have write access to memory — flag stale memories for the calling agent to handle.`,
|
||||
}
|
||||
@@ -9,9 +9,10 @@ export const codeAgent: AgentDefinition = {
|
||||
color: '#3b82f6',
|
||||
permission: {
|
||||
question: 'allow',
|
||||
plan_enter: 'allow',
|
||||
},
|
||||
tools: {
|
||||
exclude: ['memory-plan-execute', 'memory-planning-update', 'memory-planning-search'],
|
||||
exclude: ['memory-plan-execute'],
|
||||
},
|
||||
systemPrompt: `You are a coding agent that helps users with software engineering tasks. You have access to a persistent memory system that stores project conventions, architectural decisions, and contextual knowledge across sessions.
|
||||
|
||||
@@ -37,6 +38,7 @@ Mark todos as completed as soon as each task is done — do not batch completion
|
||||
# Tool usage policy
|
||||
- When doing file search or exploring the codebase, prefer the Task tool to reduce context usage.
|
||||
- Proactively use the Task tool with specialized agents when the task matches the agent's description.
|
||||
- If a task matches an available skill, use the Skill tool to load domain-specific instructions. Skill outputs persist through compaction.
|
||||
- Call multiple tools in a single response when they are independent. Batch parallel tool calls for performance.
|
||||
- Use specialized tools (Read, Glob, Grep, Edit, Write) instead of bash equivalents (cat, find, grep, sed, echo).
|
||||
- NEVER use bash echo or other CLI tools to communicate with the user. Output text directly.
|
||||
@@ -46,7 +48,7 @@ When referencing code, use the pattern \`file_path:line_number\` for easy naviga
|
||||
|
||||
## Memory Integration
|
||||
|
||||
You have memory tools (memory-read, memory-write, memory-edit, memory-delete) and the @Memory subagent (via Task tool) for complex operations — multi-query research, contradiction resolution, bulk curation, planning state updates, and cross-session planning searches. Delegate to @Memory when you need broad context or when the result set could be large, to keep your context clean.
|
||||
You have memory tools (memory-read, memory-write, memory-edit, memory-delete) and the @Memory subagent (via Task tool) for complex operations — multi-query research, contradiction resolution, and bulk curation. Delegate to @Memory when you need broad context or when the result set could be large, to keep your context clean.
|
||||
|
||||
**Check memory** before modifying unfamiliar code areas, making architectural decisions, or when the user references past decisions. Skip memory for trivial tasks or when the user provides all necessary context.
|
||||
|
||||
@@ -60,13 +62,14 @@ You have memory tools (memory-read, memory-write, memory-edit, memory-delete) an
|
||||
- Update stale memories with memory-edit rather than creating duplicates
|
||||
- Reference file paths when storing structural context
|
||||
|
||||
## Planning State
|
||||
## Injected Memory
|
||||
|
||||
You can read the current session's planning state directly with memory-planning-get. For all other planning operations, delegate to the @Memory subagent via the Task tool:
|
||||
Your messages may include \`<project-memory>\` blocks containing memories automatically retrieved based on semantic similarity to the current message. Each entry has the format \`#<id> [<scope>] <content>\`.
|
||||
|
||||
- **memory-planning-get** (direct): Retrieve planning state for the current session — use when resuming work or when the user asks about progress.
|
||||
- **Updating planning state**: Delegate to @Memory — tell it to call memory-planning-update with phase statuses, current activity, findings, and errors.
|
||||
- **Searching prior plans**: Delegate to @Memory — tell it to call memory-planning-search to find related work across sessions.
|
||||
- **[convention]**: Rules to follow — coding style, naming patterns, workflow preferences
|
||||
- **[decision]**: Architectural choices with rationale — treat as constraints
|
||||
- **[context]**: Reference information — file locations, domain knowledge, known issues
|
||||
|
||||
When executing a plan from the Architect agent, delegate to @Memory to update planning state as you complete each phase so progress is visible across sessions.`,
|
||||
These memories may be stale or irrelevant to the current task. Use your judgement. If a memory seems outdated or incorrect, flag it to the user and use memory-edit or memory-delete to correct it.
|
||||
`,
|
||||
}
|
||||
@@ -4,7 +4,7 @@ export const memoryAgent: AgentDefinition = {
|
||||
role: 'memory',
|
||||
id: 'ocm-memory',
|
||||
displayName: 'Memory',
|
||||
description: 'Expert agent for managing project memory and planning state - storing and retrieving conventions, decisions, context, and session progress',
|
||||
description: 'Expert agent for managing project memory - storing and retrieving conventions, decisions, context, and session progress',
|
||||
mode: 'subagent',
|
||||
tools: {
|
||||
exclude: ['memory-plan-execute'],
|
||||
@@ -171,7 +171,6 @@ You are invoked when:
|
||||
- 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
|
||||
- An agent needs to update planning state or search plans across sessions (only you have memory-planning-update and memory-planning-search)
|
||||
- The Architect agent needs broad memory research before designing a plan (multi-query sweep of conventions, decisions, and prior plans)
|
||||
|
||||
You are NOT needed for:
|
||||
@@ -190,43 +189,19 @@ You are NOT needed for:
|
||||
- content: The memory content
|
||||
- scope: convention | decision | context
|
||||
|
||||
3. **memory-delete**: Remove memories by ID
|
||||
3. **memory-edit**: Edit an existing memory
|
||||
- id: The memory ID to edit
|
||||
- content: Updated memory content
|
||||
- scope: Optionally change the scope
|
||||
|
||||
4. **memory-delete**: Remove memories by ID
|
||||
- id: The memory ID to delete
|
||||
|
||||
4. **memory-planning-update**: Update session planning state
|
||||
- sessionID: Session to update (optional, defaults to current session)
|
||||
- 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.
|
||||
## Injected Memory
|
||||
|
||||
5. **memory-planning-get**: Get planning state for a session
|
||||
- sessionID: Session to retrieve (optional, defaults to current session)
|
||||
Your messages may include \`<project-memory>\` blocks containing memories automatically retrieved based on semantic similarity to the current message. Each entry has the format \`#<id> [<scope>] <content>\`.
|
||||
|
||||
6. **memory-planning-search**: Search planning states across all sessions in the project
|
||||
- query: Optional search keyword to filter planning states. Omit to list all.
|
||||
|
||||
## 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
|
||||
Use these as a starting point for your research — they indicate what the system found relevant. Cross-reference with memory-read for completeness. If any injected memory is stale or contradicts newer information, update or delete it.
|
||||
|
||||
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.`,
|
||||
}
|
||||
@@ -16,7 +16,7 @@ export interface AgentDefinition {
|
||||
}
|
||||
variant?: string
|
||||
temperature?: number
|
||||
maxSteps?: number
|
||||
steps?: number
|
||||
permission?: Record<string, unknown>
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ export interface AgentConfig {
|
||||
tools?: Record<string, boolean>
|
||||
variant?: string
|
||||
temperature?: number
|
||||
maxSteps?: number
|
||||
steps?: number
|
||||
hidden?: boolean
|
||||
color?: string
|
||||
permission?: Record<string, unknown>
|
||||
|
||||
+2
-2
@@ -9,8 +9,8 @@ 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)
|
||||
constructor(cleanupIntervalMs: number = 60000) {
|
||||
this.cleanupInterval = setInterval(() => this.cleanup(), cleanupIntervalMs)
|
||||
}
|
||||
|
||||
private cleanup(): void {
|
||||
|
||||
@@ -4,7 +4,6 @@ interface CleanupOptions {
|
||||
olderThan?: number
|
||||
ids?: number[]
|
||||
scope?: MemoryScope
|
||||
sessions?: boolean
|
||||
all?: boolean
|
||||
dryRun?: boolean
|
||||
force?: boolean
|
||||
@@ -40,8 +39,6 @@ function parseArgs(args: string[]): CleanupOptions {
|
||||
process.exit(1)
|
||||
}
|
||||
options.scope = scope
|
||||
} else if (arg === '--sessions') {
|
||||
options.sessions = true
|
||||
} else if (arg === '--all') {
|
||||
options.all = true
|
||||
} else if (arg === '--dry-run') {
|
||||
@@ -78,7 +75,6 @@ Options:
|
||||
--older-than <days> Delete memories older than N days
|
||||
--ids <id,id,...> Delete specific memory IDs
|
||||
--scope <scope> Filter by scope (convention, decision, context)
|
||||
--sessions Clean up session states instead of memories
|
||||
--all Delete all memories for the project (requires --project)
|
||||
--dry-run Preview what would be deleted without deleting
|
||||
--force Skip confirmation prompt
|
||||
@@ -97,8 +93,8 @@ export function run(args: string[], globalOpts: { dbPath?: string; projectId?: s
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
if (!options.olderThan && !options.ids && !options.sessions && !options.all) {
|
||||
console.error('At least one filter must be provided: --older-than, --ids, --sessions, or --all')
|
||||
if (!options.olderThan && !options.ids && !options.all) {
|
||||
console.error('At least one filter must be provided: --older-than, --ids, or --all')
|
||||
help()
|
||||
process.exit(1)
|
||||
}
|
||||
@@ -116,11 +112,7 @@ export function run(args: string[], globalOpts: { dbPath?: string; projectId?: s
|
||||
const db = openDatabase(options.dbPath || globalOpts.dbPath)
|
||||
|
||||
try {
|
||||
if (options.sessions) {
|
||||
runSessionCleanup(db, options)
|
||||
} else {
|
||||
runMemoryCleanup(db, options)
|
||||
}
|
||||
runMemoryCleanup(db, options)
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
@@ -206,72 +198,3 @@ async function runMemoryCleanup(db: ReturnType<typeof openDatabase>, options: Cl
|
||||
console.log(`Deleted ${rows.length} memories. ${remainingCount.count} remaining.`)
|
||||
console.log("Note: Run 'memory-health reindex' in OpenCode to clean up orphaned embeddings.")
|
||||
}
|
||||
|
||||
async function runSessionCleanup(db: ReturnType<typeof openDatabase>, options: CleanupOptions): Promise<void> {
|
||||
const projectId = options.projectId!
|
||||
const nameMap = resolveProjectNames()
|
||||
let query = 'SELECT key, project_id, expires_at, created_at, updated_at FROM session_state WHERE project_id = ?'
|
||||
const params: (string | number)[] = [projectId]
|
||||
|
||||
if (options.olderThan) {
|
||||
const cutoffTime = Date.now() - options.olderThan * 24 * 60 * 60 * 1000
|
||||
query += ' AND created_at < ?'
|
||||
params.push(cutoffTime)
|
||||
}
|
||||
|
||||
if (options.all) {
|
||||
query = 'SELECT key, project_id, expires_at, created_at, updated_at FROM session_state WHERE project_id = ?'
|
||||
params.length = 0
|
||||
params.push(projectId)
|
||||
}
|
||||
|
||||
const rows = db.prepare(query).all(...params) as Array<{
|
||||
key: string
|
||||
project_id: string
|
||||
expires_at: number | null
|
||||
created_at: number
|
||||
updated_at: number
|
||||
}>
|
||||
|
||||
if (rows.length === 0) {
|
||||
console.log('No session states found to delete.')
|
||||
return
|
||||
}
|
||||
|
||||
console.log('')
|
||||
console.log(`Found ${rows.length} session states to delete:`)
|
||||
console.log(' KEY PROJECT CREATED EXPIRED')
|
||||
|
||||
const displayRows = rows.slice(0, 20)
|
||||
for (const row of displayRows) {
|
||||
const key = truncate(row.key, 38).padEnd(40)
|
||||
const project = displayProjectId(row.project_id, nameMap).padEnd(14)
|
||||
const created = formatDate(row.created_at)
|
||||
const expired = row.expires_at ? formatDate(row.expires_at) : '-'
|
||||
console.log(` ${key} ${project} ${created} ${expired}`)
|
||||
}
|
||||
|
||||
if (rows.length > 20) {
|
||||
console.log(` ... and ${rows.length - 20} more`)
|
||||
}
|
||||
|
||||
console.log('')
|
||||
|
||||
if (options.dryRun) {
|
||||
console.log('Dry run - no session states deleted.')
|
||||
return
|
||||
}
|
||||
|
||||
const shouldProceed = options.force || (await confirm(`Delete ${rows.length} session states`))
|
||||
|
||||
if (!shouldProceed) {
|
||||
console.log('Cancelled.')
|
||||
return
|
||||
}
|
||||
|
||||
const keysToDelete = rows.map((r) => r.key)
|
||||
const deleteQuery = `DELETE FROM session_state WHERE key IN (${keysToDelete.map(() => '?').join(',')})`
|
||||
db.prepare(deleteQuery).run(...keysToDelete)
|
||||
|
||||
console.log(`Deleted ${rows.length} session states.`)
|
||||
}
|
||||
@@ -7,13 +7,6 @@ interface ProjectMemoryStats {
|
||||
newest: number
|
||||
}
|
||||
|
||||
interface ProjectSessionStats {
|
||||
project_id: string
|
||||
count: number
|
||||
oldest: number
|
||||
newest: number
|
||||
}
|
||||
|
||||
function parseArgs(args: string[]): { dbPath?: string; help?: boolean } {
|
||||
const options: { dbPath?: string; help?: boolean } = {}
|
||||
let i = 0
|
||||
@@ -39,7 +32,7 @@ function parseArgs(args: string[]): { dbPath?: string; help?: boolean } {
|
||||
|
||||
export function help(): void {
|
||||
console.log(`
|
||||
List projects with memory and session state counts
|
||||
List projects with memory counts
|
||||
|
||||
Usage:
|
||||
ocm-mem list [options]
|
||||
@@ -69,12 +62,6 @@ export function run(args: string[], globalOpts: { dbPath?: string; projectId?: s
|
||||
FROM memories GROUP BY project_id ORDER BY count DESC
|
||||
`).all() as ProjectMemoryStats[]
|
||||
|
||||
const sessionRows = db.prepare(`
|
||||
SELECT project_id, COUNT(*) as count,
|
||||
MIN(created_at) as oldest, MAX(updated_at) as newest
|
||||
FROM session_state GROUP BY project_id ORDER BY count DESC
|
||||
`).all() as ProjectSessionStats[]
|
||||
|
||||
console.log('')
|
||||
|
||||
if (memoryRows.length > 0) {
|
||||
@@ -93,23 +80,6 @@ export function run(args: string[], globalOpts: { dbPath?: string; projectId?: s
|
||||
}
|
||||
|
||||
console.log('')
|
||||
|
||||
if (sessionRows.length > 0) {
|
||||
console.log('Session states:')
|
||||
console.log(' PROJECT SESSIONS OLDEST NEWEST')
|
||||
|
||||
for (const row of sessionRows) {
|
||||
const name = displayProjectId(row.project_id, nameMap).padEnd(19)
|
||||
const count = String(row.count).padEnd(9)
|
||||
const oldest = formatDate(row.oldest)
|
||||
const newest = formatDate(row.newest)
|
||||
console.log(` ${name} ${count} ${oldest} ${newest}`)
|
||||
}
|
||||
} else {
|
||||
console.log('No session states found.')
|
||||
}
|
||||
|
||||
console.log('')
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
|
||||
@@ -10,12 +10,6 @@ interface ProjectStats {
|
||||
newest: number
|
||||
}
|
||||
|
||||
interface SessionStats {
|
||||
planning: number
|
||||
compaction: number
|
||||
expired: number
|
||||
}
|
||||
|
||||
function parseArgs(args: string[]): { projectId?: string; dbPath?: string; help?: boolean } {
|
||||
const options: { projectId?: string; dbPath?: string; help?: boolean } = {}
|
||||
let i = 0
|
||||
@@ -86,14 +80,6 @@ export function run(args: string[], globalOpts: { dbPath?: string; projectId?: s
|
||||
FROM memories WHERE project_id = ?
|
||||
`).get(finalProjectId) as ProjectStats | undefined
|
||||
|
||||
const sessionRows = db.prepare(`
|
||||
SELECT
|
||||
SUM(CASE WHEN key LIKE 'session:%' THEN 1 ELSE 0 END) as planning,
|
||||
SUM(CASE WHEN key LIKE 'compaction:%' THEN 1 ELSE 0 END) as compaction,
|
||||
SUM(CASE WHEN expires_at IS NOT NULL AND expires_at < ? THEN 1 ELSE 0 END) as expired
|
||||
FROM session_state WHERE project_id = ?
|
||||
`).get(Date.now(), finalProjectId) as SessionStats | undefined
|
||||
|
||||
const totalMemories = scopeRows.reduce((sum, row) => sum + row.count, 0)
|
||||
|
||||
console.log('')
|
||||
@@ -118,17 +104,6 @@ export function run(args: string[], globalOpts: { dbPath?: string; projectId?: s
|
||||
console.log(` Newest: ${formatDate(statsRow.newest)}`)
|
||||
}
|
||||
|
||||
console.log('')
|
||||
console.log('Session State:')
|
||||
|
||||
if (sessionRows) {
|
||||
console.log(` Planning states: ${sessionRows.planning || 0}`)
|
||||
console.log(` Compaction snapshots: ${sessionRows.compaction || 0}`)
|
||||
console.log(` Expired (pending cleanup): ${sessionRows.expired || 0}`)
|
||||
} else {
|
||||
console.log(' None')
|
||||
}
|
||||
|
||||
console.log('')
|
||||
} finally {
|
||||
db.close()
|
||||
|
||||
@@ -26,15 +26,6 @@ export interface GlobalOptions {
|
||||
help?: boolean
|
||||
}
|
||||
|
||||
export interface SessionState {
|
||||
key: string
|
||||
projectId: string
|
||||
data: string
|
||||
expiresAt: number | null
|
||||
createdAt: number
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
export function resolveDefaultDbPath(): string {
|
||||
const localPath = join(process.cwd(), '.opencode', 'state', 'opencode', 'memory', 'memory.db')
|
||||
if (existsSync(localPath)) {
|
||||
|
||||
@@ -6,9 +6,6 @@ const ENHANCED_BUILTIN_AGENTS: Record<string, { tools: Record<string, boolean> }
|
||||
plan: {
|
||||
tools: {
|
||||
'memory-read': true,
|
||||
'memory-planning-update': true,
|
||||
'memory-planning-get': true,
|
||||
'memory-planning-search': true,
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -87,7 +84,7 @@ function createAgentConfigs(agents: Record<AgentRole, AgentDefinition>): Record<
|
||||
...(Object.keys(tools).length > 0 ? { tools } : {}),
|
||||
...(agent.variant ? { variant: agent.variant } : {}),
|
||||
...(agent.temperature !== undefined ? { temperature: agent.temperature } : {}),
|
||||
...(agent.maxSteps !== undefined ? { maxSteps: agent.maxSteps } : {}),
|
||||
...(agent.steps !== undefined ? { steps: agent.steps } : {}),
|
||||
...(agent.hidden ? { hidden: agent.hidden } : {}),
|
||||
...(agent.color ? { color: agent.color } : {}),
|
||||
...(agent.permission ? { permission: agent.permission } : {}),
|
||||
|
||||
@@ -111,7 +111,7 @@ export async function acquireEmbeddingServer(config: SharedEmbeddingConfig): Pro
|
||||
|
||||
const lockAcquired = await acquireLock(lockPath)
|
||||
if (!lockAcquired) {
|
||||
for (let i = 0; i < 10; i++) {
|
||||
for (let i = 0; i < 30; i++) {
|
||||
await sleep(500)
|
||||
const health = await checkServerHealth(socketPath)
|
||||
if (health !== null) {
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import type { PlanningState } from '../types'
|
||||
|
||||
interface PromptResponsePart {
|
||||
type: string
|
||||
text?: string
|
||||
@@ -17,20 +15,16 @@ 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)
|
||||
2. ALL file paths being actively worked on (with what's being done)
|
||||
3. Key decisions made and their rationale
|
||||
4. Any corrections or gotchas discovered during the session
|
||||
5. 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]
|
||||
|
||||
@@ -46,61 +40,13 @@ Preserve everything needed for seamless continuation.
|
||||
- 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' : ''}`)
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
export { createSessionHooks, type SessionHooks } from './session'
|
||||
export {
|
||||
buildCustomCompactionPrompt,
|
||||
formatPlanningState,
|
||||
formatCompactionDiagnostics,
|
||||
estimateTokens,
|
||||
trimToTokenBudget,
|
||||
extractCompactionSummary,
|
||||
} from './compaction-utils'
|
||||
export { createMemoryInjectionHook, type MemoryInjectionHook } from './memory-injection'
|
||||
@@ -0,0 +1,151 @@
|
||||
import type { MemoryService } from '../services/memory'
|
||||
import type { MemoryInjectionConfig, Logger, MemorySearchResult } from '../types'
|
||||
import { InMemoryCacheService } from '../cache/memory-cache'
|
||||
import { estimateTokens } from './compaction-utils'
|
||||
|
||||
async function sha256(message: string): Promise<string> {
|
||||
const msgBuffer = new TextEncoder().encode(message)
|
||||
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer)
|
||||
const hashArray = Array.from(new Uint8Array(hashBuffer))
|
||||
return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('')
|
||||
}
|
||||
|
||||
interface MemoryInjectionDeps {
|
||||
projectId: string
|
||||
memoryService: MemoryService
|
||||
logger: Logger
|
||||
config?: MemoryInjectionConfig
|
||||
}
|
||||
|
||||
export interface MemoryInjectionHook {
|
||||
handler: (userText: string) => Promise<string | null>
|
||||
destroy: () => void
|
||||
}
|
||||
|
||||
export function createMemoryInjectionHook(deps: MemoryInjectionDeps): MemoryInjectionHook {
|
||||
const { projectId, memoryService, logger, config } = deps
|
||||
|
||||
const enabled = config?.enabled ?? true
|
||||
const debug = config?.debug ?? false
|
||||
const maxResults = config?.maxResults ?? 5
|
||||
const distanceThreshold = config?.distanceThreshold ?? 0.5
|
||||
const maxTokens = config?.maxTokens ?? 2000
|
||||
const cacheTtlMs = config?.cacheTtlMs ?? 30000
|
||||
|
||||
const cache = new InMemoryCacheService()
|
||||
|
||||
let initialized = false
|
||||
|
||||
const handler = async (userText: string): Promise<string | null> => {
|
||||
if (!enabled) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (!initialized) {
|
||||
logger.log(`memory-injection: initialized (enabled=${enabled}, maxResults=${maxResults}, distanceThreshold=${distanceThreshold}, maxTokens=${maxTokens}, cacheTtlMs=${cacheTtlMs})`)
|
||||
initialized = true
|
||||
}
|
||||
|
||||
if (debug) {
|
||||
logger.debug('memory-injection: hook invoked', { projectId, userTextLength: userText.length })
|
||||
}
|
||||
|
||||
try {
|
||||
const hash = await sha256(userText)
|
||||
const cacheKey = `memory-injection:${hash}`
|
||||
|
||||
const cached = await cache.get<string>(cacheKey)
|
||||
if (cached !== null) {
|
||||
if (debug) {
|
||||
logger.debug('memory-injection: cache hit', { projectId, hash })
|
||||
}
|
||||
return cached === '' ? null : cached
|
||||
}
|
||||
|
||||
if (debug) {
|
||||
logger.debug('memory-injection: cache miss', { projectId, hash })
|
||||
}
|
||||
|
||||
const searchResults = await memoryService.search(userText, projectId, { limit: maxResults })
|
||||
|
||||
logger.log(`memory-injection: search returned ${searchResults.length} results for project ${projectId}`)
|
||||
|
||||
if (debug && searchResults.length > 0) {
|
||||
const distances = searchResults.map((r: MemorySearchResult) => `#${r.memory.id}(${r.memory.scope}):${r.distance.toFixed(3)}`)
|
||||
logger.debug('memory-injection: result distances', { distances, distanceThreshold })
|
||||
}
|
||||
|
||||
const filteredResults = searchResults.filter((result: MemorySearchResult) => result.distance <= distanceThreshold)
|
||||
|
||||
if (searchResults.length > 0 && filteredResults.length === 0) {
|
||||
const closest = Math.min(...searchResults.map((r: MemorySearchResult) => r.distance))
|
||||
logger.log(`memory-injection: all ${searchResults.length} results filtered out (closest distance: ${closest.toFixed(3)}, threshold: ${distanceThreshold})`)
|
||||
}
|
||||
|
||||
if (searchResults.length === 0) {
|
||||
logger.log('memory-injection: search returned 0 results (vec may be unavailable)')
|
||||
}
|
||||
|
||||
if (filteredResults.length === 0) {
|
||||
await cache.set(cacheKey, '', cacheTtlMs / 1000)
|
||||
if (debug) {
|
||||
logger.debug('memory-injection: no matching memories found', { projectId })
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const sections: string[] = []
|
||||
sections.push('<project-memory>')
|
||||
|
||||
for (const result of filteredResults) {
|
||||
const { memory } = result
|
||||
sections.push(`- #${memory.id} [${memory.scope}] ${memory.content}`)
|
||||
}
|
||||
|
||||
sections.push('</project-memory>')
|
||||
|
||||
let formatted = sections.join('\n')
|
||||
let tokens = estimateTokens(formatted)
|
||||
|
||||
if (tokens > maxTokens) {
|
||||
const trimmedSections: string[] = []
|
||||
trimmedSections.push('<project-memory>')
|
||||
|
||||
let currentTokens = estimateTokens('<project-memory>')
|
||||
for (const result of filteredResults) {
|
||||
const line = `- #${result.memory.id} [${result.memory.scope}] ${result.memory.content}`
|
||||
const lineTokens = estimateTokens(line)
|
||||
|
||||
if (currentTokens + lineTokens > maxTokens - estimateTokens('</project-memory>')) {
|
||||
break
|
||||
}
|
||||
|
||||
trimmedSections.push(line)
|
||||
currentTokens += lineTokens
|
||||
}
|
||||
|
||||
trimmedSections.push('</project-memory>')
|
||||
formatted = trimmedSections.join('\n')
|
||||
tokens = estimateTokens(formatted)
|
||||
|
||||
if (debug) {
|
||||
logger.debug('memory-injection: trimmed to token limit', { tokens })
|
||||
}
|
||||
}
|
||||
|
||||
await cache.set(cacheKey, formatted, cacheTtlMs / 1000)
|
||||
|
||||
logger.log(`memory-injection: injected ${filteredResults.length} relevant memories (${tokens} tokens) for query`)
|
||||
|
||||
return formatted
|
||||
} catch (error) {
|
||||
logger.error('memory-injection: failed to inject memories', error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
handler,
|
||||
destroy: () => cache.destroy(),
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,8 @@
|
||||
import type { Logger, PlanningState, PreCompactionSnapshot, CompactionConfig } from '../types'
|
||||
import type { Logger, 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,
|
||||
@@ -33,7 +31,6 @@ interface EventInput {
|
||||
|
||||
interface CompactingInput {
|
||||
sessionID: string
|
||||
branch?: string
|
||||
}
|
||||
|
||||
interface CompactingOutput {
|
||||
@@ -53,17 +50,11 @@ function formatEventProperties(props?: Record<string, unknown>): string {
|
||||
}
|
||||
|
||||
function buildSubtaskPrompt(
|
||||
sessionId: string,
|
||||
compactionSummary: string,
|
||||
planningState: PlanningState | null
|
||||
): string {
|
||||
const planningSection = planningState
|
||||
? `## Current Planning State\n\n${formatPlanningState(planningState) ?? '(no details)'}\n\n---\n`
|
||||
: ''
|
||||
|
||||
return `Review the following and extract any project knowledge worth preserving across sessions.
|
||||
|
||||
${planningSection}## Compaction Summary
|
||||
## Compaction Summary
|
||||
|
||||
${compactionSummary}
|
||||
|
||||
@@ -74,26 +65,21 @@ For each item found, store it with the appropriate scope:
|
||||
- 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). If found, use memory-planning-update with sessionID "${sessionId}" to store it.
|
||||
|
||||
Be selective — only store knowledge useful in future sessions. Check for duplicates before writing (use memory-read to search first).
|
||||
|
||||
End your response with:
|
||||
1. A brief summary of what was stored
|
||||
2. Whether there was active work in progress (in-progress todos, pending tasks, or incomplete planning phases). If so, tell the main agent to review the planning state and todo list and continue where it left off.`
|
||||
2. Whether there was active work in progress (in-progress todos or pending tasks). If so, tell the main agent to review the todo list and continue where it left off.`
|
||||
}
|
||||
|
||||
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
|
||||
@@ -119,11 +105,6 @@ export function createSessionHooks(
|
||||
|
||||
logger.log(`Post-compaction: fetched compaction summary (${compactionSummary.length} chars)`)
|
||||
|
||||
const planningState = sessionStateService.getPlanningState(sessionId, projectId)
|
||||
if (planningState) {
|
||||
logger.log(`Post-compaction: fetched planning state for session ${sessionId}`)
|
||||
}
|
||||
|
||||
await ctx.client.session.prompt({
|
||||
path: { id: sessionId },
|
||||
body: {
|
||||
@@ -132,7 +113,7 @@ export function createSessionHooks(
|
||||
type: 'subtask',
|
||||
agent: 'Memory',
|
||||
description: 'Memory extraction after compaction',
|
||||
prompt: buildSubtaskPrompt(sessionId, compactionSummary, planningState),
|
||||
prompt: buildSubtaskPrompt(compactionSummary),
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -172,45 +153,11 @@ export function createSessionHooks(
|
||||
})
|
||||
},
|
||||
async onCompacting(input: CompactingInput, output: CompactingOutput) {
|
||||
const { sessionID: sessionId, branch } = input
|
||||
const { sessionID: sessionId } = 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, projectId)
|
||||
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, projectId)
|
||||
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 }),
|
||||
@@ -234,7 +181,7 @@ export function createSessionHooks(
|
||||
const maxTokens = compactionConfig.maxContextTokens ?? 4000
|
||||
|
||||
let trimmedSections = [...sections]
|
||||
let currentTokens = totalTokens
|
||||
let currentTokens = 0
|
||||
|
||||
for (let i = trimmedSections.length - 1; i >= 0; i--) {
|
||||
const sectionTokens = estimateTokens(trimmedSections[i]!)
|
||||
@@ -257,23 +204,7 @@ export function createSessionHooks(
|
||||
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')),
|
||||
|
||||
+116
-215
@@ -3,27 +3,28 @@ import { tool } from '@opencode-ai/plugin'
|
||||
import { agents } from './agents'
|
||||
import { createConfigHandler } from './config'
|
||||
import { VERSION } from './version'
|
||||
import { createSessionHooks } from './hooks'
|
||||
import { createSessionHooks, createMemoryInjectionHook } from './hooks'
|
||||
import { join } from 'path'
|
||||
import { initializeDatabase, resolveDataDir, closeDatabase, createMetadataQuery, getTableDimensions, recreateVecTable } from './storage'
|
||||
import { initializeDatabase, resolveDataDir, closeDatabase, createMetadataQuery } from './storage'
|
||||
import type { MemoryService } from './services/memory'
|
||||
import { createVecService } from './storage/vec'
|
||||
import { createEmbeddingProvider, checkServerHealth, isServerRunning, killEmbeddingServer } 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 { Database } from 'bun:sqlite'
|
||||
import type { PluginConfig, CompactionConfig, HealthStatus, Logger, PlanningState } from './types'
|
||||
import type { PluginConfig, CompactionConfig, HealthStatus, Logger } from './types'
|
||||
import type { EmbeddingProvider } from './embedding'
|
||||
import type { VecService } from './storage/vec-types'
|
||||
import { createNoopVecService } from './storage/vec'
|
||||
|
||||
|
||||
const z = tool.schema
|
||||
|
||||
async function getHealthStatus(
|
||||
projectId: string,
|
||||
db: Database,
|
||||
config: PluginConfig,
|
||||
provider: EmbeddingProvider,
|
||||
@@ -35,7 +36,7 @@ async function getHealthStatus(
|
||||
let memoryCount = 0
|
||||
try {
|
||||
db.prepare('SELECT 1').get()
|
||||
const row = db.prepare("SELECT COUNT(*) as count FROM memories").get() as { count: number }
|
||||
const row = db.prepare("SELECT COUNT(*) as count FROM memories WHERE project_id = ?").get(projectId) as { count: number }
|
||||
memoryCount = row.count
|
||||
} catch {
|
||||
dbStatus = 'error'
|
||||
@@ -138,12 +139,13 @@ function formatHealthStatus(status: HealthStatus, provider: EmbeddingProvider):
|
||||
}
|
||||
|
||||
async function executeHealthCheck(
|
||||
projectId: string,
|
||||
db: Database,
|
||||
config: PluginConfig,
|
||||
provider: EmbeddingProvider,
|
||||
dataDir: string,
|
||||
): Promise<string> {
|
||||
const status = await getHealthStatus(db, config, provider, dataDir)
|
||||
const status = await getHealthStatus(projectId, db, config, provider, dataDir)
|
||||
return formatHealthStatus(status, provider)
|
||||
}
|
||||
|
||||
@@ -154,12 +156,13 @@ interface DimensionMismatchState {
|
||||
}
|
||||
|
||||
async function executeReindex(
|
||||
projectId: string,
|
||||
memoryService: MemoryService,
|
||||
db: Database,
|
||||
config: PluginConfig,
|
||||
provider: EmbeddingProvider,
|
||||
dataDir: string,
|
||||
mismatchState: DimensionMismatchState,
|
||||
vec: VecService,
|
||||
): Promise<string> {
|
||||
const configuredModel = config.embedding.model
|
||||
const configuredDimensions = config.embedding.dimensions ?? provider.dimensions
|
||||
@@ -175,14 +178,12 @@ async function executeReindex(
|
||||
return 'Reindex failed: embedding provider is not operational. Check your API key and model configuration.'
|
||||
}
|
||||
|
||||
const tableResult = getTableDimensions(db)
|
||||
if (tableResult.exists && tableResult.dimensions !== configuredDimensions) {
|
||||
recreateVecTable(db, configuredDimensions)
|
||||
const newVec = await createVecService(db, dataDir, configuredDimensions)
|
||||
memoryService.setVecService(newVec)
|
||||
const tableInfo = await vec.getDimensions()
|
||||
if (tableInfo.exists && tableInfo.dimensions !== null && tableInfo.dimensions !== configuredDimensions) {
|
||||
await vec.recreateTable(configuredDimensions)
|
||||
}
|
||||
|
||||
const result = await memoryService.reindex()
|
||||
const result = await memoryService.reindex(projectId)
|
||||
|
||||
if (result.success > 0 || result.total === 0) {
|
||||
const metadata = createMetadataQuery(db)
|
||||
@@ -213,14 +214,17 @@ async function executeReindex(
|
||||
}
|
||||
|
||||
async function autoValidateOnLoad(
|
||||
projectId: string,
|
||||
memoryService: MemoryService,
|
||||
db: Database,
|
||||
config: PluginConfig,
|
||||
provider: EmbeddingProvider,
|
||||
dataDir: string,
|
||||
mismatchState: DimensionMismatchState,
|
||||
vec: VecService,
|
||||
logger: Logger,
|
||||
): Promise<void> {
|
||||
const status = await getHealthStatus(db, config, provider, dataDir)
|
||||
const status = await getHealthStatus(projectId, db, config, provider, dataDir)
|
||||
|
||||
if (status.overallStatus === 'error') {
|
||||
logger.log('Auto-validate: unhealthy (db error), skipping')
|
||||
@@ -238,16 +242,8 @@ async function autoValidateOnLoad(
|
||||
}
|
||||
|
||||
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})`)
|
||||
await executeReindex(projectId, memoryService, db, config, provider, mismatchState, vec)
|
||||
logger.log('Auto-validate: reindex complete')
|
||||
}
|
||||
|
||||
function parseModelString(modelStr?: string): { providerID: string; modelID: string } | undefined {
|
||||
@@ -269,6 +265,7 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
|
||||
const logger = createLogger({
|
||||
enabled: loggingConfig?.enabled ?? false,
|
||||
file: loggingConfig?.file ?? resolveLogPath(),
|
||||
debug: loggingConfig?.debug ?? false,
|
||||
})
|
||||
logger.log(`Initializing plugin for directory: ${directory}, projectId: ${projectId}`)
|
||||
|
||||
@@ -292,10 +289,6 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
|
||||
logger,
|
||||
})
|
||||
|
||||
const sessionStateService = createSessionStateService(db, logger)
|
||||
sessionStateService.startCleanupInterval()
|
||||
sessionStateService.deleteExpired()
|
||||
|
||||
if (config.dedupThreshold) {
|
||||
memoryService.setDedupThreshold(config.dedupThreshold)
|
||||
}
|
||||
@@ -306,8 +299,17 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
|
||||
actual: null,
|
||||
}
|
||||
|
||||
const initPromise = createVecService(db, dataDir, dimensions)
|
||||
const initState = {
|
||||
vecReady: false,
|
||||
syncRunning: false,
|
||||
syncComplete: false,
|
||||
}
|
||||
|
||||
let currentVec: VecService = noopVec
|
||||
|
||||
createVecService(db, dataDir, dimensions, logger)
|
||||
.then(async (vec) => {
|
||||
currentVec = vec
|
||||
memoryService.setVecService(vec)
|
||||
|
||||
if (!vec.available) {
|
||||
@@ -316,30 +318,46 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
|
||||
}
|
||||
|
||||
logger.log('Vec service initialized')
|
||||
initState.vecReady = true
|
||||
|
||||
const tableResult = getTableDimensions(db)
|
||||
if (tableResult.exists && tableResult.dimensions !== dimensions) {
|
||||
mismatchState.detected = true
|
||||
mismatchState.expected = dimensions
|
||||
mismatchState.actual = tableResult.dimensions
|
||||
memoryService.setVecService(createNoopVecService())
|
||||
logger.log(`Dimension mismatch detected: config=${dimensions}, table=${tableResult.dimensions ?? 'unknown'}`)
|
||||
return
|
||||
const tableInfo = await vec.getDimensions()
|
||||
if (tableInfo.exists && tableInfo.dimensions !== null && tableInfo.dimensions !== dimensions) {
|
||||
logger.log(`Dimension mismatch detected: config=${dimensions}, table=${tableInfo.dimensions}, auto-recreating`)
|
||||
await vec.recreateTable(dimensions)
|
||||
}
|
||||
|
||||
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)
|
||||
initState.syncRunning = true
|
||||
embeddingSync.start().then(
|
||||
() => {
|
||||
initState.syncRunning = false
|
||||
initState.syncComplete = true
|
||||
autoValidateOnLoad(projectId, memoryService, db, config, provider, dataDir, mismatchState, currentVec, logger)
|
||||
.catch((err: unknown) => {
|
||||
logger.error('Auto-validate failed', err)
|
||||
})
|
||||
},
|
||||
(err: unknown) => {
|
||||
initState.syncRunning = false
|
||||
logger.error('Embedding sync failed', err)
|
||||
}
|
||||
)
|
||||
})
|
||||
.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 memoryInjectionConfig = config.memoryInjection
|
||||
const messagesTransformConfig = config.messagesTransform
|
||||
const sessionHooks = createSessionHooks(projectId, memoryService, logger, input, compactionConfig)
|
||||
const memoryInjection = createMemoryInjectionHook({
|
||||
projectId,
|
||||
memoryService,
|
||||
logger,
|
||||
config: memoryInjectionConfig,
|
||||
})
|
||||
const injectedMessageIds = new Set<string>()
|
||||
|
||||
const scopeEnum = z.enum(['convention', 'decision', 'context'])
|
||||
|
||||
@@ -353,8 +371,8 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
|
||||
if (cleaned) return
|
||||
cleaned = true
|
||||
logger.log('Cleaning up plugin resources...')
|
||||
memoryInjection.destroy()
|
||||
await memoryService.destroy()
|
||||
sessionStateService.destroy()
|
||||
closeDatabase(db)
|
||||
logger.log('Plugin cleanup complete')
|
||||
}
|
||||
@@ -376,7 +394,6 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
|
||||
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
|
||||
@@ -411,7 +428,6 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
|
||||
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({
|
||||
@@ -432,11 +448,10 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
|
||||
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) {
|
||||
if (!memory || memory.projectId !== projectId) {
|
||||
logger.log(`memory-edit: id=${args.id} not found`)
|
||||
return withDimensionWarning(`Memory #${args.id} not found.`)
|
||||
}
|
||||
@@ -456,12 +471,11 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
|
||||
id: z.number().describe('The memory ID to delete'),
|
||||
},
|
||||
execute: async (args) => {
|
||||
await initPromise
|
||||
const id = args.id
|
||||
logger.log(`memory-delete: id=${id}`)
|
||||
|
||||
const memory = memoryService.getById(id)
|
||||
if (!memory) {
|
||||
if (!memory || memory.projectId !== projectId) {
|
||||
logger.log(`memory-delete: id=${id} not found`)
|
||||
return withDimensionWarning(`Memory #${id} not found.`)
|
||||
}
|
||||
@@ -477,157 +491,24 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
|
||||
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, dataDir, mismatchState)
|
||||
}
|
||||
return withDimensionWarning(await 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().optional().describe('Session ID to update. Defaults to current session if omitted.'),
|
||||
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, context) => {
|
||||
await initPromise
|
||||
const sessionId = args.sessionID ?? context.sessionID
|
||||
logger.log(`memory-planning-update: session=${sessionId}`)
|
||||
|
||||
const existing = sessionStateService.getPlanningState(sessionId, projectId)
|
||||
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().optional().describe('Session ID to retrieve. Defaults to current session if omitted.'),
|
||||
},
|
||||
execute: async (args, context) => {
|
||||
await initPromise
|
||||
const sessionId = args.sessionID ?? context.sessionID
|
||||
logger.log(`memory-planning-get: session=${sessionId}`)
|
||||
|
||||
const planningState = sessionStateService.getPlanningState(sessionId, projectId)
|
||||
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 (!currentVec.available) {
|
||||
return 'Reindex unavailable: vector service is still initializing. Try again in a few seconds.'
|
||||
}
|
||||
return executeReindex(projectId, memoryService, db, config, provider, mismatchState, currentVec)
|
||||
}
|
||||
|
||||
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'
|
||||
},
|
||||
}),
|
||||
'memory-planning-search': tool({
|
||||
description: 'Search planning states across all sessions in the current project. Use this to find planning context from prior sessions.',
|
||||
args: {
|
||||
query: z.string().optional().describe('Search keyword to filter planning states. Omit to list all.'),
|
||||
},
|
||||
execute: async (args) => {
|
||||
await initPromise
|
||||
logger.log(`memory-planning-search: query="${args.query ?? 'all'}"`)
|
||||
|
||||
const results = args.query
|
||||
? sessionStateService.searchPlanningStates(projectId, args.query)
|
||||
: sessionStateService.listPlanningStates(projectId)
|
||||
|
||||
if (results.length === 0) {
|
||||
return args.query
|
||||
? `No planning states found matching "${args.query}"`
|
||||
: 'No planning states found for this project'
|
||||
}
|
||||
|
||||
const formatted = results.map(({ sessionId, planningState, updatedAt }) => {
|
||||
const parts: string[] = [`**Session:** ${sessionId} (updated ${new Date(updatedAt).toISOString().split('T')[0]})`]
|
||||
if (planningState.objective) parts.push(` Objective: ${planningState.objective}`)
|
||||
if (planningState.current) parts.push(` Current: ${planningState.current}`)
|
||||
if (planningState.next) parts.push(` Next: ${planningState.next}`)
|
||||
if (planningState.phases && planningState.phases.length > 0) {
|
||||
const completed = planningState.phases.filter(p => p.status === 'completed').length
|
||||
parts.push(` Phases: ${completed}/${planningState.phases.length} completed`)
|
||||
}
|
||||
return parts.join('\n')
|
||||
})
|
||||
|
||||
return `Found ${results.length} planning state(s):\n\n${formatted.join('\n\n')}`
|
||||
const result = await executeHealthCheck(projectId, db, config, provider, dataDir)
|
||||
const initInfo = `\nInit: ${initState.vecReady ? 'vec ready' : 'vec pending'}${initState.syncRunning ? ', sync in progress' : initState.syncComplete ? ', sync complete' : ''}`
|
||||
return withDimensionWarning(result + initInfo)
|
||||
},
|
||||
}),
|
||||
'memory-plan-execute': tool({
|
||||
description: 'Create a new Code session, save planning state, and send the plan as the first prompt. Call this after the user approves the plan.',
|
||||
description: 'Create a new Code session and send the plan as the first prompt. Call this after the user approves the plan.',
|
||||
args: {
|
||||
plan: z.string().describe('The full implementation plan to send to the Code agent'),
|
||||
title: z.string().describe('Short title for the session (shown in session list)'),
|
||||
objective: z.string().optional().describe('Short description of what we are building'),
|
||||
phases: z.array(z.object({
|
||||
title: z.string(),
|
||||
status: z.string(),
|
||||
notes: z.string().optional(),
|
||||
})).optional().describe('Phases from the plan, each with status "pending"'),
|
||||
findings: z.array(z.string()).optional().describe('Key architectural decisions discovered during research'),
|
||||
},
|
||||
execute: async (args, context) => {
|
||||
await initPromise
|
||||
execute: async (args) => {
|
||||
logger.log(`memory-plan-execute: creating session titled "${args.title}"`)
|
||||
|
||||
const sessionTitle = args.title.length > 60 ? `${args.title.substring(0, 57)}...` : args.title
|
||||
@@ -644,24 +525,12 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
|
||||
const newSessionId = createResult.data.id
|
||||
logger.log(`memory-plan-execute: created session=${newSessionId}`)
|
||||
|
||||
const planningState: PlanningState = {
|
||||
...(args.objective && { objective: args.objective }),
|
||||
current: `Plan approved, sending to Code agent`,
|
||||
...(args.phases && { phases: args.phases }),
|
||||
...(args.findings && { findings: args.findings }),
|
||||
active: true,
|
||||
}
|
||||
sessionStateService.setPlanningState(context.sessionID, projectId, planningState)
|
||||
logger.log(`memory-plan-execute: saved planning state for session=${context.sessionID}`)
|
||||
|
||||
const planningInstruction = `\n\n---\n\nWhen you complete each phase, delegate to the @Memory subagent via the Task tool to update planning state. Tell it to call memory-planning-update with sessionID "${context.sessionID}". Update phase statuses as you progress (pending → in_progress → completed). Set current to describe what you're working on. When all work is done, set current to "Completed".`
|
||||
|
||||
const executionModel = parseModelString(config.executionModel)
|
||||
|
||||
const promptResult = await client.session.promptAsync({
|
||||
path: { id: newSessionId },
|
||||
body: {
|
||||
parts: [{ type: 'text' as const, text: args.plan + planningInstruction }],
|
||||
parts: [{ type: 'text' as const, text: args.plan }],
|
||||
agent: 'Code',
|
||||
...(executionModel && { model: executionModel }),
|
||||
},
|
||||
@@ -674,13 +543,6 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
|
||||
|
||||
logger.log(`memory-plan-execute: prompted session=${newSessionId}`)
|
||||
|
||||
const currentState = sessionStateService.getPlanningState(context.sessionID, projectId)
|
||||
sessionStateService.setPlanningState(context.sessionID, projectId, {
|
||||
...(currentState ?? planningState),
|
||||
current: `Plan sent to execution session ${newSessionId}`,
|
||||
})
|
||||
logger.log(`memory-plan-execute: updated planning state for source session=${context.sessionID}`)
|
||||
|
||||
const modelInfo = executionModel ? `${executionModel.providerID}/${executionModel.modelID}` : 'default'
|
||||
return `Implementation session created and plan sent.\n\nSession: ${newSessionId}\nTitle: ${sessionTitle}\nModel: ${modelInfo}\n\nSwitch to this session to begin. You can change the model from the session dropdown.`
|
||||
},
|
||||
@@ -699,13 +561,13 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
|
||||
'experimental.session.compacting': async (input, output) => {
|
||||
logger.log(`Compacting triggered`)
|
||||
await sessionHooks.onCompacting(
|
||||
input as { sessionID: string; branch?: string },
|
||||
input as { sessionID: string },
|
||||
output as { context: string[]; prompt?: string }
|
||||
)
|
||||
},
|
||||
'experimental.chat.messages.transform': async (
|
||||
_input: Record<string, never>,
|
||||
output: { messages: Array<{ info: { role: string; agent?: string }; parts: Array<Record<string, unknown>> }> }
|
||||
output: { messages: Array<{ info: { role: string; agent?: string; id?: string }; parts: Array<Record<string, unknown>> }> }
|
||||
) => {
|
||||
const messages = output.messages
|
||||
let userMessage: typeof messages[number] | undefined
|
||||
@@ -715,14 +577,53 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
|
||||
break
|
||||
}
|
||||
}
|
||||
if (!userMessage || userMessage.info.agent !== agents.architect.displayName) return
|
||||
|
||||
if (!userMessage) return
|
||||
|
||||
const messageId = userMessage.info.id
|
||||
const alreadyInjected = messageId ? injectedMessageIds.has(messageId) : false
|
||||
|
||||
if (!alreadyInjected) {
|
||||
const textParts = userMessage.parts
|
||||
.filter((p) => p.type === 'text' && typeof p.text === 'string')
|
||||
.map((p) => p.text as string)
|
||||
const userText = textParts.join('\n').trim()
|
||||
|
||||
if (userText.length > 0) {
|
||||
const memoryInjectionEnabled = config.memoryInjection?.enabled ?? true
|
||||
if (memoryInjectionEnabled) {
|
||||
const injected = await memoryInjection.handler(userText)
|
||||
if (injected) {
|
||||
userMessage.parts.push({
|
||||
type: 'text',
|
||||
text: injected,
|
||||
synthetic: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (messageId) {
|
||||
injectedMessageIds.add(messageId)
|
||||
if (injectedMessageIds.size > 100) {
|
||||
const first = injectedMessageIds.values().next().value
|
||||
if (first) injectedMessageIds.delete(first)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const messagesTransformEnabled = messagesTransformConfig?.enabled ?? true
|
||||
if (!messagesTransformEnabled) return
|
||||
|
||||
const isArchitect = userMessage.info.agent === agents.architect.displayName
|
||||
if (!isArchitect) return
|
||||
|
||||
userMessage.parts.push({
|
||||
type: 'text',
|
||||
text: `<system-reminder>
|
||||
Plan mode is active. You MUST NOT make any file edits, run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supersedes any other instructions you have received.
|
||||
|
||||
You may ONLY: observe, analyze, plan, and use memory tools (memory-read, memory-write, memory-edit, memory-delete, memory-health, memory-planning-get, memory-plan-execute).
|
||||
You may ONLY: observe, analyze, plan, and use memory tools (memory-read, memory-write, memory-edit, memory-delete, memory-health, memory-plan-execute).
|
||||
</system-reminder>`,
|
||||
synthetic: true,
|
||||
})
|
||||
|
||||
@@ -18,7 +18,7 @@ export class EmbeddingSyncService {
|
||||
private batchSize: number
|
||||
private maxRetries: number
|
||||
private syncInProgress: boolean = false
|
||||
private static readonly MAX_ITERATIONS = 100
|
||||
private static readonly MAX_ITERATIONS = 1000
|
||||
|
||||
constructor(memoryService: MemoryService, logger?: Logger, options: EmbeddingSyncOptions = {}) {
|
||||
this.memoryService = memoryService
|
||||
@@ -44,12 +44,12 @@ export class EmbeddingSyncService {
|
||||
let failed = 0
|
||||
|
||||
try {
|
||||
let pending = this.memoryService.countMemoriesWithoutEmbeddings()
|
||||
let pending = await this.memoryService.countMemoriesWithoutEmbeddings()
|
||||
let iterations = 0
|
||||
|
||||
while (pending > 0 && iterations < EmbeddingSyncService.MAX_ITERATIONS) {
|
||||
iterations++
|
||||
const memories = this.memoryService.getMemoriesWithoutEmbeddings(undefined, this.batchSize)
|
||||
const memories = await this.memoryService.getMemoriesWithoutEmbeddings(undefined, this.batchSize)
|
||||
let batchSuccess = 0
|
||||
let batchFailed = 0
|
||||
|
||||
@@ -83,7 +83,7 @@ export class EmbeddingSyncService {
|
||||
break
|
||||
}
|
||||
|
||||
pending = this.memoryService.countMemoriesWithoutEmbeddings()
|
||||
pending = await this.memoryService.countMemoriesWithoutEmbeddings()
|
||||
|
||||
if (pending > 0) {
|
||||
this.logger?.log(`[embedding-sync] Progress: ${embedded} embedded, ${failed} failed, ${pending} remaining`)
|
||||
@@ -110,12 +110,12 @@ export class EmbeddingSyncService {
|
||||
let failed = 0
|
||||
|
||||
try {
|
||||
let pending = this.memoryService.countMemoriesWithoutEmbeddings(projectId)
|
||||
let pending = await this.memoryService.countMemoriesWithoutEmbeddings(projectId)
|
||||
let iterations = 0
|
||||
|
||||
while (pending > 0 && iterations < EmbeddingSyncService.MAX_ITERATIONS) {
|
||||
iterations++
|
||||
const memories = this.memoryService.getMemoriesWithoutEmbeddings(projectId, this.batchSize)
|
||||
const memories = await this.memoryService.getMemoriesWithoutEmbeddings(projectId, this.batchSize)
|
||||
let batchSuccess = 0
|
||||
let batchFailed = 0
|
||||
|
||||
@@ -148,7 +148,7 @@ export class EmbeddingSyncService {
|
||||
break
|
||||
}
|
||||
|
||||
pending = this.memoryService.countMemoriesWithoutEmbeddings(projectId)
|
||||
pending = await this.memoryService.countMemoriesWithoutEmbeddings(projectId)
|
||||
}
|
||||
|
||||
if (iterations >= EmbeddingSyncService.MAX_ITERATIONS) {
|
||||
|
||||
@@ -169,6 +169,7 @@ export class MemoryService {
|
||||
}
|
||||
): Promise<MemorySearchResult[]> {
|
||||
const embedding = await this.embeddingService.embedText(query)
|
||||
this.logger?.log(`memory-search: embedding generated (dimensions=${embedding.length}, hasSignal=${embedding.some(v => v !== 0)})`)
|
||||
const results = await this.queries.search(embedding, projectId, filters)
|
||||
results.forEach((r) => this.queries.trackAccess(r.memory.id))
|
||||
return results
|
||||
@@ -197,11 +198,11 @@ export class MemoryService {
|
||||
return this.queries.countByProject(projectId)
|
||||
}
|
||||
|
||||
getMemoriesWithoutEmbeddings(projectId?: string, limit: number = 50): Memory[] {
|
||||
async getMemoriesWithoutEmbeddings(projectId?: string, limit: number = 50): Promise<Memory[]> {
|
||||
return this.queries.getMemoriesWithoutEmbeddings(projectId, limit)
|
||||
}
|
||||
|
||||
countMemoriesWithoutEmbeddings(projectId?: string): number {
|
||||
async countMemoriesWithoutEmbeddings(projectId?: string): Promise<number> {
|
||||
return this.queries.countMemoriesWithoutEmbeddings(projectId)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,137 +0,0 @@
|
||||
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 interface PlanningStateResult {
|
||||
sessionId: string
|
||||
planningState: PlanningState
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
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:${projectId}:${sessionId}`
|
||||
this.set(key, projectId, planningState, DEFAULT_SESSION_TTL)
|
||||
}
|
||||
|
||||
getPlanningState(sessionId: string, projectId: string): PlanningState | null {
|
||||
const key = `session:${projectId}:${sessionId}`
|
||||
return this.get<PlanningState>(key)
|
||||
}
|
||||
|
||||
listPlanningStates(projectId: string): PlanningStateResult[] {
|
||||
const prefix = `session:${projectId}:`
|
||||
const rows = this.queries.listByProjectAndPrefix(projectId, prefix)
|
||||
return rows.map(row => ({
|
||||
sessionId: row.key.slice(prefix.length),
|
||||
planningState: JSON.parse(row.data) as PlanningState,
|
||||
updatedAt: row.updated_at,
|
||||
}))
|
||||
}
|
||||
|
||||
searchPlanningStates(projectId: string, query: string): PlanningStateResult[] {
|
||||
const prefix = `session:${projectId}:`
|
||||
const rows = this.queries.searchByProjectAndPrefix(projectId, prefix, query)
|
||||
return rows.map(row => ({
|
||||
sessionId: row.key.slice(prefix.length),
|
||||
planningState: JSON.parse(row.data) as PlanningState,
|
||||
updatedAt: row.updated_at,
|
||||
}))
|
||||
}
|
||||
|
||||
setCompactionSnapshot(sessionId: string, projectId: string, snapshot: PreCompactionSnapshot): void {
|
||||
const key = `compaction:snapshot:${projectId}:${sessionId}`
|
||||
this.set(key, projectId, snapshot, DEFAULT_SNAPSHOT_TTL)
|
||||
}
|
||||
|
||||
getCompactionSnapshot(sessionId: string, projectId: string): PreCompactionSnapshot | null {
|
||||
const key = `compaction:snapshot:${projectId}:${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)
|
||||
}
|
||||
@@ -110,6 +110,8 @@ function normalizeConfig(config: PluginConfig): PluginConfig {
|
||||
dedupThreshold: config.dedupThreshold,
|
||||
logging: config.logging,
|
||||
compaction: config.compaction,
|
||||
memoryInjection: config.memoryInjection,
|
||||
messagesTransform: config.messagesTransform,
|
||||
executionModel: config.executionModel,
|
||||
}
|
||||
|
||||
|
||||
@@ -97,20 +97,6 @@ export function initializeDatabase(dataDir: string): Database {
|
||||
db.run(`CREATE INDEX IF NOT EXISTS idx_memories_project_id ON memories(project_id)`)
|
||||
db.run(`CREATE INDEX IF NOT EXISTS idx_memories_scope ON memories(scope)`)
|
||||
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS session_state (
|
||||
key TEXT PRIMARY KEY,
|
||||
project_id TEXT NOT NULL,
|
||||
data TEXT NOT NULL,
|
||||
expires_at INTEGER,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
)
|
||||
`)
|
||||
|
||||
db.run(`CREATE INDEX IF NOT EXISTS idx_session_state_project_id ON session_state(project_id)`)
|
||||
db.run(`CREATE INDEX IF NOT EXISTS idx_session_state_expires_at ON session_state(expires_at)`)
|
||||
|
||||
runMigrations(db)
|
||||
|
||||
db.run(`
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
export { initializeDatabase, closeDatabase, resolveDataDir, resolveLogPath } from './database'
|
||||
export { createVecService } from './vec'
|
||||
export { getTableDimensions, recreateVecTable } from './vec-utils'
|
||||
export type { TableDimensionsResult } from './vec-utils'
|
||||
export type { VecService, VecSearchResult } from './vec-types'
|
||||
export type { VecService, VecSearchResult, TableDimensionsResult } from './vec-types'
|
||||
export { createMemoryQuery } from './memory-queries'
|
||||
export { createSessionStateQueries } from './session-state-queries'
|
||||
export { createMetadataQuery } from './metadata-queries'
|
||||
|
||||
export type {
|
||||
@@ -15,8 +12,5 @@ export type {
|
||||
MemorySearchResult,
|
||||
MemoryStats,
|
||||
ListMemoriesFilter,
|
||||
SessionState,
|
||||
PlanningState,
|
||||
PreCompactionSnapshot,
|
||||
CompactionConfig,
|
||||
} from '../types'
|
||||
@@ -36,7 +36,15 @@ interface Logger {
|
||||
export function createMemoryQuery(db: Database, vec: VecService, logger?: Logger) {
|
||||
const logError = (context: string, error?: unknown) => {
|
||||
if (logger) {
|
||||
logger.error(context, error)
|
||||
const errorMessage = error instanceof Error ? error.message : String(error)
|
||||
const errorStack = error instanceof Error ? error.stack : undefined
|
||||
logger.error(context, { message: errorMessage, stack: errorStack })
|
||||
}
|
||||
}
|
||||
|
||||
const logInfo = (message: string) => {
|
||||
if (logger) {
|
||||
logger.log(message)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -227,6 +235,7 @@ export function createMemoryQuery(db: Database, vec: VecService, logger?: Logger
|
||||
: { scope: filters?.scope, limit: filters?.limit }
|
||||
|
||||
const memories = this.listAll(basicFilters)
|
||||
logInfo(`memory-queries: vec unavailable, returning ${memories.length} unranked results`)
|
||||
return memories.map(memory => ({ memory, distance: 1.0 }))
|
||||
}
|
||||
|
||||
@@ -238,6 +247,7 @@ export function createMemoryQuery(db: Database, vec: VecService, logger?: Logger
|
||||
? { projectId, scope: filters?.scope, limit: filters?.limit }
|
||||
: { scope: filters?.scope, limit: filters?.limit }
|
||||
const memories = this.listAll(basicFilters)
|
||||
logInfo(`memory-queries: vec returned 0 results (no embeddings?), returning ${memories.length} unranked results`)
|
||||
return memories.map(memory => ({ memory, distance: 1.0 }))
|
||||
}
|
||||
|
||||
@@ -251,18 +261,23 @@ export function createMemoryQuery(db: Database, vec: VecService, logger?: Logger
|
||||
WHERE id IN (${placeholders})
|
||||
`).all(...memoryIds) as MemoryRow[]
|
||||
|
||||
return rows
|
||||
const results = rows
|
||||
.map(row => ({
|
||||
memory: mapRow(row),
|
||||
distance: distanceMap.get(row.id) ?? 1.0,
|
||||
}))
|
||||
.sort((a, b) => a.distance - b.distance)
|
||||
} catch {
|
||||
|
||||
logInfo(`memory-queries: vec returned ${vecResults.length} ranked results`)
|
||||
return results
|
||||
} catch (error) {
|
||||
logError('memory-queries: vec search error, returning unranked results', error)
|
||||
const basicFilters = projectId
|
||||
? { projectId, scope: filters?.scope, limit: filters?.limit }
|
||||
: { scope: filters?.scope, limit: filters?.limit }
|
||||
|
||||
const memories = this.listAll(basicFilters)
|
||||
logInfo(`memory-queries: returning ${memories.length} unranked results after error`)
|
||||
return memories.map(memory => ({ memory, distance: 1.0 }))
|
||||
}
|
||||
},
|
||||
@@ -312,93 +327,25 @@ export function createMemoryQuery(db: Database, vec: VecService, logger?: Logger
|
||||
return !!result
|
||||
},
|
||||
|
||||
getMemoriesWithoutEmbeddings(
|
||||
async getMemoriesWithoutEmbeddings(
|
||||
projectId?: string,
|
||||
limit: number = 50
|
||||
): Memory[] {
|
||||
const embeddingsTableExists = db.prepare(
|
||||
"SELECT name FROM sqlite_master WHERE type='table' AND name='memory_embeddings'"
|
||||
).get()
|
||||
): Promise<Memory[]> {
|
||||
const rows = await vec.getWithoutEmbeddings(projectId, limit)
|
||||
if (rows.length === 0) return []
|
||||
|
||||
if (!embeddingsTableExists) {
|
||||
const conditions: string[] = []
|
||||
const params: (string | number)[] = []
|
||||
|
||||
if (projectId) {
|
||||
conditions.push('project_id = ?')
|
||||
params.push(projectId)
|
||||
}
|
||||
|
||||
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''
|
||||
const rows = db.prepare(`
|
||||
SELECT id, project_id, scope, content, file_path, access_count, last_accessed_at, created_at, updated_at
|
||||
FROM memories
|
||||
${where}
|
||||
ORDER BY created_at ASC
|
||||
LIMIT ? OFFSET 0
|
||||
`).all(...params, limit) as MemoryRow[]
|
||||
|
||||
return rows.map(mapRow)
|
||||
}
|
||||
|
||||
const conditions: string[] = ['e.memory_id IS NULL']
|
||||
const params: (string | number)[] = []
|
||||
|
||||
if (projectId) {
|
||||
conditions.push('m.project_id = ?')
|
||||
params.push(projectId)
|
||||
}
|
||||
|
||||
const rows = db.prepare(`
|
||||
SELECT m.id, m.project_id, m.scope, m.content, m.file_path, m.access_count, m.last_accessed_at, m.created_at, m.updated_at
|
||||
FROM memories m
|
||||
LEFT JOIN memory_embeddings e ON m.id = e.memory_id
|
||||
WHERE ${conditions.join(' AND ')}
|
||||
ORDER BY m.created_at ASC
|
||||
LIMIT ? OFFSET 0
|
||||
`).all(...params, limit) as MemoryRow[]
|
||||
|
||||
return rows.map(mapRow)
|
||||
const ids = rows.map(r => r.id)
|
||||
const placeholders = ids.map(() => '?').join(',')
|
||||
const memories = db.prepare(`
|
||||
SELECT id, project_id, scope, content, file_path, access_count, last_accessed_at, created_at, updated_at
|
||||
FROM memories WHERE id IN (${placeholders})
|
||||
ORDER BY created_at ASC
|
||||
`).all(...ids) as MemoryRow[]
|
||||
return memories.map(mapRow)
|
||||
},
|
||||
|
||||
countMemoriesWithoutEmbeddings(projectId?: string): number {
|
||||
const embeddingsTableExists = db.prepare(
|
||||
"SELECT name FROM sqlite_master WHERE type='table' AND name='memory_embeddings'"
|
||||
).get()
|
||||
|
||||
if (!embeddingsTableExists) {
|
||||
const conditions: string[] = []
|
||||
const params: (string | number)[] = []
|
||||
|
||||
if (projectId) {
|
||||
conditions.push('project_id = ?')
|
||||
params.push(projectId)
|
||||
}
|
||||
|
||||
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''
|
||||
const result = db.prepare(`
|
||||
SELECT COUNT(*) as count FROM memories ${where}
|
||||
`).get(...params) as { count: number }
|
||||
|
||||
return result.count
|
||||
}
|
||||
|
||||
const conditions: string[] = ['e.memory_id IS NULL']
|
||||
const params: (string | number)[] = []
|
||||
|
||||
if (projectId) {
|
||||
conditions.push('m.project_id = ?')
|
||||
params.push(projectId)
|
||||
}
|
||||
|
||||
const result = db.prepare(`
|
||||
SELECT COUNT(*) as count
|
||||
FROM memories m
|
||||
LEFT JOIN memory_embeddings e ON m.id = e.memory_id
|
||||
WHERE ${conditions.join(' AND ')}
|
||||
`).get(...params) as { count: number }
|
||||
|
||||
return result.count
|
||||
async countMemoriesWithoutEmbeddings(projectId?: string): Promise<number> {
|
||||
return vec.countWithoutEmbeddings(projectId)
|
||||
},
|
||||
|
||||
getByContent(projectId: string, content: string): Memory | undefined {
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
|
||||
export interface SessionStateRow {
|
||||
key: string
|
||||
project_id: string
|
||||
data: string
|
||||
expires_at: number | null
|
||||
created_at: number
|
||||
updated_at: number
|
||||
}
|
||||
|
||||
function mapRow(row: {
|
||||
key: string
|
||||
project_id: string
|
||||
data: string
|
||||
expires_at: number | null
|
||||
created_at: number
|
||||
updated_at: number
|
||||
}): SessionStateRow {
|
||||
return row
|
||||
}
|
||||
|
||||
function escapeLikeWildcards(value: string): string {
|
||||
return value.replace(/\\/g, '\\\\').replace(/%/g, '\\%').replace(/_/g, '\\_')
|
||||
}
|
||||
|
||||
type SessionStateRowRaw = Parameters<typeof mapRow>[0]
|
||||
|
||||
export function createSessionStateQueries(db: Database) {
|
||||
const getStmt = db.prepare(
|
||||
`SELECT key, project_id, data, expires_at, created_at, updated_at
|
||||
FROM session_state
|
||||
WHERE key = ? AND (expires_at IS NULL OR expires_at > ?)`
|
||||
)
|
||||
|
||||
const setStmt = db.prepare(
|
||||
`INSERT INTO session_state (key, project_id, data, expires_at, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(key) DO UPDATE SET
|
||||
data = excluded.data,
|
||||
expires_at = excluded.expires_at,
|
||||
updated_at = excluded.updated_at`
|
||||
)
|
||||
|
||||
const deleteStmt = db.prepare(`DELETE FROM session_state WHERE key = ?`)
|
||||
|
||||
const deleteByPrefixStmt = db.prepare(
|
||||
`DELETE FROM session_state WHERE key LIKE ?`
|
||||
)
|
||||
|
||||
const deleteExpiredStmt = db.prepare(
|
||||
`DELETE FROM session_state WHERE expires_at IS NOT NULL AND expires_at < ?`
|
||||
)
|
||||
|
||||
const listByProjectStmt = db.prepare(
|
||||
`SELECT key, project_id, data, expires_at, created_at, updated_at
|
||||
FROM session_state
|
||||
WHERE project_id = ? AND (expires_at IS NULL OR expires_at > ?)
|
||||
ORDER BY updated_at DESC`
|
||||
)
|
||||
|
||||
const searchByProjectAndPrefixStmt = db.prepare(
|
||||
`SELECT key, project_id, data, expires_at, created_at, updated_at
|
||||
FROM session_state
|
||||
WHERE project_id = ? AND key LIKE ? AND data LIKE ? ESCAPE '\\' AND (expires_at IS NULL OR expires_at > ?)
|
||||
ORDER BY updated_at DESC`
|
||||
)
|
||||
|
||||
const listByProjectAndPrefixStmt = db.prepare(
|
||||
`SELECT key, project_id, data, expires_at, created_at, updated_at
|
||||
FROM session_state
|
||||
WHERE project_id = ? AND key LIKE ? AND (expires_at IS NULL OR expires_at > ?)
|
||||
ORDER BY updated_at DESC`
|
||||
)
|
||||
|
||||
return {
|
||||
get(key: string): SessionStateRow | undefined {
|
||||
const now = Date.now()
|
||||
const row = getStmt.get(key, now) as SessionStateRowRaw | null
|
||||
return row ? mapRow(row) : undefined
|
||||
},
|
||||
|
||||
set(key: string, projectId: string, data: string, expiresAt: number | null): void {
|
||||
const now = Date.now()
|
||||
setStmt.run(key, projectId, data, expiresAt, now, now)
|
||||
},
|
||||
|
||||
delete(key: string): void {
|
||||
deleteStmt.run(key)
|
||||
},
|
||||
|
||||
deleteByPrefix(prefix: string): void {
|
||||
const pattern = prefix.endsWith('*') ? prefix.slice(0, -1) + '%' : `${prefix}%`
|
||||
deleteByPrefixStmt.run(pattern)
|
||||
},
|
||||
|
||||
deleteExpired(): number {
|
||||
const now = Date.now()
|
||||
const result = deleteExpiredStmt.run(now)
|
||||
return result.changes
|
||||
},
|
||||
|
||||
listByProject(projectId: string): SessionStateRow[] {
|
||||
const now = Date.now()
|
||||
const rows = listByProjectStmt.all(projectId, now) as SessionStateRowRaw[]
|
||||
return rows.map(mapRow)
|
||||
},
|
||||
|
||||
searchByProjectAndPrefix(projectId: string, keyPrefix: string, searchTerm: string): SessionStateRow[] {
|
||||
const now = Date.now()
|
||||
const keyPattern = `${escapeLikeWildcards(keyPrefix)}%`
|
||||
const searchPattern = `%${escapeLikeWildcards(searchTerm)}%`
|
||||
const rows = searchByProjectAndPrefixStmt.all(projectId, keyPattern, searchPattern, now) as SessionStateRowRaw[]
|
||||
return rows.map(mapRow)
|
||||
},
|
||||
|
||||
listByProjectAndPrefix(projectId: string, keyPrefix: string): SessionStateRow[] {
|
||||
const now = Date.now()
|
||||
const keyPattern = `${escapeLikeWildcards(keyPrefix)}%`
|
||||
const rows = listByProjectAndPrefixStmt.all(projectId, keyPattern, now) as SessionStateRowRaw[]
|
||||
return rows.map(mapRow)
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -84,7 +84,10 @@ async function startWorker(config: {
|
||||
|
||||
cleanupStale(pidPath, socketPath)
|
||||
|
||||
const workerScript = join(__dirname, 'vec-worker.ts')
|
||||
const workerScriptJs = join(__dirname, 'vec-worker.js')
|
||||
const workerScript = existsSync(workerScriptJs)
|
||||
? workerScriptJs
|
||||
: join(__dirname, 'vec-worker.ts')
|
||||
const proc = spawn('bun', [
|
||||
workerScript,
|
||||
'--db', config.dbPath,
|
||||
@@ -174,6 +177,27 @@ export async function createWorkerVecService(config: {
|
||||
return resp.results as VecSearchResult[]
|
||||
},
|
||||
|
||||
async countWithoutEmbeddings(projectId?: string): Promise<number> {
|
||||
const resp = await req({ action: 'countWithoutEmbeddings', projectId })
|
||||
return (resp?.count as number) ?? 0
|
||||
},
|
||||
|
||||
async getWithoutEmbeddings(projectId?: string, limit: number = 50): Promise<Array<{ id: number; content: string }>> {
|
||||
const resp = await req({ action: 'getWithoutEmbeddings', projectId, limit })
|
||||
if (!resp?.rows) return []
|
||||
return resp.rows as Array<{ id: number; content: string }>
|
||||
},
|
||||
|
||||
async recreateTable(dimensions: number): Promise<void> {
|
||||
await req({ action: 'recreateTable', dimensions })
|
||||
},
|
||||
|
||||
async getDimensions(): Promise<{ exists: boolean; dimensions: number | null }> {
|
||||
const resp = await req({ action: 'getDimensions' })
|
||||
if (!resp) return { exists: false, dimensions: null }
|
||||
return { exists: resp.exists as boolean, dimensions: (resp.dimensions as number | null) ?? null }
|
||||
},
|
||||
|
||||
dispose() {
|
||||
const pidPath = join(config.dataDir, 'vec-worker.pid')
|
||||
if (existsSync(pidPath)) {
|
||||
|
||||
@@ -1,115 +0,0 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { VecService, VecSearchResult } from './vec-types'
|
||||
import { createRequire } from 'node:module'
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
|
||||
export function createDirectVecService(db: Database): VecService {
|
||||
let loaded = false
|
||||
|
||||
try {
|
||||
const { getLoadablePath } = require('sqlite-vec')
|
||||
db.loadExtension(getLoadablePath())
|
||||
loaded = true
|
||||
} catch {
|
||||
loaded = false
|
||||
}
|
||||
|
||||
return {
|
||||
get available() {
|
||||
return loaded
|
||||
},
|
||||
|
||||
async initialize(dimensions: number) {
|
||||
if (!loaded) return
|
||||
|
||||
const exists = db.prepare(
|
||||
"SELECT name FROM sqlite_master WHERE type='table' AND name='memory_embeddings'"
|
||||
).get()
|
||||
|
||||
if (!exists) {
|
||||
db.run(`
|
||||
CREATE VIRTUAL TABLE IF NOT EXISTS memory_embeddings USING vec0(
|
||||
embedding float[${dimensions}],
|
||||
+memory_id INTEGER,
|
||||
+project_id TEXT
|
||||
)
|
||||
`)
|
||||
}
|
||||
},
|
||||
|
||||
async insert(embedding: number[], memoryId: number, projectId: string) {
|
||||
if (!loaded) return
|
||||
db.prepare(
|
||||
'INSERT INTO memory_embeddings (embedding, memory_id, project_id) VALUES (?, ?, ?)'
|
||||
).run(JSON.stringify(embedding), memoryId, projectId)
|
||||
},
|
||||
|
||||
async delete(memoryId: number) {
|
||||
if (!loaded) return
|
||||
db.prepare('DELETE FROM memory_embeddings WHERE memory_id = ?').run(memoryId)
|
||||
},
|
||||
|
||||
async deleteByProject(projectId: string) {
|
||||
if (!loaded) return
|
||||
db.prepare('DELETE FROM memory_embeddings WHERE project_id = ?').run(projectId)
|
||||
},
|
||||
|
||||
async deleteByMemoryIds(memoryIds: number[]) {
|
||||
if (!loaded || memoryIds.length === 0) return
|
||||
const placeholders = memoryIds.map(() => '?').join(',')
|
||||
db.prepare(`DELETE FROM memory_embeddings WHERE memory_id IN (${placeholders})`).run(...memoryIds)
|
||||
},
|
||||
|
||||
async search(embedding: number[], projectId?: string, scope?: string, limit: number = 10): Promise<VecSearchResult[]> {
|
||||
if (!loaded) return []
|
||||
|
||||
const embeddingJson = JSON.stringify(embedding)
|
||||
const conditions: string[] = []
|
||||
const params: (string | number)[] = [embeddingJson]
|
||||
|
||||
if (projectId) {
|
||||
conditions.push('e.project_id = ?')
|
||||
params.push(projectId)
|
||||
}
|
||||
if (scope) {
|
||||
conditions.push('m.scope = ?')
|
||||
params.push(scope)
|
||||
}
|
||||
params.push(limit)
|
||||
|
||||
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''
|
||||
const rows = db.prepare(`
|
||||
SELECT e.memory_id, (e.embedding <=> ?) as distance
|
||||
FROM memory_embeddings e
|
||||
JOIN memories m ON m.id = e.memory_id
|
||||
${whereClause}
|
||||
ORDER BY distance
|
||||
LIMIT ?
|
||||
`).all(...params) as Array<{ memory_id: number; distance: number }>
|
||||
|
||||
return rows.map(r => ({ memoryId: r.memory_id, distance: r.distance }))
|
||||
},
|
||||
|
||||
async findSimilar(embedding: number[], projectId: string, threshold: number, limit: number): Promise<VecSearchResult[]> {
|
||||
if (!loaded) return []
|
||||
|
||||
const embeddingJson = JSON.stringify(embedding)
|
||||
const rows = db.prepare(`
|
||||
SELECT e.memory_id, (e.embedding <=> ?) as distance
|
||||
FROM memory_embeddings e
|
||||
JOIN memories m ON m.id = e.memory_id
|
||||
WHERE m.project_id = ?
|
||||
AND (e.embedding <=> ?) < ?
|
||||
ORDER BY distance LIMIT ?
|
||||
`).all(embeddingJson, projectId, embeddingJson, threshold, limit) as Array<{
|
||||
memory_id: number
|
||||
distance: number
|
||||
}>
|
||||
|
||||
return rows.map(r => ({ memoryId: r.memory_id, distance: r.distance }))
|
||||
},
|
||||
|
||||
dispose() {},
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@ export interface VecSearchResult {
|
||||
distance: number
|
||||
}
|
||||
|
||||
export type TableDimensionsResult = { exists: boolean; dimensions: number | null }
|
||||
|
||||
export interface VecService {
|
||||
readonly available: boolean
|
||||
initialize(dimensions: number): Promise<void>
|
||||
@@ -12,5 +14,9 @@ export interface VecService {
|
||||
deleteByMemoryIds(memoryIds: number[]): Promise<void>
|
||||
search(embedding: number[], projectId?: string, scope?: string, limit?: number): Promise<VecSearchResult[]>
|
||||
findSimilar(embedding: number[], projectId: string, threshold: number, limit: number): Promise<VecSearchResult[]>
|
||||
countWithoutEmbeddings(projectId?: string): Promise<number>
|
||||
getWithoutEmbeddings(projectId?: string, limit?: number): Promise<Array<{ id: number; content: string }>>
|
||||
recreateTable(dimensions: number): Promise<void>
|
||||
getDimensions(): Promise<TableDimensionsResult>
|
||||
dispose(): void
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
|
||||
export type TableDimensionsResult =
|
||||
| { exists: false }
|
||||
| { exists: true; dimensions: number | null }
|
||||
|
||||
export function getTableDimensions(db: Database): TableDimensionsResult {
|
||||
const row = db.prepare(
|
||||
"SELECT sql FROM sqlite_master WHERE type='table' AND name='memory_embeddings'"
|
||||
).get() as { sql: string } | undefined
|
||||
|
||||
if (!row) return { exists: false }
|
||||
|
||||
const match = row.sql.match(/float\[(\d+)\]/i)
|
||||
return { exists: true, dimensions: match ? parseInt(match[1]!, 10) : null }
|
||||
}
|
||||
|
||||
export function recreateVecTable(db: Database, dimensions: number): void {
|
||||
db.run('DROP TABLE IF EXISTS memory_embeddings')
|
||||
db.run(`
|
||||
CREATE VIRTUAL TABLE memory_embeddings USING vec0(
|
||||
embedding float[${dimensions}],
|
||||
+memory_id INTEGER,
|
||||
+project_id TEXT
|
||||
)
|
||||
`)
|
||||
}
|
||||
@@ -57,7 +57,40 @@ class VecWorker {
|
||||
if (!exists) {
|
||||
this.db.run(`
|
||||
CREATE VIRTUAL TABLE IF NOT EXISTS memory_embeddings USING vec0(
|
||||
embedding float[${this.config.dimensions}],
|
||||
embedding float[${this.config.dimensions}] distance_metric=cosine,
|
||||
+memory_id INTEGER,
|
||||
+project_id TEXT
|
||||
)
|
||||
`)
|
||||
return
|
||||
}
|
||||
|
||||
const row = this.db.prepare(
|
||||
"SELECT sql FROM sqlite_master WHERE type='table' AND name='memory_embeddings'"
|
||||
).get() as { sql: string } | undefined
|
||||
|
||||
if (!row) return
|
||||
|
||||
const match = row.sql.match(/float\[(\d+)\]/i)
|
||||
const existingDimensions = match ? parseInt(match[1]!, 10) : null
|
||||
|
||||
if (existingDimensions !== null && existingDimensions !== this.config.dimensions) {
|
||||
this.db.run('DROP TABLE IF EXISTS memory_embeddings')
|
||||
this.db.run(`
|
||||
CREATE VIRTUAL TABLE memory_embeddings USING vec0(
|
||||
embedding float[${this.config.dimensions}] distance_metric=cosine,
|
||||
+memory_id INTEGER,
|
||||
+project_id TEXT
|
||||
)
|
||||
`)
|
||||
return
|
||||
}
|
||||
|
||||
if (!row.sql.includes('distance_metric=cosine')) {
|
||||
this.db.run('DROP TABLE IF EXISTS memory_embeddings')
|
||||
this.db.run(`
|
||||
CREATE VIRTUAL TABLE memory_embeddings USING vec0(
|
||||
embedding float[${this.config.dimensions}] distance_metric=cosine,
|
||||
+memory_id INTEGER,
|
||||
+project_id TEXT
|
||||
)
|
||||
@@ -118,7 +151,7 @@ class VecWorker {
|
||||
if (!exists) {
|
||||
this.db.run(`
|
||||
CREATE VIRTUAL TABLE IF NOT EXISTS memory_embeddings USING vec0(
|
||||
embedding float[${dims}],
|
||||
embedding float[${dims}] distance_metric=cosine,
|
||||
+memory_id INTEGER,
|
||||
+project_id TEXT
|
||||
)
|
||||
@@ -165,32 +198,40 @@ class VecWorker {
|
||||
const scope = req.scope as string | undefined
|
||||
const limit = (req.limit as number) ?? 10
|
||||
const embeddingJson = JSON.stringify(embedding)
|
||||
const needsPostFilter = !!(projectId || scope)
|
||||
const knnLimit = needsPostFilter ? limit * 5 : limit
|
||||
|
||||
const conditions: string[] = []
|
||||
const params: (string | number)[] = [embeddingJson]
|
||||
|
||||
if (projectId) {
|
||||
conditions.push('e.project_id = ?')
|
||||
params.push(projectId)
|
||||
}
|
||||
if (scope) {
|
||||
conditions.push('m.scope = ?')
|
||||
params.push(scope)
|
||||
}
|
||||
|
||||
params.push(limit)
|
||||
|
||||
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''
|
||||
const rows = this.db.prepare(`
|
||||
SELECT e.memory_id, (e.embedding <=> ?) as distance
|
||||
FROM memory_embeddings e
|
||||
JOIN memories m ON m.id = e.memory_id
|
||||
${where}
|
||||
ORDER BY distance
|
||||
let knnRows = this.db.prepare(`
|
||||
SELECT memory_id, distance
|
||||
FROM memory_embeddings
|
||||
WHERE embedding MATCH ?
|
||||
LIMIT ?
|
||||
`).all(...params) as Array<{ memory_id: number; distance: number }>
|
||||
`).all(embeddingJson, knnLimit) as Array<{ memory_id: number; distance: number }>
|
||||
|
||||
return { results: rows.map(r => ({ memoryId: r.memory_id, distance: r.distance })) }
|
||||
if (needsPostFilter && knnRows.length > 0) {
|
||||
const ids = knnRows.map(r => r.memory_id)
|
||||
const placeholders = ids.map(() => '?').join(',')
|
||||
const conditions: string[] = [`id IN (${placeholders})`]
|
||||
const params: (string | number)[] = [...ids]
|
||||
|
||||
if (projectId) {
|
||||
conditions.push('project_id = ?')
|
||||
params.push(projectId)
|
||||
}
|
||||
if (scope) {
|
||||
conditions.push('scope = ?')
|
||||
params.push(scope)
|
||||
}
|
||||
|
||||
const validRows = this.db.prepare(
|
||||
`SELECT id FROM memories WHERE ${conditions.join(' AND ')}`
|
||||
).all(...params) as Array<{ id: number }>
|
||||
const validIds = new Set(validRows.map(r => r.id))
|
||||
knnRows = knnRows.filter(r => validIds.has(r.memory_id))
|
||||
}
|
||||
|
||||
const results = knnRows.slice(0, limit)
|
||||
return { results: results.map(r => ({ memoryId: r.memory_id, distance: r.distance })) }
|
||||
}
|
||||
|
||||
case 'findSimilar': {
|
||||
@@ -200,19 +241,28 @@ class VecWorker {
|
||||
const limit = req.limit as number
|
||||
const embeddingJson = JSON.stringify(embedding)
|
||||
|
||||
const rows = this.db.prepare(`
|
||||
SELECT e.memory_id, (e.embedding <=> ?) as distance
|
||||
FROM memory_embeddings e
|
||||
JOIN memories m ON m.id = e.memory_id
|
||||
WHERE m.project_id = ?
|
||||
AND (e.embedding <=> ?) < ?
|
||||
ORDER BY distance LIMIT ?
|
||||
`).all(embeddingJson, projectId, embeddingJson, threshold, limit) as Array<{
|
||||
memory_id: number
|
||||
distance: number
|
||||
}>
|
||||
const knnRows = this.db.prepare(`
|
||||
SELECT memory_id, distance
|
||||
FROM memory_embeddings
|
||||
WHERE embedding MATCH ?
|
||||
LIMIT ?
|
||||
`).all(embeddingJson, limit * 5) as Array<{ memory_id: number; distance: number }>
|
||||
|
||||
return { results: rows.map(r => ({ memoryId: r.memory_id, distance: r.distance })) }
|
||||
const ids = knnRows.map(r => r.memory_id)
|
||||
if (ids.length === 0) {
|
||||
return { results: [] }
|
||||
}
|
||||
|
||||
const placeholders = ids.map(() => '?').join(',')
|
||||
const projectRows = this.db.prepare(
|
||||
`SELECT id FROM memories WHERE id IN (${placeholders}) AND project_id = ?`
|
||||
).all(...ids, projectId) as Array<{ id: number }>
|
||||
const validIds = new Set(projectRows.map(r => r.id))
|
||||
|
||||
const filtered = knnRows
|
||||
.filter(r => validIds.has(r.memory_id) && r.distance < threshold)
|
||||
.slice(0, limit)
|
||||
return { results: filtered.map(r => ({ memoryId: r.memory_id, distance: r.distance })) }
|
||||
}
|
||||
|
||||
case 'count': {
|
||||
@@ -220,6 +270,99 @@ class VecWorker {
|
||||
return { count: row.count }
|
||||
}
|
||||
|
||||
case 'countWithoutEmbeddings': {
|
||||
const projectId = req.projectId as string | undefined
|
||||
const embeddingsTableExists = this.db.prepare(
|
||||
"SELECT name FROM sqlite_master WHERE type='table' AND name='memory_embeddings'"
|
||||
).get()
|
||||
|
||||
if (!embeddingsTableExists) {
|
||||
const conditions: string[] = []
|
||||
const params: (string | number)[] = []
|
||||
if (projectId) {
|
||||
conditions.push('project_id = ?')
|
||||
params.push(projectId)
|
||||
}
|
||||
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''
|
||||
const result = this.db.prepare(`SELECT COUNT(*) as count FROM memories ${where}`).get(...params) as { count: number }
|
||||
return { count: result.count }
|
||||
}
|
||||
|
||||
const conditions: string[] = ['e.memory_id IS NULL']
|
||||
const params: (string | number)[] = []
|
||||
if (projectId) {
|
||||
conditions.push('m.project_id = ?')
|
||||
params.push(projectId)
|
||||
}
|
||||
const result = this.db.prepare(`
|
||||
SELECT COUNT(*) as count
|
||||
FROM memories m
|
||||
LEFT JOIN memory_embeddings e ON m.id = e.memory_id
|
||||
WHERE ${conditions.join(' AND ')}
|
||||
`).get(...params) as { count: number }
|
||||
return { count: result.count }
|
||||
}
|
||||
|
||||
case 'getWithoutEmbeddings': {
|
||||
const projectId = req.projectId as string | undefined
|
||||
const limit = (req.limit as number) ?? 50
|
||||
const embeddingsTableExists = this.db.prepare(
|
||||
"SELECT name FROM sqlite_master WHERE type='table' AND name='memory_embeddings'"
|
||||
).get()
|
||||
|
||||
if (!embeddingsTableExists) {
|
||||
const conditions: string[] = []
|
||||
const params: (string | number)[] = []
|
||||
if (projectId) {
|
||||
conditions.push('project_id = ?')
|
||||
params.push(projectId)
|
||||
}
|
||||
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''
|
||||
const rows = this.db.prepare(`
|
||||
SELECT id, content FROM memories ${where} ORDER BY created_at ASC LIMIT ?
|
||||
`).all(...params, limit) as Array<{ id: number; content: string }>
|
||||
return { rows }
|
||||
}
|
||||
|
||||
const conditions: string[] = ['e.memory_id IS NULL']
|
||||
const params: (string | number)[] = []
|
||||
if (projectId) {
|
||||
conditions.push('m.project_id = ?')
|
||||
params.push(projectId)
|
||||
}
|
||||
const rows = this.db.prepare(`
|
||||
SELECT m.id, m.content
|
||||
FROM memories m
|
||||
LEFT JOIN memory_embeddings e ON m.id = e.memory_id
|
||||
WHERE ${conditions.join(' AND ')}
|
||||
ORDER BY m.created_at ASC
|
||||
LIMIT ?
|
||||
`).all(...params, limit) as Array<{ id: number; content: string }>
|
||||
return { rows }
|
||||
}
|
||||
|
||||
case 'recreateTable': {
|
||||
const dims = req.dimensions as number
|
||||
this.db.run('DROP TABLE IF EXISTS memory_embeddings')
|
||||
this.db.run(`
|
||||
CREATE VIRTUAL TABLE memory_embeddings USING vec0(
|
||||
embedding float[${dims}] distance_metric=cosine,
|
||||
+memory_id INTEGER,
|
||||
+project_id TEXT
|
||||
)
|
||||
`)
|
||||
return { status: 'ok' }
|
||||
}
|
||||
|
||||
case 'getDimensions': {
|
||||
const row = this.db.prepare(
|
||||
"SELECT sql FROM sqlite_master WHERE type='table' AND name='memory_embeddings'"
|
||||
).get() as { sql: string } | undefined
|
||||
if (!row) return { exists: false, dimensions: null }
|
||||
const match = row.sql.match(/float\[(\d+)\]/i)
|
||||
return { exists: true, dimensions: match ? parseInt(match[1]!, 10) : null }
|
||||
}
|
||||
|
||||
default:
|
||||
return { error: `Unknown action: ${req.action}` }
|
||||
}
|
||||
|
||||
@@ -1,40 +1,25 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { platform } from 'os'
|
||||
import { join } from 'path'
|
||||
import type { VecService } from './vec-types'
|
||||
import { createDirectVecService } from './vec-direct'
|
||||
import type { Logger } from '../types'
|
||||
|
||||
export type { VecService, VecSearchResult } from './vec-types'
|
||||
|
||||
export function initializeVecTables(db: Database, dimensions: number): void {
|
||||
const direct = createDirectVecService(db)
|
||||
if (direct.available) {
|
||||
direct.initialize(dimensions)
|
||||
}
|
||||
}
|
||||
|
||||
export async function createVecService(db: Database, dataDir: string, dimensions: number): Promise<VecService> {
|
||||
const direct = createDirectVecService(db)
|
||||
|
||||
if (direct.available) {
|
||||
await direct.initialize(dimensions)
|
||||
return direct
|
||||
}
|
||||
|
||||
if (platform() === 'darwin') {
|
||||
try {
|
||||
const { createWorkerVecService } = await import('./vec-client')
|
||||
const dbPath = join(dataDir, 'memory.db')
|
||||
const worker = await createWorkerVecService({ dbPath, dataDir, dimensions })
|
||||
if (worker.available) {
|
||||
await worker.initialize(dimensions)
|
||||
return worker
|
||||
}
|
||||
} catch {
|
||||
// Worker fallback unavailable
|
||||
export async function createVecService(_db: Database, dataDir: string, dimensions: number, logger?: Logger): Promise<VecService> {
|
||||
try {
|
||||
const { createWorkerVecService } = await import('./vec-client')
|
||||
const dbPath = join(dataDir, 'memory.db')
|
||||
const worker = await createWorkerVecService({ dbPath, dataDir, dimensions })
|
||||
if (worker.available) {
|
||||
await worker.initialize(dimensions)
|
||||
return worker
|
||||
}
|
||||
logger?.error('Vec worker started but not available')
|
||||
} catch (err) {
|
||||
logger?.error('Vec worker failed to start', err)
|
||||
}
|
||||
|
||||
logger?.log('Vec worker unavailable, using noop service')
|
||||
return createNoopVecService()
|
||||
}
|
||||
|
||||
@@ -48,6 +33,10 @@ export function createNoopVecService(): VecService {
|
||||
async deleteByMemoryIds() {},
|
||||
async search() { return [] },
|
||||
async findSimilar() { return [] },
|
||||
async countWithoutEmbeddings() { return 0 },
|
||||
async getWithoutEmbeddings() { return [] },
|
||||
async recreateTable() {},
|
||||
async getDimensions() { return { exists: false, dimensions: null } },
|
||||
dispose() {},
|
||||
}
|
||||
}
|
||||
@@ -50,11 +50,13 @@ export interface EmbeddingConfig {
|
||||
export interface LoggingConfig {
|
||||
enabled: boolean
|
||||
file: string
|
||||
debug?: boolean
|
||||
}
|
||||
|
||||
export interface Logger {
|
||||
log: (message: string, ...args: unknown[]) => void
|
||||
error: (message: string, ...args: unknown[]) => void
|
||||
debug: (message: string, ...args: unknown[]) => void
|
||||
}
|
||||
|
||||
export interface PluginConfig {
|
||||
@@ -63,6 +65,8 @@ export interface PluginConfig {
|
||||
dedupThreshold?: number
|
||||
logging?: LoggingConfig
|
||||
compaction?: CompactionConfig
|
||||
memoryInjection?: MemoryInjectionConfig
|
||||
messagesTransform?: MessagesTransformConfig
|
||||
executionModel?: string
|
||||
}
|
||||
|
||||
@@ -72,38 +76,23 @@ export interface ListMemoriesFilter {
|
||||
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 MemoryInjectionConfig {
|
||||
enabled?: boolean
|
||||
maxResults?: number
|
||||
distanceThreshold?: number
|
||||
maxTokens?: number
|
||||
cacheTtlMs?: number
|
||||
debug?: boolean
|
||||
}
|
||||
|
||||
export interface MessagesTransformConfig {
|
||||
enabled?: boolean
|
||||
debug?: boolean
|
||||
}
|
||||
|
||||
export interface HealthStatus {
|
||||
|
||||
@@ -26,21 +26,41 @@ function checkFileSize(filePath: string): void {
|
||||
}
|
||||
|
||||
export function createLogger(config: LoggingConfig) {
|
||||
if (!config.enabled) {
|
||||
const isEnabled = config.enabled
|
||||
const isDebug = config.debug ?? false
|
||||
|
||||
if (!isEnabled) {
|
||||
return {
|
||||
log: (_message: string, ..._args: unknown[]): void => {},
|
||||
error: (_message: string, ..._args: unknown[]): void => {},
|
||||
debug: (_message: string, ..._args: unknown[]): void => {},
|
||||
}
|
||||
}
|
||||
|
||||
const filePath = config.file
|
||||
ensureLogDir(filePath)
|
||||
|
||||
function formatArg(arg: unknown): string {
|
||||
if (arg === null) return 'null'
|
||||
if (arg === undefined) return 'undefined'
|
||||
if (arg instanceof Error) {
|
||||
return arg.stack ?? `${arg.name}: ${arg.message}`
|
||||
}
|
||||
if (typeof arg === 'object') {
|
||||
try {
|
||||
return JSON.stringify(arg)
|
||||
} catch {
|
||||
return String(arg)
|
||||
}
|
||||
}
|
||||
return String(arg)
|
||||
}
|
||||
|
||||
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 formattedArgs = args.length > 0 ? ' ' + args.map(formatArg).join(' ') : ''
|
||||
const line = `${timestamp} ${level} ${PREFIX} ${message}${formattedArgs}\n`
|
||||
|
||||
try {
|
||||
@@ -57,5 +77,10 @@ export function createLogger(config: LoggingConfig) {
|
||||
error: (message: string, ...args: unknown[]): void => {
|
||||
write('ERROR', message, args)
|
||||
},
|
||||
debug: isDebug
|
||||
? (message: string, ...args: unknown[]): void => {
|
||||
write('DEBUG', message, args)
|
||||
}
|
||||
: (_message: string, ..._args: unknown[]): void => {},
|
||||
}
|
||||
}
|
||||
@@ -1 +1 @@
|
||||
export const VERSION = '0.0.10'
|
||||
export const VERSION = '0.0.14'
|
||||
Reference in new issue
Block a user