mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
Add CLI export/import and bundled agents to memory plugin
This commit is contained in:
1 parent
60d999f858
commit
59465de475
6 files changed
+1312
-2
No files matched your search
@@ -0,0 +1,30 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [0.0.6] - 2026-02-24
|
||||
|
||||
### Added
|
||||
|
||||
- Core memory tools: `memory-read`, `memory-write`, `memory-edit`, `memory-delete`, `memory-health`
|
||||
- Planning state tools: `memory-planning-update` and `memory-planning-get` for tracking session objectives, phases, findings, and errors
|
||||
- `memory-plan-execute` tool for creating new Code sessions with approved implementation plans
|
||||
- Three embedding providers: local (`all-MiniLM-L6-v2`), OpenAI (`text-embedding-3-small/large`, `ada-002`), and Voyage (`voyage-code-3`, `voyage-2`)
|
||||
- Bundled Code agent (`ocm-code`) with memory-aware coding workflows
|
||||
- Bundled Architect agent (`ocm-architect`) for read-only planning with automatic plan handoff
|
||||
- Bundled Memory agent (`ocm-memory`) for expert knowledge curation and post-compaction extraction
|
||||
- Compaction context injection with custom prompt, planning state, conventions, and decisions
|
||||
- Configurable compaction settings: custom prompt, inline planning, token budget, snapshot storage
|
||||
- CLI export/import for backing up and migrating memories as JSON or Markdown
|
||||
- Embedding cache with SHA-256 keying and 24-hour TTL
|
||||
- Embedding sync service with batch processing and retry logic
|
||||
- Session state KV store with TTL management (7-day planning, 24-hour snapshots)
|
||||
- Automatic deduplication via exact match and semantic similarity detection
|
||||
- Dimension mismatch detection on startup with guided recovery via reindex
|
||||
- Build-time version injection displayed in `memory-health` output
|
||||
- Automatic model download via `postinstall` script
|
||||
- Auto-copy of bundled config on first run
|
||||
- SQLite storage with `sqlite-vec` for vector similarity search
|
||||
@@ -6,8 +6,12 @@ Memory management plugin for OpenCode that enables semantic search and persisten
|
||||
|
||||
- **Semantic Memory Search** - Store and retrieve project memories using vector embeddings
|
||||
- **Multiple Memory Scopes** - Categorize memories as convention, decision, or context
|
||||
- **Automatic Deduplication** - Prevents duplicate memories from being stored
|
||||
- **Session Context** - Tracks session state and injects relevant memories during compaction
|
||||
- **Automatic Deduplication** - Prevents duplicates via exact match and semantic similarity detection
|
||||
- **Compaction Context Injection** - Injects planning state, conventions, and decisions into session compaction for seamless continuity
|
||||
- **Bundled Agents** - Ships with Code, Architect, and Memory agents preconfigured for memory-aware workflows
|
||||
- **CLI Export/Import** - Export and import memories as JSON or Markdown for backup and migration
|
||||
- **Dimension Mismatch Detection** - Detects embedding model changes and guides recovery via reindex
|
||||
- **Session Planning** - Tracks objectives, phases, findings, and errors across sessions with automatic TTL cleanup
|
||||
|
||||
## Tools
|
||||
|
||||
@@ -20,9 +24,76 @@ Memory management plugin for OpenCode that enables semantic search and persisten
|
||||
| `memory-health` | Health check or full reindex of the memory store |
|
||||
| `memory-planning-update` | Update session planning state (phases, objectives, progress) |
|
||||
| `memory-planning-get` | Get the current planning state for a session |
|
||||
| `memory-plan-execute` | Create a new Code session and send an approved plan as the first prompt |
|
||||
|
||||
Planning state differs from memories: it stores temporary session data (objectives, phase progress, findings, errors) with a 7-day TTL, while memories are persisted indefinitely and retrieved via semantic search.
|
||||
|
||||
## Agents
|
||||
|
||||
The plugin bundles three agents that integrate with the memory system:
|
||||
|
||||
| Agent | ID | Mode | Description |
|
||||
|-------|----|------|-------------|
|
||||
| **Code** | `ocm-code` | primary | Primary coding agent with memory awareness. Checks memory before unfamiliar code, stores architectural decisions and conventions as it works. |
|
||||
| **Architect** | `ocm-architect` | primary | Read-only planning agent. Researches the codebase, checks memory for conventions and decisions, designs implementation plans, then hands off to Code via `memory-plan-execute`. |
|
||||
| **Memory** | `ocm-memory` | subagent | Expert agent for storing, retrieving, and curating project knowledge. Handles post-compaction memory extraction and contradiction resolution. |
|
||||
|
||||
The Architect agent operates in read-only mode (`temperature: 0.0`, all edits denied). After the user approves a plan, it calls `memory-plan-execute` to create a new Code session with the full plan as context.
|
||||
|
||||
## CLI
|
||||
|
||||
Export and import memories using the bundled CLI tool. The CLI auto-detects the project ID from git and resolves the database path automatically.
|
||||
|
||||
### Export
|
||||
|
||||
```bash
|
||||
# Export all memories as JSON (stdout)
|
||||
bun run src/cli/export.ts export
|
||||
|
||||
# Export as Markdown to file
|
||||
bun run src/cli/export.ts export --format markdown --output memories.md
|
||||
|
||||
# Export with project and scope filter
|
||||
bun run src/cli/export.ts export --project my-project --scope convention
|
||||
|
||||
# Limit and paginate results
|
||||
bun run src/cli/export.ts export --limit 50 --offset 100
|
||||
```
|
||||
|
||||
**Export options:**
|
||||
|
||||
| Flag | Description |
|
||||
|------|-------------|
|
||||
| `--format, -f` | Output format: `json` or `markdown` (default: `json`) |
|
||||
| `--output, -o` | Output file path (prints to stdout if omitted) |
|
||||
| `--project, -p` | Project ID filter (auto-detected from git) |
|
||||
| `--scope, -s` | Filter by scope: `convention`, `decision`, or `context` |
|
||||
| `--limit, -l` | Max number of memories (default: `1000`) |
|
||||
| `--offset` | Pagination offset (default: `0`) |
|
||||
| `--db-path` | Custom database file path |
|
||||
|
||||
### Import
|
||||
|
||||
```bash
|
||||
# Import from JSON
|
||||
bun run src/cli/export.ts import memories.json --project my-project
|
||||
|
||||
# Import from Markdown (format auto-detected from extension)
|
||||
bun run src/cli/export.ts import memories.md --project my-project
|
||||
|
||||
# Skip duplicate detection
|
||||
bun run src/cli/export.ts import memories.json --project my-project --force
|
||||
```
|
||||
|
||||
**Import options:**
|
||||
|
||||
| Flag | Description |
|
||||
|------|-------------|
|
||||
| `--format, -f` | Input format: `json` or `markdown` (auto-detected from extension) |
|
||||
| `--project, -p` | Project ID to assign memories to (auto-detected from git) |
|
||||
| `--force` | Skip duplicate detection and import all |
|
||||
| `--db-path` | Custom database file path |
|
||||
|
||||
## Installation
|
||||
|
||||
Install the package from npm:
|
||||
@@ -63,6 +134,12 @@ You can edit this file to customize settings. The file is created only if it doe
|
||||
"logging": {
|
||||
"enabled": false,
|
||||
"file": "~/.local/share/opencode/memory/logs/memory.log"
|
||||
},
|
||||
"compaction": {
|
||||
"customPrompt": true,
|
||||
"inlinePlanning": true,
|
||||
"maxContextTokens": 4000,
|
||||
"snapshotToKV": true
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -101,6 +178,12 @@ For API-based embeddings:
|
||||
|
||||
When enabled, logs are written to the specified file with timestamps. The log file has a 10MB size limit with automatic rotation.
|
||||
|
||||
#### Compaction
|
||||
- `compaction.customPrompt` - Use a custom compaction prompt optimized for session continuity (default: `true`)
|
||||
- `compaction.inlinePlanning` - Inject planning state (phases, objectives, progress) into compaction context (default: `true`)
|
||||
- `compaction.maxContextTokens` - Token budget for injected memory context with priority-based trimming (default: `4000`)
|
||||
- `compaction.snapshotToKV` - Store compaction snapshots in the session KV store for recovery (default: `true`)
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
|
||||
@@ -6,6 +6,9 @@ export const codeAgent: AgentDefinition = {
|
||||
displayName: 'Code',
|
||||
description: 'Primary coding agent with awareness of project memory and conventions',
|
||||
mode: 'primary',
|
||||
tools: {
|
||||
exclude: ['memory-plan-execute'],
|
||||
},
|
||||
systemPrompt: `You are a coding agent with access to a persistent memory system that stores project conventions, architectural decisions, and contextual knowledge across sessions.
|
||||
|
||||
## Memory Integration
|
||||
|
||||
@@ -6,6 +6,9 @@ export const memoryAgent: AgentDefinition = {
|
||||
displayName: 'Memory',
|
||||
description: 'Expert agent for managing project memory - storing and retrieving conventions, decisions, and context',
|
||||
mode: 'subagent',
|
||||
tools: {
|
||||
exclude: ['memory-plan-execute'],
|
||||
},
|
||||
systemPrompt: `You are the project's institutional memory. Your purpose is to capture, organize, and retrieve knowledge that persists across sessions.
|
||||
|
||||
## Your Role
|
||||
|
||||
@@ -0,0 +1,667 @@
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { existsSync } from 'fs'
|
||||
import { homedir, platform } from 'os'
|
||||
import { join, extname } from 'path'
|
||||
import { readFileSync } from 'fs'
|
||||
import { writeFileSync } from 'fs'
|
||||
import { execSync } from 'child_process'
|
||||
|
||||
type MemoryScope = 'convention' | 'decision' | 'context'
|
||||
|
||||
interface PluginMemory {
|
||||
id: number
|
||||
projectId: string
|
||||
scope: MemoryScope
|
||||
content: string
|
||||
filePath: string | null
|
||||
accessCount: number
|
||||
lastAccessedAt: number | null
|
||||
createdAt: number
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
interface ExportOptions {
|
||||
format?: 'json' | 'markdown'
|
||||
output?: string
|
||||
projectId?: string
|
||||
scope?: MemoryScope
|
||||
limit?: number
|
||||
offset?: number
|
||||
dbPath?: string
|
||||
}
|
||||
|
||||
interface ImportOptions {
|
||||
format?: 'json' | 'markdown'
|
||||
projectId: string
|
||||
force?: boolean
|
||||
dbPath?: string
|
||||
}
|
||||
|
||||
function resolveDefaultDbPath(): string {
|
||||
const localPath = join(process.cwd(), '.opencode', 'state', 'opencode', 'memory', 'memory.db')
|
||||
if (existsSync(localPath)) {
|
||||
return localPath
|
||||
}
|
||||
|
||||
const defaultBase = join(homedir(), platform() === 'win32' ? 'AppData' : '.local', 'share')
|
||||
const xdgDataHome = process.env['XDG_DATA_HOME'] || defaultBase
|
||||
const dataDir = join(xdgDataHome, 'opencode', 'memory')
|
||||
return join(dataDir, 'memory.db')
|
||||
}
|
||||
|
||||
function getGitProjectId(): string | null {
|
||||
try {
|
||||
const repoRoot = execSync('git rev-parse --show-toplevel', { encoding: 'utf-8' }).trim()
|
||||
if (!repoRoot) return null
|
||||
|
||||
const repoName = repoRoot.split('/').pop() ?? null
|
||||
if (repoName) return repoName
|
||||
|
||||
try {
|
||||
const remoteUrl = execSync('git remote get-url origin', { encoding: 'utf-8' }).trim()
|
||||
const match = remoteUrl.match(/[:/]([^/.]+)\.git$/)
|
||||
if (match) return match[1]
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
|
||||
return null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function groupBy<T>(arr: T[], keyFn: (item: T) => string): Record<string, T[]> {
|
||||
return arr.reduce((acc, item) => {
|
||||
const key = keyFn(item)
|
||||
if (!acc[key]) acc[key] = []
|
||||
acc[key].push(item)
|
||||
return acc
|
||||
}, {} as Record<string, T[]>)
|
||||
}
|
||||
|
||||
function capitalize(str: string): string {
|
||||
return str.charAt(0).toUpperCase() + str.slice(1)
|
||||
}
|
||||
|
||||
export function formatAsJson(memories: PluginMemory[]): string {
|
||||
return JSON.stringify(memories, null, 2)
|
||||
}
|
||||
|
||||
export function formatAsMarkdown(memories: PluginMemory[]): string {
|
||||
const byScope = groupBy(memories, (m) => m.scope)
|
||||
const lines = [
|
||||
'# Memory Export',
|
||||
'',
|
||||
`Exported on ${new Date().toISOString().split('T')[0]}`,
|
||||
'',
|
||||
]
|
||||
|
||||
for (const scope of ['convention', 'decision', 'context'] as const) {
|
||||
const items = byScope[scope] || []
|
||||
if (items.length === 0) continue
|
||||
|
||||
lines.push(`## ${capitalize(scope)}s (${items.length})`, '')
|
||||
|
||||
for (const m of items) {
|
||||
lines.push(
|
||||
`### [${m.id}] - Created ${new Date(m.createdAt).toISOString().split('T')[0]}`,
|
||||
'',
|
||||
m.content,
|
||||
''
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return lines.join('\n')
|
||||
}
|
||||
|
||||
export function parseJsonImport(content: string, projectId: string): PluginMemory[] {
|
||||
const data = JSON.parse(content)
|
||||
if (!Array.isArray(data)) {
|
||||
throw new Error('Invalid JSON format: expected array of memories')
|
||||
}
|
||||
|
||||
const now = Date.now()
|
||||
return data.map((item: Record<string, unknown>, index: number) => ({
|
||||
id: 0,
|
||||
projectId: (item.projectId as string) || projectId,
|
||||
scope: (item.scope as MemoryScope) || 'context',
|
||||
content: item.content as string,
|
||||
filePath: (item.filePath as string) || null,
|
||||
accessCount: 0,
|
||||
lastAccessedAt: null,
|
||||
createdAt: (item.createdAt as number) || now,
|
||||
updatedAt: (item.updatedAt as number) || now,
|
||||
}))
|
||||
}
|
||||
|
||||
export function parseMarkdownImport(content: string, projectId: string): PluginMemory[] {
|
||||
const memories: PluginMemory[] = []
|
||||
const lines = content.split('\n')
|
||||
let currentScope: MemoryScope = 'context'
|
||||
let currentContent: string[] = []
|
||||
let currentCreatedAt = Date.now()
|
||||
let memoryIndex = 0
|
||||
|
||||
const scopePattern = /^##\s+(\w+)(?:s)?\s+\(\d+\)$/i
|
||||
const memoryPattern = /^###\s+\[(\d+)\]\s+-\s+Created\s+(\d{4}-\d{2}-\d{2})/
|
||||
|
||||
function saveCurrentMemory() {
|
||||
if (currentContent.length > 0) {
|
||||
const contentStr = currentContent.join('\n').trim()
|
||||
if (contentStr) {
|
||||
memories.push({
|
||||
id: 0,
|
||||
projectId,
|
||||
scope: currentScope,
|
||||
content: contentStr,
|
||||
filePath: null,
|
||||
accessCount: 0,
|
||||
lastAccessedAt: null,
|
||||
createdAt: currentCreatedAt,
|
||||
updatedAt: currentCreatedAt,
|
||||
})
|
||||
}
|
||||
currentContent = []
|
||||
}
|
||||
}
|
||||
|
||||
for (const line of lines) {
|
||||
const scopeMatch = line.match(scopePattern)
|
||||
if (scopeMatch) {
|
||||
saveCurrentMemory()
|
||||
const scopeStr = scopeMatch[1].toLowerCase()
|
||||
if (scopeStr.startsWith('convention')) {
|
||||
currentScope = 'convention'
|
||||
} else if (scopeStr.startsWith('decision')) {
|
||||
currentScope = 'decision'
|
||||
} else {
|
||||
currentScope = 'context'
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
const memoryMatch = line.match(memoryPattern)
|
||||
if (memoryMatch) {
|
||||
saveCurrentMemory()
|
||||
memoryIndex++
|
||||
try {
|
||||
currentCreatedAt = new Date(memoryMatch[2]).getTime()
|
||||
} catch {
|
||||
currentCreatedAt = Date.now()
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if (line.startsWith('#') && !line.startsWith('##')) {
|
||||
continue
|
||||
}
|
||||
|
||||
if (line.trim() || currentContent.length > 0) {
|
||||
currentContent.push(line)
|
||||
}
|
||||
}
|
||||
|
||||
saveCurrentMemory()
|
||||
|
||||
if (memories.length === 0 && content.trim()) {
|
||||
const fallbackContent = content
|
||||
.replace(/^#.*$/gm, '')
|
||||
.replace(/^##.*$/gm, '')
|
||||
.replace(/^###.*$/gm, '')
|
||||
.trim()
|
||||
|
||||
if (fallbackContent) {
|
||||
memories.push({
|
||||
id: 0,
|
||||
projectId,
|
||||
scope: 'context',
|
||||
content: fallbackContent,
|
||||
filePath: null,
|
||||
accessCount: 0,
|
||||
lastAccessedAt: null,
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return memories
|
||||
}
|
||||
|
||||
function exportMemories(options: ExportOptions): void {
|
||||
let dbPath = options.dbPath || resolveDefaultDbPath()
|
||||
|
||||
if (!existsSync(dbPath)) {
|
||||
console.error(`Database not found at ${dbPath}. Run OpenCode first to initialize memories.`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const db = new Database(dbPath)
|
||||
|
||||
try {
|
||||
const gitProjectId = getGitProjectId()
|
||||
const projectId = options.projectId || gitProjectId
|
||||
|
||||
if (!projectId) {
|
||||
console.error('Project ID required. Use --project or ensure this is a git repository.')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const conditions: string[] = ['project_id = ?']
|
||||
const params: (string | number)[] = [projectId]
|
||||
|
||||
if (options.scope) {
|
||||
conditions.push('scope = ?')
|
||||
params.push(options.scope)
|
||||
}
|
||||
|
||||
const limit = options.limit ?? 1000
|
||||
const offset = options.offset ?? 0
|
||||
|
||||
const query = `
|
||||
SELECT id, project_id, scope, content, file_path, access_count, last_accessed_at, created_at, updated_at
|
||||
FROM memories
|
||||
WHERE ${conditions.join(' AND ')}
|
||||
ORDER BY updated_at DESC
|
||||
LIMIT ? OFFSET ?
|
||||
`
|
||||
|
||||
const rows = db.prepare(query).all(...params, limit, offset) as Array<{
|
||||
id: number
|
||||
project_id: string
|
||||
scope: string
|
||||
content: string
|
||||
file_path: string | null
|
||||
access_count: number
|
||||
last_accessed_at: number | null
|
||||
created_at: number
|
||||
updated_at: number
|
||||
}>
|
||||
|
||||
const memories: PluginMemory[] = rows.map((row) => ({
|
||||
id: row.id,
|
||||
projectId: row.project_id,
|
||||
scope: row.scope as MemoryScope,
|
||||
content: row.content,
|
||||
filePath: row.file_path,
|
||||
accessCount: row.access_count,
|
||||
lastAccessedAt: row.last_accessed_at,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
}))
|
||||
|
||||
const format = options.format || 'json'
|
||||
let output: string
|
||||
|
||||
if (format === 'markdown') {
|
||||
output = formatAsMarkdown(memories)
|
||||
} else {
|
||||
output = formatAsJson(memories)
|
||||
}
|
||||
|
||||
if (options.output) {
|
||||
writeFileSync(options.output, output, 'utf-8')
|
||||
console.log(`Exported ${memories.length} memories to ${options.output}`)
|
||||
} else {
|
||||
console.log(output)
|
||||
}
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
}
|
||||
|
||||
function importMemories(filePath: string, options: ImportOptions): void {
|
||||
let dbPath = options.dbPath || resolveDefaultDbPath()
|
||||
|
||||
if (!existsSync(dbPath)) {
|
||||
console.error(`Database not found at ${dbPath}. Run OpenCode first to initialize memories.`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
let content: string
|
||||
|
||||
try {
|
||||
content = readFileSync(filePath, 'utf-8')
|
||||
} catch {
|
||||
console.error(`Failed to read file: ${filePath}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const format = options.format || (extname(filePath).toLowerCase() === '.md' ? 'markdown' : 'json')
|
||||
|
||||
let memories: PluginMemory[]
|
||||
|
||||
try {
|
||||
if (format === 'markdown') {
|
||||
memories = parseMarkdownImport(content, options.projectId)
|
||||
} else {
|
||||
memories = parseJsonImport(content, options.projectId)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Failed to parse ${format} file: ${error instanceof Error ? error.message : 'Unknown error'}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (memories.length === 0) {
|
||||
console.log('No memories found to import.')
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const db = new Database(dbPath)
|
||||
|
||||
try {
|
||||
let importedCount = 0
|
||||
let skippedCount = 0
|
||||
|
||||
for (const memory of memories) {
|
||||
memory.projectId = options.projectId
|
||||
|
||||
if (!options.force) {
|
||||
const existing = db
|
||||
.prepare('SELECT id FROM memories WHERE project_id = ? AND content = ? LIMIT 1')
|
||||
.get(options.projectId, memory.content)
|
||||
|
||||
if (existing) {
|
||||
skippedCount++
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
const now = Date.now()
|
||||
const result = db
|
||||
.prepare(
|
||||
'INSERT INTO memories (project_id, scope, content, file_path, access_count, last_accessed_at, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
|
||||
)
|
||||
.run(
|
||||
memory.projectId,
|
||||
memory.scope,
|
||||
memory.content,
|
||||
memory.filePath,
|
||||
0,
|
||||
null,
|
||||
memory.createdAt || now,
|
||||
memory.updatedAt || now
|
||||
)
|
||||
|
||||
importedCount++
|
||||
}
|
||||
|
||||
console.log(`Import complete: ${importedCount} imported, ${skippedCount} skipped`)
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
}
|
||||
|
||||
function parseArgs(args: string[]): { command: string; options: ExportOptions | ImportOptions; filePath?: string } {
|
||||
const command = args[0] || 'export'
|
||||
const remaining = args.slice(1)
|
||||
|
||||
if (command === 'export') {
|
||||
const options: ExportOptions = {}
|
||||
let i = 0
|
||||
|
||||
while (i < remaining.length) {
|
||||
const arg = remaining[i]
|
||||
|
||||
if (arg === '--format' || arg === '-f') {
|
||||
const format = remaining[++i] as 'json' | 'markdown'
|
||||
if (format !== 'json' && format !== 'markdown') {
|
||||
console.error(`Unknown format '${format}'. Use 'json' or 'markdown'.`)
|
||||
process.exit(1)
|
||||
}
|
||||
options.format = format
|
||||
} else if (arg === '--output' || arg === '-o') {
|
||||
options.output = remaining[++i]
|
||||
} else if (arg === '--project' || arg === '-p') {
|
||||
options.projectId = remaining[++i]
|
||||
} else if (arg === '--scope' || arg === '-s') {
|
||||
const scope = remaining[++i] as MemoryScope
|
||||
if (scope !== 'convention' && scope !== 'decision' && scope !== 'context') {
|
||||
console.error(`Unknown scope '${scope}'. Use 'convention', 'decision', or 'context'.`)
|
||||
process.exit(1)
|
||||
}
|
||||
options.scope = scope
|
||||
} else if (arg === '--limit' || arg === '-l') {
|
||||
options.limit = parseInt(remaining[++i], 10)
|
||||
if (isNaN(options.limit)) {
|
||||
console.error('Invalid limit value')
|
||||
process.exit(1)
|
||||
}
|
||||
} else if (arg === '--offset') {
|
||||
options.offset = parseInt(remaining[++i], 10)
|
||||
if (isNaN(options.offset ?? 0)) {
|
||||
console.error('Invalid offset value')
|
||||
process.exit(1)
|
||||
}
|
||||
} else if (arg === '--db-path') {
|
||||
options.dbPath = remaining[++i]
|
||||
} else if (arg === '--help' || arg === '-h') {
|
||||
printExportHelp()
|
||||
process.exit(0)
|
||||
} else {
|
||||
console.error(`Unknown option: ${arg}`)
|
||||
printExportHelp()
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
i++
|
||||
}
|
||||
|
||||
return { command: 'export', options }
|
||||
}
|
||||
|
||||
if (command === 'import') {
|
||||
const options: ImportOptions = { projectId: '' }
|
||||
let filePath = remaining[0]
|
||||
let i = 1
|
||||
|
||||
if (!filePath || filePath.startsWith('-')) {
|
||||
console.error('Import requires a file path')
|
||||
printImportHelp()
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (filePath === '-') {
|
||||
filePath = '/dev/stdin'
|
||||
}
|
||||
|
||||
while (i < remaining.length) {
|
||||
const arg = remaining[i]
|
||||
|
||||
if (arg === '--format' || arg === '-f') {
|
||||
const format = remaining[++i] as 'json' | 'markdown'
|
||||
if (format !== 'json' && format !== 'markdown') {
|
||||
console.error(`Unknown format '${format}'. Use 'json' or 'markdown'.`)
|
||||
process.exit(1)
|
||||
}
|
||||
options.format = format
|
||||
} else if (arg === '--project' || arg === '-p') {
|
||||
options.projectId = remaining[++i]
|
||||
} else if (arg === '--force') {
|
||||
options.force = true
|
||||
} else if (arg === '--db-path') {
|
||||
options.dbPath = remaining[++i]
|
||||
} else if (arg === '--help' || arg === '-h') {
|
||||
printImportHelp()
|
||||
process.exit(0)
|
||||
} else {
|
||||
console.error(`Unknown option: ${arg}`)
|
||||
printImportHelp()
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
i++
|
||||
}
|
||||
|
||||
if (!options.projectId) {
|
||||
options.projectId = getGitProjectId() || ''
|
||||
}
|
||||
|
||||
if (!options.projectId) {
|
||||
console.error('Project ID required. Use --project or ensure this is a git repository.')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
return { command: 'import', options, filePath }
|
||||
}
|
||||
|
||||
if (command === '--help' || command === '-h' || command === 'help') {
|
||||
printHelp()
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const exportOptions: ExportOptions = {}
|
||||
let i = 0
|
||||
|
||||
while (i < args.length) {
|
||||
const arg = args[i]
|
||||
|
||||
if (arg === '--format' || arg === '-f') {
|
||||
const format = args[++i] as 'json' | 'markdown'
|
||||
if (format !== 'json' && format !== 'markdown') {
|
||||
console.error(`Unknown format '${format}'. Use 'json' or 'markdown'.`)
|
||||
process.exit(1)
|
||||
}
|
||||
exportOptions.format = format
|
||||
} else if (arg === '--output' || arg === '-o') {
|
||||
exportOptions.output = args[++i]
|
||||
} else if (arg === '--project' || arg === '-p') {
|
||||
exportOptions.projectId = args[++i]
|
||||
} else if (arg === '--scope' || arg === '-s') {
|
||||
const scope = args[++i] as MemoryScope
|
||||
if (scope !== 'convention' && scope !== 'decision' && scope !== 'context') {
|
||||
console.error(`Unknown scope '${scope}'. Use 'convention', 'decision', or 'context'.`)
|
||||
process.exit(1)
|
||||
}
|
||||
exportOptions.scope = scope
|
||||
} else if (arg === '--limit' || arg === '-l') {
|
||||
exportOptions.limit = parseInt(args[++i], 10)
|
||||
if (isNaN(exportOptions.limit ?? 0)) {
|
||||
console.error('Invalid limit value')
|
||||
process.exit(1)
|
||||
}
|
||||
} else if (arg === '--offset') {
|
||||
exportOptions.offset = parseInt(args[++i], 10)
|
||||
if (isNaN(exportOptions.offset ?? 0)) {
|
||||
console.error('Invalid offset value')
|
||||
process.exit(1)
|
||||
}
|
||||
} else if (arg === '--db-path') {
|
||||
exportOptions.dbPath = args[++i]
|
||||
}
|
||||
|
||||
i++
|
||||
}
|
||||
|
||||
return { command: 'export', options: exportOptions }
|
||||
}
|
||||
|
||||
function printHelp(): void {
|
||||
console.log(`
|
||||
OpenCode Memory CLI
|
||||
|
||||
Usage:
|
||||
bun run src/cli/export.ts <command> [options]
|
||||
|
||||
Commands:
|
||||
export Export memories from database (default)
|
||||
import Import memories into database
|
||||
|
||||
Examples:
|
||||
# Export all memories as markdown (to stdout)
|
||||
bun run src/cli/export.ts export
|
||||
|
||||
# Export as JSON to file
|
||||
bun run src/cli/export.ts export --format json --output memories.json
|
||||
|
||||
# Export with project filter
|
||||
bun run src/cli/export.ts export --project my-project --scope convention
|
||||
|
||||
# Import from JSON
|
||||
bun run src/cli/export.ts import memories.json --project my-project
|
||||
|
||||
# Import from Markdown
|
||||
bun run src/cli/export.ts import memories.md --project my-project
|
||||
|
||||
# Import with force (skip duplicate detection)
|
||||
bun run src/cli/export.ts import memories.json --project my-project --force
|
||||
|
||||
Run 'bun run src/cli/export.ts <command> --help' for more information on a command.
|
||||
`.trim())
|
||||
}
|
||||
|
||||
function printExportHelp(): void {
|
||||
console.log(`
|
||||
Export memories from the database
|
||||
|
||||
Usage:
|
||||
bun run src/cli/export.ts export [options]
|
||||
|
||||
Options:
|
||||
--format, -f <format> Output format: json or markdown (default: json)
|
||||
--output, -o <file> Output file path (prints to stdout if not specified)
|
||||
--project, -p <id> Project ID to filter by (auto-detected from git if not provided)
|
||||
--scope, -s <scope> Filter by scope: convention, decision, or context
|
||||
--limit, -l <n> Limit number of memories (default: 1000)
|
||||
--offset <n> Offset for pagination (default: 0)
|
||||
--db-path <path> Path to database file
|
||||
--help, -h Show this help message
|
||||
`.trim())
|
||||
}
|
||||
|
||||
function printImportHelp(): void {
|
||||
console.log(`
|
||||
Import memories into the database
|
||||
|
||||
Usage:
|
||||
bun run src/cli/export.ts import <file> [options]
|
||||
|
||||
Arguments:
|
||||
<file> Input file path (use '-' for stdin)
|
||||
|
||||
Options:
|
||||
--format, -f <format> Input format: json or markdown (auto-detected from extension)
|
||||
--project, -p <id> Project ID to assign memories to (required, auto-detected from git)
|
||||
--force Skip duplicate detection and import all memories
|
||||
--db-path <path> Path to database file
|
||||
--help, -h Show this help message
|
||||
`.trim())
|
||||
}
|
||||
|
||||
function runCli(): void {
|
||||
const [cmd, ...args] = process.argv.slice(2)
|
||||
|
||||
if (!cmd || cmd === 'help') {
|
||||
printHelp()
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
if (cmd === 'export' || cmd === 'import') {
|
||||
const parsed = parseArgs([cmd, ...args])
|
||||
const { command, options, filePath } = parsed
|
||||
|
||||
if (command === 'export') {
|
||||
exportMemories(options as ExportOptions)
|
||||
} else if (filePath) {
|
||||
importMemories(filePath, options as ImportOptions)
|
||||
}
|
||||
} else if (cmd === '--help' || cmd === '-h') {
|
||||
printHelp()
|
||||
process.exit(0)
|
||||
} else {
|
||||
const parsed = parseArgs([cmd, ...args])
|
||||
const { command: defaultCommand, options: exportOptions } = parsed
|
||||
|
||||
if (defaultCommand === 'export') {
|
||||
exportMemories(exportOptions as ExportOptions)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const isMain = typeof import.meta.url === `file://${process.argv[1]}`.replace(/\\/g, '/') || process.argv[1]?.includes('export.ts')
|
||||
|
||||
if (isMain || process.argv[1]?.endsWith('export.ts')) {
|
||||
runCli()
|
||||
}
|
||||
@@ -0,0 +1,524 @@
|
||||
import { describe, test, expect, beforeEach, afterEach } from 'bun:test'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { writeFileSync, existsSync } from 'fs'
|
||||
import { join } from 'path'
|
||||
import { mkdtempSync, rmSync } from 'fs'
|
||||
|
||||
const TEST_PROJECT_ID = 'test-project-cli'
|
||||
|
||||
interface PluginMemory {
|
||||
id: number
|
||||
projectId: string
|
||||
scope: 'convention' | 'decision' | 'context'
|
||||
content: string
|
||||
filePath: string | null
|
||||
accessCount: number
|
||||
lastAccessedAt: number | null
|
||||
createdAt: number
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
function createTestDb(tempDir: string): Database {
|
||||
const dbPath = join(tempDir, 'memory.db')
|
||||
const db = new Database(dbPath)
|
||||
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS memories (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
project_id TEXT NOT NULL,
|
||||
scope TEXT NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
file_path TEXT,
|
||||
access_count INTEGER NOT NULL DEFAULT 0,
|
||||
last_accessed_at INTEGER,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
)
|
||||
`)
|
||||
|
||||
db.run(`CREATE INDEX IF NOT EXISTS idx_memories_project_id ON memories(project_id)`)
|
||||
db.run(`CREATE INDEX IF NOT EXISTS idx_memories_scope ON memories(scope)`)
|
||||
|
||||
return db
|
||||
}
|
||||
|
||||
function insertTestMemories(db: Database, projectId: string): void {
|
||||
const now = Date.now()
|
||||
db.run(
|
||||
'INSERT INTO memories (project_id, scope, content, file_path, access_count, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||||
[projectId, 'convention', 'Use TypeScript for all new code', null, 0, now, now]
|
||||
)
|
||||
db.run(
|
||||
'INSERT INTO memories (project_id, scope, content, file_path, access_count, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||||
[projectId, 'decision', 'Chose Bun as runtime for performance', null, 0, now - 1000, now - 1000]
|
||||
)
|
||||
db.run(
|
||||
'INSERT INTO memories (project_id, scope, content, file_path, access_count, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||||
[projectId, 'context', 'Project started in 2024', null, 0, now - 2000, now - 2000]
|
||||
)
|
||||
}
|
||||
|
||||
describe('CLI Export - formatAsJson', () => {
|
||||
let tempDir: string
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = mkdtempSync(join('.', 'temp-cli-test-'))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
if (existsSync(tempDir)) {
|
||||
rmSync(tempDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test('exports formatAsJson function', async () => {
|
||||
const { formatAsJson } = await import('../src/cli/export.ts')
|
||||
expect(typeof formatAsJson).toBe('function')
|
||||
})
|
||||
|
||||
test('formatAsJson converts memories to valid JSON', async () => {
|
||||
const { formatAsJson } = await import('../src/cli/export.ts')
|
||||
|
||||
const memories: PluginMemory[] = [
|
||||
{
|
||||
id: 1,
|
||||
projectId: TEST_PROJECT_ID,
|
||||
scope: 'convention',
|
||||
content: 'Test memory content',
|
||||
filePath: null,
|
||||
accessCount: 0,
|
||||
lastAccessedAt: null,
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
},
|
||||
]
|
||||
|
||||
const jsonOutput = formatAsJson(memories)
|
||||
const parsed = JSON.parse(jsonOutput)
|
||||
|
||||
expect(parsed).toHaveLength(1)
|
||||
expect(parsed[0].content).toBe('Test memory content')
|
||||
expect(parsed[0].projectId).toBe(TEST_PROJECT_ID)
|
||||
expect(parsed[0].scope).toBe('convention')
|
||||
})
|
||||
|
||||
test('formatAsJson handles empty array', async () => {
|
||||
const { formatAsJson } = await import('../src/cli/export.ts')
|
||||
|
||||
const jsonOutput = formatAsJson([])
|
||||
const parsed = JSON.parse(jsonOutput)
|
||||
|
||||
expect(parsed).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('CLI Export - formatAsMarkdown', () => {
|
||||
let tempDir: string
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = mkdtempSync(join('.', 'temp-cli-test-'))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
if (existsSync(tempDir)) {
|
||||
rmSync(tempDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test('exports formatAsMarkdown function', async () => {
|
||||
const { formatAsMarkdown } = await import('../src/cli/export.ts')
|
||||
expect(typeof formatAsMarkdown).toBe('function')
|
||||
})
|
||||
|
||||
test('formatAsMarkdown generates markdown with sections by scope', async () => {
|
||||
const { formatAsMarkdown } = await import('../src/cli/export.ts')
|
||||
|
||||
const memories: PluginMemory[] = [
|
||||
{
|
||||
id: 1,
|
||||
projectId: TEST_PROJECT_ID,
|
||||
scope: 'convention',
|
||||
content: 'Use TypeScript for all new code',
|
||||
filePath: null,
|
||||
accessCount: 0,
|
||||
lastAccessedAt: null,
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
projectId: TEST_PROJECT_ID,
|
||||
scope: 'decision',
|
||||
content: 'Chose Bun as runtime for performance',
|
||||
filePath: null,
|
||||
accessCount: 0,
|
||||
lastAccessedAt: null,
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
},
|
||||
]
|
||||
|
||||
const markdownOutput = formatAsMarkdown(memories)
|
||||
|
||||
expect(markdownOutput).toContain('# Memory Export')
|
||||
expect(markdownOutput).toContain('## Conventions (1)')
|
||||
expect(markdownOutput).toContain('## Decisions (1)')
|
||||
expect(markdownOutput).toContain('Use TypeScript for all new code')
|
||||
expect(markdownOutput).toContain('Chose Bun as runtime for performance')
|
||||
})
|
||||
|
||||
test('formatAsMarkdown groups memories by scope', async () => {
|
||||
const { formatAsMarkdown } = await import('../src/cli/export.ts')
|
||||
|
||||
const db = createTestDb(tempDir)
|
||||
insertTestMemories(db, TEST_PROJECT_ID)
|
||||
db.close()
|
||||
|
||||
const db2 = new Database(join(tempDir, 'memory.db'))
|
||||
const rows = db2.prepare('SELECT * FROM memories WHERE project_id = ?').all(TEST_PROJECT_ID) as Array<{
|
||||
id: number
|
||||
project_id: string
|
||||
scope: string
|
||||
content: string
|
||||
file_path: string | null
|
||||
access_count: number
|
||||
last_accessed_at: number | null
|
||||
created_at: number
|
||||
updated_at: number
|
||||
}>
|
||||
db2.close()
|
||||
|
||||
const memories: PluginMemory[] = rows.map((row) => ({
|
||||
id: row.id,
|
||||
projectId: row.project_id,
|
||||
scope: row.scope as 'convention' | 'decision' | 'context',
|
||||
content: row.content,
|
||||
filePath: row.file_path,
|
||||
accessCount: row.access_count,
|
||||
lastAccessedAt: row.last_accessed_at,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
}))
|
||||
|
||||
const markdownOutput = formatAsMarkdown(memories)
|
||||
|
||||
expect(markdownOutput).toContain('Conventions')
|
||||
expect(markdownOutput).toContain('Decisions')
|
||||
expect(markdownOutput).toContain('Contexts')
|
||||
expect(markdownOutput).toContain('Use TypeScript for all new code')
|
||||
expect(markdownOutput).toContain('Chose Bun as runtime for performance')
|
||||
expect(markdownOutput).toContain('Project started in 2024')
|
||||
})
|
||||
|
||||
test('formatAsMarkdown only includes scopes with memories', async () => {
|
||||
const { formatAsMarkdown } = await import('../src/cli/export.ts')
|
||||
|
||||
const memories: PluginMemory[] = [
|
||||
{
|
||||
id: 1,
|
||||
projectId: TEST_PROJECT_ID,
|
||||
scope: 'convention',
|
||||
content: 'Only convention',
|
||||
filePath: null,
|
||||
accessCount: 0,
|
||||
lastAccessedAt: null,
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
},
|
||||
]
|
||||
|
||||
const markdownOutput = formatAsMarkdown(memories)
|
||||
|
||||
expect(markdownOutput).toContain('## Conventions (1)')
|
||||
expect(markdownOutput).not.toContain('## Decisions')
|
||||
expect(markdownOutput).not.toContain('## Contexts')
|
||||
})
|
||||
})
|
||||
|
||||
describe('CLI Export - parseJsonImport', () => {
|
||||
let tempDir: string
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = mkdtempSync(join('.', 'temp-cli-test-'))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
if (existsSync(tempDir)) {
|
||||
rmSync(tempDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test('exports parseJsonImport function', async () => {
|
||||
const { parseJsonImport } = await import('../src/cli/export.ts')
|
||||
expect(typeof parseJsonImport).toBe('function')
|
||||
})
|
||||
|
||||
test('parseJsonImport parses valid JSON array', async () => {
|
||||
const { parseJsonImport } = await import('../src/cli/export.ts')
|
||||
|
||||
const input = [
|
||||
{
|
||||
projectId: TEST_PROJECT_ID,
|
||||
scope: 'decision',
|
||||
content: 'Test content 1',
|
||||
},
|
||||
{
|
||||
projectId: TEST_PROJECT_ID,
|
||||
scope: 'convention',
|
||||
content: 'Test content 2',
|
||||
},
|
||||
]
|
||||
|
||||
const memories = parseJsonImport(JSON.stringify(input), TEST_PROJECT_ID)
|
||||
|
||||
expect(memories).toHaveLength(2)
|
||||
expect(memories[0].content).toBe('Test content 1')
|
||||
expect(memories[0].scope).toBe('decision')
|
||||
expect(memories[1].content).toBe('Test content 2')
|
||||
expect(memories[1].scope).toBe('convention')
|
||||
})
|
||||
|
||||
test('parseJsonImport uses default values for missing fields', async () => {
|
||||
const { parseJsonImport } = await import('../src/cli/export.ts')
|
||||
|
||||
const input = [
|
||||
{
|
||||
content: 'Minimal memory',
|
||||
},
|
||||
]
|
||||
|
||||
const memories = parseJsonImport(JSON.stringify(input), TEST_PROJECT_ID)
|
||||
|
||||
expect(memories).toHaveLength(1)
|
||||
expect(memories[0].content).toBe('Minimal memory')
|
||||
expect(memories[0].projectId).toBe(TEST_PROJECT_ID)
|
||||
expect(memories[0].scope).toBe('context')
|
||||
})
|
||||
|
||||
test('parseJsonImport throws on invalid JSON', async () => {
|
||||
const { parseJsonImport } = await import('../src/cli/export.ts')
|
||||
|
||||
expect(() => parseJsonImport('not valid json', TEST_PROJECT_ID)).toThrow()
|
||||
})
|
||||
|
||||
test('parseJsonImport throws when input is not an array', async () => {
|
||||
const { parseJsonImport } = await import('../src/cli/export.ts')
|
||||
|
||||
expect(() => parseJsonImport('{"invalid": "object"}', TEST_PROJECT_ID)).toThrow()
|
||||
expect(() => parseJsonImport('{}', TEST_PROJECT_ID)).toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
describe('CLI Export - parseMarkdownImport', () => {
|
||||
let tempDir: string
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = mkdtempSync(join('.', 'temp-cli-test-'))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
if (existsSync(tempDir)) {
|
||||
rmSync(tempDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test('exports parseMarkdownImport function', async () => {
|
||||
const { parseMarkdownImport } = await import('../src/cli/export.ts')
|
||||
expect(typeof parseMarkdownImport).toBe('function')
|
||||
})
|
||||
|
||||
test('parseMarkdownImport parses scoped sections', async () => {
|
||||
const { parseMarkdownImport } = await import('../src/cli/export.ts')
|
||||
|
||||
const markdownContent = `# Memory Export
|
||||
|
||||
## Conventions (1)
|
||||
|
||||
### [1] - Created 2024-01-01
|
||||
|
||||
Use ESLint for code linting
|
||||
|
||||
## Decisions (1)
|
||||
|
||||
### [2] - Created 2024-01-01
|
||||
|
||||
Adopted Prettier for formatting
|
||||
`
|
||||
|
||||
const memories = parseMarkdownImport(markdownContent, TEST_PROJECT_ID)
|
||||
|
||||
expect(memories.length).toBeGreaterThanOrEqual(1)
|
||||
const hasEslint = memories.some((m) => m.content.includes('ESLint'))
|
||||
expect(hasEslint).toBe(true)
|
||||
})
|
||||
|
||||
test('parseMarkdownImport falls back to parsing any content', async () => {
|
||||
const { parseMarkdownImport } = await import('../src/cli/export.ts')
|
||||
|
||||
const markdownContent = `# My Memories
|
||||
|
||||
Just some random content that should be captured as context
|
||||
`
|
||||
|
||||
const memories = parseMarkdownImport(markdownContent, TEST_PROJECT_ID)
|
||||
|
||||
expect(memories.length).toBeGreaterThanOrEqual(1)
|
||||
expect(memories[0]?.content).toContain('random content')
|
||||
})
|
||||
})
|
||||
|
||||
describe('CLI Export - database integration', () => {
|
||||
let tempDir: string
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = mkdtempSync(join('.', 'temp-cli-test-'))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
if (existsSync(tempDir)) {
|
||||
rmSync(tempDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test('can query memories from database', async () => {
|
||||
const { formatAsJson } = await import('../src/cli/export.ts')
|
||||
|
||||
const db = createTestDb(tempDir)
|
||||
insertTestMemories(db, TEST_PROJECT_ID)
|
||||
db.close()
|
||||
|
||||
const db2 = new Database(join(tempDir, 'memory.db'))
|
||||
const rows = db2
|
||||
.prepare('SELECT * FROM memories WHERE project_id = ?')
|
||||
.all(TEST_PROJECT_ID) as PluginMemory[]
|
||||
db2.close()
|
||||
|
||||
const jsonOutput = formatAsJson(rows)
|
||||
|
||||
expect(jsonOutput).toContain('Use TypeScript for all new code')
|
||||
expect(jsonOutput).toContain('Chose Bun as runtime for performance')
|
||||
expect(jsonOutput).toContain('Project started in 2024')
|
||||
|
||||
const parsed = JSON.parse(jsonOutput)
|
||||
expect(parsed).toHaveLength(3)
|
||||
})
|
||||
|
||||
test('can filter by scope', async () => {
|
||||
const { formatAsJson } = await import('../src/cli/export.ts')
|
||||
|
||||
const db = createTestDb(tempDir)
|
||||
insertTestMemories(db, TEST_PROJECT_ID)
|
||||
db.close()
|
||||
|
||||
const db2 = new Database(join(tempDir, 'memory.db'))
|
||||
const rows = db2
|
||||
.prepare('SELECT * FROM memories WHERE project_id = ? AND scope = ?')
|
||||
.all(TEST_PROJECT_ID, 'convention') as PluginMemory[]
|
||||
db2.close()
|
||||
|
||||
const jsonOutput = formatAsJson(rows)
|
||||
|
||||
expect(jsonOutput).toContain('Use TypeScript for all new code')
|
||||
expect(jsonOutput).not.toContain('Chose Bun as runtime')
|
||||
expect(jsonOutput).not.toContain('Project started in 2024')
|
||||
|
||||
const parsed = JSON.parse(jsonOutput)
|
||||
expect(parsed).toHaveLength(1)
|
||||
expect(parsed[0].scope).toBe('convention')
|
||||
})
|
||||
|
||||
test('import adds new memories to database', async () => {
|
||||
const db = createTestDb(tempDir)
|
||||
db.close()
|
||||
|
||||
const importData = [
|
||||
{
|
||||
projectId: TEST_PROJECT_ID,
|
||||
scope: 'decision',
|
||||
content: 'Imported decision memory',
|
||||
},
|
||||
{
|
||||
projectId: TEST_PROJECT_ID,
|
||||
scope: 'convention',
|
||||
content: 'Imported convention memory',
|
||||
},
|
||||
]
|
||||
|
||||
const db2 = new Database(join(tempDir, 'memory.db'))
|
||||
|
||||
for (const item of importData) {
|
||||
const now = Date.now()
|
||||
db2.run(
|
||||
'INSERT INTO memories (project_id, scope, content, file_path, access_count, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||||
[item.projectId, item.scope, item.content, null, 0, now, now]
|
||||
)
|
||||
}
|
||||
|
||||
db2.close()
|
||||
|
||||
const db3 = new Database(join(tempDir, 'memory.db'))
|
||||
const rows = db3.prepare('SELECT * FROM memories WHERE project_id = ?').all(TEST_PROJECT_ID) as PluginMemory[]
|
||||
db3.close()
|
||||
|
||||
expect(rows).toHaveLength(2)
|
||||
expect(rows.some((r) => r.content === 'Imported decision memory')).toBe(true)
|
||||
expect(rows.some((r) => r.content === 'Imported convention memory')).toBe(true)
|
||||
})
|
||||
|
||||
test('duplicate detection works correctly', async () => {
|
||||
const db = createTestDb(tempDir)
|
||||
const now = Date.now()
|
||||
|
||||
db.run(
|
||||
'INSERT INTO memories (project_id, scope, content, file_path, access_count, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||||
[TEST_PROJECT_ID, 'convention', 'Existing memory', null, 0, now, now]
|
||||
)
|
||||
db.close()
|
||||
|
||||
const importData = [
|
||||
{
|
||||
projectId: TEST_PROJECT_ID,
|
||||
scope: 'convention',
|
||||
content: 'Existing memory',
|
||||
},
|
||||
{
|
||||
projectId: TEST_PROJECT_ID,
|
||||
scope: 'convention',
|
||||
content: 'New memory',
|
||||
},
|
||||
]
|
||||
|
||||
const db2 = new Database(join(tempDir, 'memory.db'))
|
||||
|
||||
let importedCount = 0
|
||||
let skippedCount = 0
|
||||
|
||||
for (const item of importData) {
|
||||
const existing = db2
|
||||
.prepare('SELECT id FROM memories WHERE project_id = ? AND content = ? LIMIT 1')
|
||||
.get(TEST_PROJECT_ID, item.content)
|
||||
|
||||
if (existing) {
|
||||
skippedCount++
|
||||
} else {
|
||||
const now2 = Date.now()
|
||||
db2.run(
|
||||
'INSERT INTO memories (project_id, scope, content, file_path, access_count, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||||
[item.projectId, item.scope, item.content, null, 0, now2, now2]
|
||||
)
|
||||
importedCount++
|
||||
}
|
||||
}
|
||||
|
||||
db2.close()
|
||||
|
||||
expect(importedCount).toBe(1)
|
||||
expect(skippedCount).toBe(1)
|
||||
|
||||
const db3 = new Database(join(tempDir, 'memory.db'))
|
||||
const rows = db3.prepare('SELECT * FROM memories WHERE project_id = ?').all(TEST_PROJECT_ID) as PluginMemory[]
|
||||
db3.close()
|
||||
|
||||
expect(rows).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user