mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
Add executionModel feature and refactor CLI into modular commands (#150)
* Add executionModel feature and refactor CLI into modular commands - Add executionModel config option to memory plugin for specifying AI provider/model - Refactor monolithic CLI into modular commands: export, import, list, stats, cleanup - Add model selector UI with connected providers and recent models - Add showClear prop to Combobox component - Update documentation and bump version to 0.0.10 * Update execution model placeholder text * Update docs with new CLI commands and ocm-mem binary usage * Bump version to v0.9.06 * Add executionModel field to default config
This commit is contained in:
1 parent
e5b2cab9d9
commit
c15e53fb98
22 files changed
+1719
-783
No files matched your search
@@ -70,7 +70,7 @@ Planning state is saved automatically when you call memory-plan-execute — pass
|
||||
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** — STOP and wait for explicit user approval. Do NOT proceed until the user confirms. Once approved, call memory-plan-execute with the full plan (it saves planning state automatically)
|
||||
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)
|
||||
|
||||
## Plan Format
|
||||
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
import { openDatabase, formatDate, truncate, confirm, resolveProjectNames, displayProjectId, MemoryScope } from '../utils'
|
||||
|
||||
interface CleanupOptions {
|
||||
olderThan?: number
|
||||
ids?: number[]
|
||||
scope?: MemoryScope
|
||||
sessions?: boolean
|
||||
all?: boolean
|
||||
dryRun?: boolean
|
||||
force?: boolean
|
||||
projectId?: string
|
||||
dbPath?: string
|
||||
help?: boolean
|
||||
}
|
||||
|
||||
function parseArgs(args: string[]): CleanupOptions {
|
||||
const options: CleanupOptions = {}
|
||||
let i = 0
|
||||
|
||||
while (i < args.length) {
|
||||
const arg = args[i]
|
||||
|
||||
if (arg === '--older-than') {
|
||||
options.olderThan = parseInt(args[++i], 10)
|
||||
if (isNaN(options.olderThan)) {
|
||||
console.error('Invalid --older-than value')
|
||||
process.exit(1)
|
||||
}
|
||||
} else if (arg === '--ids') {
|
||||
const idsStr = args[++i]
|
||||
options.ids = idsStr.split(',').map((id) => parseInt(id.trim(), 10)).filter((id) => !isNaN(id))
|
||||
if (options.ids.length === 0) {
|
||||
console.error('Invalid --ids value')
|
||||
process.exit(1)
|
||||
}
|
||||
} else if (arg === '--scope') {
|
||||
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)
|
||||
}
|
||||
options.scope = scope
|
||||
} else if (arg === '--sessions') {
|
||||
options.sessions = true
|
||||
} else if (arg === '--all') {
|
||||
options.all = true
|
||||
} else if (arg === '--dry-run') {
|
||||
options.dryRun = true
|
||||
} else if (arg === '--force') {
|
||||
options.force = true
|
||||
} else if (arg === '--project' || arg === '-p') {
|
||||
options.projectId = args[++i]
|
||||
} else if (arg === '--db-path') {
|
||||
options.dbPath = args[++i]
|
||||
} else if (arg === '--help' || arg === '-h') {
|
||||
help()
|
||||
process.exit(0)
|
||||
} else {
|
||||
console.error(`Unknown option: ${arg}`)
|
||||
help()
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
i++
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
export function help(): void {
|
||||
console.log(`
|
||||
Delete memories by criteria
|
||||
|
||||
Usage:
|
||||
ocm-mem cleanup [options]
|
||||
|
||||
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
|
||||
--project, -p <id> Project ID (auto-detected from git if not provided)
|
||||
--db-path <path> Path to memory database
|
||||
--help, -h Show this help message
|
||||
`.trim())
|
||||
}
|
||||
|
||||
export function run(args: string[], globalOpts: { dbPath?: string; projectId?: string }): void {
|
||||
const options = parseArgs(args)
|
||||
options.projectId = options.projectId || globalOpts.projectId
|
||||
|
||||
if (options.help) {
|
||||
help()
|
||||
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')
|
||||
help()
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (options.all && !options.projectId) {
|
||||
console.error('--all requires --project to be specified')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (!options.projectId) {
|
||||
console.error('Project ID required. Use --project or run from a git repository.')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const db = openDatabase(options.dbPath || globalOpts.dbPath)
|
||||
|
||||
try {
|
||||
if (options.sessions) {
|
||||
runSessionCleanup(db, options)
|
||||
} else {
|
||||
runMemoryCleanup(db, options)
|
||||
}
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
}
|
||||
|
||||
async function runMemoryCleanup(db: ReturnType<typeof openDatabase>, options: CleanupOptions): Promise<void> {
|
||||
const projectId = options.projectId!
|
||||
let query = 'SELECT id, project_id, scope, content, created_at FROM memories 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.ids && options.ids.length > 0) {
|
||||
query += ` AND id IN (${options.ids.map(() => '?').join(',')})`
|
||||
params.push(...options.ids)
|
||||
}
|
||||
|
||||
if (options.scope) {
|
||||
query += ' AND scope = ?'
|
||||
params.push(options.scope)
|
||||
}
|
||||
|
||||
if (options.all) {
|
||||
query = 'SELECT id, project_id, scope, content, created_at FROM memories WHERE project_id = ?'
|
||||
params.length = 0
|
||||
params.push(projectId)
|
||||
}
|
||||
|
||||
const rows = db.prepare(query).all(...params) as Array<{
|
||||
id: number
|
||||
project_id: string
|
||||
scope: string
|
||||
content: string
|
||||
created_at: number
|
||||
}>
|
||||
|
||||
if (rows.length === 0) {
|
||||
console.log('No memories found to delete.')
|
||||
return
|
||||
}
|
||||
|
||||
console.log('')
|
||||
console.log(`Found ${rows.length} memories to delete:`)
|
||||
console.log(' ID SCOPE CREATED CONTENT')
|
||||
|
||||
const displayRows = rows.slice(0, 20)
|
||||
for (const row of displayRows) {
|
||||
const id = String(row.id).padEnd(6)
|
||||
const scope = row.scope.padEnd(12)
|
||||
const created = formatDate(row.created_at)
|
||||
const content = truncate(row.content, 40)
|
||||
console.log(` ${id} ${scope} ${created} ${content}`)
|
||||
}
|
||||
|
||||
if (rows.length > 20) {
|
||||
console.log(` ... and ${rows.length - 20} more`)
|
||||
}
|
||||
|
||||
console.log('')
|
||||
|
||||
if (options.dryRun) {
|
||||
console.log('Dry run - no memories deleted.')
|
||||
return
|
||||
}
|
||||
|
||||
const shouldProceed = options.force || await confirm(`Delete ${rows.length} memories`)
|
||||
|
||||
if (!shouldProceed) {
|
||||
console.log('Cancelled.')
|
||||
return
|
||||
}
|
||||
|
||||
const idsToDelete = rows.map((r) => r.id)
|
||||
const deleteQuery = `DELETE FROM memories WHERE id IN (${idsToDelete.map(() => '?').join(',')})`
|
||||
db.prepare(deleteQuery).run(...idsToDelete)
|
||||
|
||||
const remainingCount = db.prepare('SELECT COUNT(*) as count FROM memories WHERE project_id = ?').get(projectId) as { count: number }
|
||||
|
||||
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.`)
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
import { writeFileSync } from 'fs'
|
||||
import {
|
||||
openDatabase,
|
||||
groupBy,
|
||||
capitalize,
|
||||
PluginMemory,
|
||||
MemoryScope,
|
||||
} from '../utils'
|
||||
|
||||
export interface ExportOptions {
|
||||
format?: 'json' | 'markdown'
|
||||
output?: string
|
||||
projectId?: string
|
||||
scope?: MemoryScope
|
||||
limit?: number
|
||||
offset?: number
|
||||
dbPath?: string
|
||||
}
|
||||
|
||||
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')
|
||||
}
|
||||
|
||||
function exportMemories(options: ExportOptions): void {
|
||||
const db = openDatabase(options.dbPath)
|
||||
|
||||
try {
|
||||
if (!options.projectId) {
|
||||
console.error('Project ID required. Use --project or ensure this is a git repository.')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const projectId = options.projectId
|
||||
|
||||
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 parseArgs(args: string[]): ExportOptions {
|
||||
const options: 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)
|
||||
}
|
||||
options.format = format
|
||||
} else if (arg === '--output' || arg === '-o') {
|
||||
options.output = args[++i]
|
||||
} else if (arg === '--project' || arg === '-p') {
|
||||
options.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)
|
||||
}
|
||||
options.scope = scope
|
||||
} else if (arg === '--limit' || arg === '-l') {
|
||||
options.limit = parseInt(args[++i], 10)
|
||||
if (isNaN(options.limit)) {
|
||||
console.error('Invalid limit value')
|
||||
process.exit(1)
|
||||
}
|
||||
} else if (arg === '--offset') {
|
||||
options.offset = parseInt(args[++i], 10)
|
||||
if (isNaN(options.offset ?? 0)) {
|
||||
console.error('Invalid offset value')
|
||||
process.exit(1)
|
||||
}
|
||||
} else if (arg === '--db-path') {
|
||||
options.dbPath = args[++i]
|
||||
} else if (arg === '--help' || arg === '-h') {
|
||||
help()
|
||||
process.exit(0)
|
||||
} else {
|
||||
console.error(`Unknown option: ${arg}`)
|
||||
help()
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
i++
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
export function help(): void {
|
||||
console.log(`
|
||||
Export memories from the database
|
||||
|
||||
Usage:
|
||||
ocm-mem 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())
|
||||
}
|
||||
|
||||
export function run(args: string[], globalOpts: { dbPath?: string; projectId?: string }): void {
|
||||
const options = parseArgs(args)
|
||||
options.dbPath = options.dbPath || globalOpts.dbPath
|
||||
options.projectId = options.projectId || globalOpts.projectId
|
||||
|
||||
exportMemories(options)
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
import { readFileSync } from 'fs'
|
||||
import { extname } from 'path'
|
||||
import {
|
||||
openDatabase,
|
||||
PluginMemory,
|
||||
MemoryScope,
|
||||
} from '../utils'
|
||||
|
||||
export interface ImportOptions {
|
||||
format?: 'json' | 'markdown'
|
||||
projectId: string
|
||||
force?: boolean
|
||||
dbPath?: string
|
||||
}
|
||||
|
||||
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 importMemories(filePath: string, options: ImportOptions): void {
|
||||
const db = openDatabase(options.dbPath)
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
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()
|
||||
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[]): { filePath: string; options: ImportOptions } {
|
||||
const options: ImportOptions = { projectId: '' }
|
||||
let filePath = args[0]
|
||||
let i = 1
|
||||
|
||||
if (!filePath || filePath.startsWith('-')) {
|
||||
console.error('Import requires a file path')
|
||||
help()
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (filePath === '-') {
|
||||
filePath = '/dev/stdin'
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
options.format = format
|
||||
} else if (arg === '--project' || arg === '-p') {
|
||||
options.projectId = args[++i]
|
||||
} else if (arg === '--force') {
|
||||
options.force = true
|
||||
} else if (arg === '--db-path') {
|
||||
options.dbPath = args[++i]
|
||||
} else if (arg === '--help' || arg === '-h') {
|
||||
help()
|
||||
process.exit(0)
|
||||
} else {
|
||||
console.error(`Unknown option: ${arg}`)
|
||||
help()
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
i++
|
||||
}
|
||||
|
||||
return { filePath, options }
|
||||
}
|
||||
|
||||
export function help(): void {
|
||||
console.log(`
|
||||
Import memories into the database
|
||||
|
||||
Usage:
|
||||
ocm-mem 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())
|
||||
}
|
||||
|
||||
export function run(args: string[], globalOpts: { dbPath?: string; projectId?: string }): void {
|
||||
const { filePath, options } = parseArgs(args)
|
||||
options.dbPath = options.dbPath || globalOpts.dbPath
|
||||
options.projectId = options.projectId || globalOpts.projectId || ''
|
||||
|
||||
if (!options.projectId) {
|
||||
console.error('Project ID required. Use --project or ensure this is a git repository.')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
importMemories(filePath, options)
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { openDatabase, formatDate, resolveProjectNames, displayProjectId } from '../utils'
|
||||
|
||||
interface ProjectMemoryStats {
|
||||
project_id: string
|
||||
count: number
|
||||
oldest: number
|
||||
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
|
||||
|
||||
while (i < args.length) {
|
||||
const arg = args[i]
|
||||
|
||||
if (arg === '--db-path') {
|
||||
options.dbPath = args[++i]
|
||||
} else if (arg === '--help' || arg === '-h') {
|
||||
options.help = true
|
||||
} else {
|
||||
console.error(`Unknown option: ${arg}`)
|
||||
help()
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
i++
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
export function help(): void {
|
||||
console.log(`
|
||||
List projects with memory and session state counts
|
||||
|
||||
Usage:
|
||||
ocm-mem list [options]
|
||||
|
||||
Options:
|
||||
--db-path <path> Path to memory database
|
||||
--help, -h Show this help message
|
||||
`.trim())
|
||||
}
|
||||
|
||||
export function run(args: string[], globalOpts: { dbPath?: string; projectId?: string }): void {
|
||||
const options = parseArgs(args)
|
||||
options.dbPath = options.dbPath || globalOpts.dbPath
|
||||
|
||||
if (options.help) {
|
||||
help()
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const db = openDatabase(options.dbPath)
|
||||
const nameMap = resolveProjectNames()
|
||||
|
||||
try {
|
||||
const memoryRows = db.prepare(`
|
||||
SELECT project_id, COUNT(*) as count,
|
||||
MIN(created_at) as oldest, MAX(created_at) as newest
|
||||
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) {
|
||||
console.log('Projects with memories:')
|
||||
console.log(' PROJECT MEMORIES OLDEST NEWEST')
|
||||
|
||||
for (const row of memoryRows) {
|
||||
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 memories found.')
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import { openDatabase, formatDate, resolveProjectNames, displayProjectId } from '../utils'
|
||||
|
||||
interface ScopeStats {
|
||||
scope: string
|
||||
count: number
|
||||
}
|
||||
|
||||
interface ProjectStats {
|
||||
oldest: number
|
||||
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
|
||||
|
||||
while (i < args.length) {
|
||||
const arg = args[i]
|
||||
|
||||
if (arg === '--project' || arg === '-p') {
|
||||
options.projectId = args[++i]
|
||||
} else if (arg === '--db-path') {
|
||||
options.dbPath = args[++i]
|
||||
} else if (arg === '--help' || arg === '-h') {
|
||||
options.help = true
|
||||
} else {
|
||||
console.error(`Unknown option: ${arg}`)
|
||||
help()
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
i++
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
export function help(): void {
|
||||
console.log(`
|
||||
Show memory statistics for a project
|
||||
|
||||
Usage:
|
||||
ocm-mem stats [options]
|
||||
|
||||
Options:
|
||||
--project, -p <id> Project ID (auto-detected from git if not provided)
|
||||
--db-path <path> Path to memory database
|
||||
--help, -h Show this help message
|
||||
`.trim())
|
||||
}
|
||||
|
||||
export function run(args: string[], globalOpts: { dbPath?: string; projectId?: string }): void {
|
||||
const options = parseArgs(args)
|
||||
const dbPath = options.dbPath || globalOpts.dbPath
|
||||
const projectId = options.projectId || globalOpts.projectId
|
||||
|
||||
if (options.help) {
|
||||
help()
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
if (!projectId) {
|
||||
console.error('Project ID required. Use --project or run from a git repository.')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const finalProjectId = projectId
|
||||
|
||||
const db = openDatabase(dbPath)
|
||||
const nameMap = resolveProjectNames()
|
||||
|
||||
try {
|
||||
const scopeRows = db.prepare(`
|
||||
SELECT scope, COUNT(*) as count FROM memories
|
||||
WHERE project_id = ? GROUP BY scope
|
||||
`).all(finalProjectId) as ScopeStats[]
|
||||
|
||||
const statsRow = db.prepare(`
|
||||
SELECT MIN(created_at) as oldest, MAX(created_at) as newest
|
||||
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('')
|
||||
console.log(`Memory Statistics for: ${displayProjectId(finalProjectId, nameMap)}`)
|
||||
console.log(` Total: ${totalMemories}`)
|
||||
console.log(' By scope:')
|
||||
|
||||
const scopeCounts: Record<string, number> = {}
|
||||
for (const scope of ['convention', 'decision', 'context'] as const) {
|
||||
scopeCounts[scope] = 0
|
||||
}
|
||||
for (const row of scopeRows) {
|
||||
scopeCounts[row.scope] = row.count
|
||||
}
|
||||
|
||||
console.log(` convention: ${scopeCounts['convention']}`)
|
||||
console.log(` decision: ${scopeCounts['decision']}`)
|
||||
console.log(` context: ${scopeCounts['context']}`)
|
||||
|
||||
if (statsRow && statsRow.oldest) {
|
||||
console.log(` Oldest: ${formatDate(statsRow.oldest)}`)
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -1,667 +0,0 @@
|
||||
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,154 @@
|
||||
#!/usr/bin/env bun
|
||||
import { parseGlobalOptions, getGitProjectId, resolveProjectIdByName } from './utils'
|
||||
|
||||
interface CommandModule {
|
||||
run: (args: string[], globalOpts: { dbPath?: string; projectId?: string }) => Promise<void>
|
||||
help: () => void | Promise<void>
|
||||
}
|
||||
|
||||
const commands: Record<string, CommandModule> = {
|
||||
export: {
|
||||
run: async (args, globalOpts) => {
|
||||
const { run } = await import('./commands/export')
|
||||
run(args, globalOpts)
|
||||
},
|
||||
help: async () => {
|
||||
const { help } = await import('./commands/export')
|
||||
help()
|
||||
},
|
||||
},
|
||||
import: {
|
||||
run: async (args, globalOpts) => {
|
||||
const { run } = await import('./commands/import')
|
||||
run(args, globalOpts)
|
||||
},
|
||||
help: async () => {
|
||||
const { help } = await import('./commands/import')
|
||||
help()
|
||||
},
|
||||
},
|
||||
list: {
|
||||
run: async (args, globalOpts) => {
|
||||
const { run } = await import('./commands/list')
|
||||
run(args, globalOpts)
|
||||
},
|
||||
help: async () => {
|
||||
const { help } = await import('./commands/list')
|
||||
help()
|
||||
},
|
||||
},
|
||||
stats: {
|
||||
run: async (args, globalOpts) => {
|
||||
const { run } = await import('./commands/stats')
|
||||
run(args, globalOpts)
|
||||
},
|
||||
help: async () => {
|
||||
const { help } = await import('./commands/stats')
|
||||
help()
|
||||
},
|
||||
},
|
||||
cleanup: {
|
||||
run: async (args, globalOpts) => {
|
||||
const { run } = await import('./commands/cleanup')
|
||||
run(args, globalOpts)
|
||||
},
|
||||
help: async () => {
|
||||
const { help } = await import('./commands/cleanup')
|
||||
help()
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
function printMainHelp(): void {
|
||||
console.log(`
|
||||
OpenCode Memory CLI
|
||||
|
||||
Usage:
|
||||
ocm-mem <command> [options]
|
||||
|
||||
Commands:
|
||||
export Export memories to file (JSON or Markdown)
|
||||
import Import memories from file
|
||||
list List projects with memory counts
|
||||
stats Show memory statistics
|
||||
cleanup Delete memories by criteria
|
||||
|
||||
Global Options:
|
||||
--db-path <path> Path to memory database
|
||||
--project, -p <name> Project name or SHA (auto-detected from git)
|
||||
--dir, -d <path> Git repo path for project detection
|
||||
--help, -h Show help
|
||||
|
||||
Run '<command> --help' for more information on a command.
|
||||
`.trim())
|
||||
}
|
||||
|
||||
function resolveProjectId(input: string): string {
|
||||
const isSha = /^[0-9a-f]{40}$/.test(input)
|
||||
if (isSha) return input
|
||||
|
||||
return resolveProjectIdByName(input) || input
|
||||
}
|
||||
|
||||
async function runCli(): Promise<void> {
|
||||
const args = process.argv.slice(2)
|
||||
|
||||
if (args.length === 0 || (args.length === 1 && (args[0] === 'help' || args[0] === '--help' || args[0] === '-h'))) {
|
||||
printMainHelp()
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const hasHelpFlag = (arr: string[]) => arr.includes('--help') || arr.includes('-h')
|
||||
|
||||
if (hasHelpFlag(args) && args.length === 1) {
|
||||
printMainHelp()
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const { globalOpts, remainingArgs } = parseGlobalOptions(args)
|
||||
const commandName = remainingArgs[0]
|
||||
|
||||
if (!commandName) {
|
||||
printMainHelp()
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const command = commands[commandName]
|
||||
|
||||
if (!command) {
|
||||
console.error(`Unknown command: ${commandName}`)
|
||||
printMainHelp()
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (globalOpts.help) {
|
||||
await command.help()
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const commandArgs = remainingArgs.slice(1)
|
||||
|
||||
if (hasHelpFlag(commandArgs)) {
|
||||
await command.help()
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
let finalProjectId = globalOpts.projectId
|
||||
? resolveProjectId(globalOpts.projectId)
|
||||
: getGitProjectId(globalOpts.dir)
|
||||
|
||||
const effectiveGlobalOpts: { dbPath?: string; projectId?: string } = {
|
||||
...globalOpts,
|
||||
}
|
||||
|
||||
if (finalProjectId) {
|
||||
effectiveGlobalOpts.projectId = finalProjectId
|
||||
}
|
||||
|
||||
await command.run(commandArgs, effectiveGlobalOpts)
|
||||
}
|
||||
|
||||
runCli().catch((error) => {
|
||||
console.error('Error:', error)
|
||||
process.exit(1)
|
||||
})
|
||||
@@ -0,0 +1,206 @@
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { existsSync, readFileSync } from 'fs'
|
||||
import { homedir, platform } from 'os'
|
||||
import { join, basename } from 'path'
|
||||
import { execSync } from 'child_process'
|
||||
import { createInterface } from 'readline'
|
||||
|
||||
export type MemoryScope = 'convention' | 'decision' | 'context'
|
||||
|
||||
export interface PluginMemory {
|
||||
id: number
|
||||
projectId: string
|
||||
scope: MemoryScope
|
||||
content: string
|
||||
filePath: string | null
|
||||
accessCount: number
|
||||
lastAccessedAt: number | null
|
||||
createdAt: number
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
export interface GlobalOptions {
|
||||
dbPath?: string
|
||||
projectId?: string
|
||||
dir?: string
|
||||
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)) {
|
||||
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')
|
||||
}
|
||||
|
||||
export function getGitProjectId(dir?: string): string | null {
|
||||
try {
|
||||
const execOpts = dir ? { encoding: 'utf-8' as const, cwd: dir } : { encoding: 'utf-8' as const }
|
||||
const repoRoot = execSync('git rev-parse --show-toplevel', execOpts).trim()
|
||||
if (!repoRoot) return null
|
||||
|
||||
const cacheFile = join(repoRoot, '.git', 'opencode')
|
||||
if (existsSync(cacheFile)) {
|
||||
const cachedId = readFileSync(cacheFile, 'utf-8').trim()
|
||||
if (cachedId) return cachedId
|
||||
}
|
||||
|
||||
const output = execSync('git rev-list --max-parents=0 --all', execOpts).trim()
|
||||
if (!output) return null
|
||||
|
||||
const commits = output.split('\n').filter(Boolean).sort()
|
||||
return commits[0] || null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export 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[]>)
|
||||
}
|
||||
|
||||
export function capitalize(str: string): string {
|
||||
return str.charAt(0).toUpperCase() + str.slice(1)
|
||||
}
|
||||
|
||||
export function openDatabase(dbPath?: string): Database {
|
||||
const resolvedPath = dbPath || resolveDefaultDbPath()
|
||||
|
||||
if (!existsSync(resolvedPath)) {
|
||||
console.error(`Database not found at ${resolvedPath}. Run OpenCode first to initialize memories.`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
return new Database(resolvedPath)
|
||||
}
|
||||
|
||||
export function formatDate(timestamp: number): string {
|
||||
return new Date(timestamp).toISOString().split('T')[0]
|
||||
}
|
||||
|
||||
export function truncate(str: string, maxLen: number): string {
|
||||
if (str.length <= maxLen) return str
|
||||
return str.slice(0, maxLen - 3) + '...'
|
||||
}
|
||||
|
||||
export function confirm(message: string): Promise<boolean> {
|
||||
return new Promise((resolve) => {
|
||||
const rl = createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout,
|
||||
})
|
||||
|
||||
rl.question(`${message} (y/n): `, (answer) => {
|
||||
rl.close()
|
||||
resolve(answer.toLowerCase() === 'y')
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
export interface ParsedGlobalOptions {
|
||||
globalOpts: GlobalOptions
|
||||
remainingArgs: string[]
|
||||
}
|
||||
|
||||
export function parseGlobalOptions(args: string[]): ParsedGlobalOptions {
|
||||
const globalOpts: GlobalOptions = {}
|
||||
const remainingArgs: string[] = []
|
||||
|
||||
let i = 0
|
||||
while (i < args.length) {
|
||||
const arg = args[i]
|
||||
|
||||
if (arg === '--db-path') {
|
||||
globalOpts.dbPath = args[++i]
|
||||
} else if (arg === '--project' || arg === '-p') {
|
||||
globalOpts.projectId = args[++i]
|
||||
} else if (arg === '--dir' || arg === '-d') {
|
||||
globalOpts.dir = args[++i]
|
||||
} else if (arg === '--help' || arg === '-h') {
|
||||
globalOpts.help = true
|
||||
} else {
|
||||
remainingArgs.push(arg)
|
||||
}
|
||||
|
||||
i++
|
||||
}
|
||||
|
||||
return { globalOpts, remainingArgs }
|
||||
}
|
||||
|
||||
export function resolveProjectNames(): Map<string, string> {
|
||||
const nameMap = new Map<string, string>()
|
||||
|
||||
try {
|
||||
const defaultBase = join(homedir(), platform() === 'win32' ? 'AppData' : '.local', 'share')
|
||||
const xdgDataHome = process.env['XDG_DATA_HOME'] || defaultBase
|
||||
const opencodePath = join(xdgDataHome, 'opencode', 'opencode.db')
|
||||
|
||||
if (!existsSync(opencodePath)) return nameMap
|
||||
|
||||
const db = new Database(opencodePath, { readonly: true })
|
||||
|
||||
try {
|
||||
const rows = db.prepare('SELECT id, worktree FROM project').all() as Array<{ id: string; worktree: string }>
|
||||
|
||||
for (const row of rows) {
|
||||
nameMap.set(row.id, basename(row.worktree))
|
||||
}
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
} catch {
|
||||
// opencode.db may not exist or have different schema — graceful fallback
|
||||
}
|
||||
|
||||
return nameMap
|
||||
}
|
||||
|
||||
export function resolveProjectIdByName(name: string): string | null {
|
||||
try {
|
||||
const defaultBase = join(homedir(), platform() === 'win32' ? 'AppData' : '.local', 'share')
|
||||
const xdgDataHome = process.env['XDG_DATA_HOME'] || defaultBase
|
||||
const opencodePath = join(xdgDataHome, 'opencode', 'opencode.db')
|
||||
|
||||
if (!existsSync(opencodePath)) return null
|
||||
|
||||
const db = new Database(opencodePath, { readonly: true })
|
||||
|
||||
try {
|
||||
const rows = db.prepare('SELECT id, worktree FROM project').all() as Array<{ id: string; worktree: string }>
|
||||
|
||||
for (const row of rows) {
|
||||
if (basename(row.worktree) === name) return row.id
|
||||
}
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export function displayProjectId(id: string, nameMap: Map<string, string>): string {
|
||||
return nameMap.get(id) || id
|
||||
}
|
||||
@@ -250,6 +250,16 @@ async function autoValidateOnLoad(
|
||||
logger.log(`Auto-validate: reindex complete (total=${result.total}, success=${result.success}, failed=${result.failed})`)
|
||||
}
|
||||
|
||||
function parseModelString(modelStr?: string): { providerID: string; modelID: string } | undefined {
|
||||
if (!modelStr) return undefined
|
||||
const slashIndex = modelStr.indexOf('/')
|
||||
if (slashIndex <= 0 || slashIndex === modelStr.length - 1) return undefined
|
||||
return {
|
||||
providerID: modelStr.substring(0, slashIndex),
|
||||
modelID: modelStr.substring(slashIndex + 1),
|
||||
}
|
||||
}
|
||||
|
||||
export function createMemoryPlugin(config: PluginConfig): Plugin {
|
||||
return async (input: PluginInput): Promise<Hooks> => {
|
||||
const { directory, project, client } = input
|
||||
@@ -646,11 +656,14 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
|
||||
|
||||
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 }],
|
||||
agent: 'Code',
|
||||
...(executionModel && { model: executionModel }),
|
||||
},
|
||||
})
|
||||
|
||||
@@ -668,7 +681,8 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
|
||||
})
|
||||
logger.log(`memory-plan-execute: updated planning state for source session=${context.sessionID}`)
|
||||
|
||||
return `Implementation session created and plan sent.\n\nSession: ${newSessionId}\nTitle: ${sessionTitle}\n\nSwitch to this session to begin. You can change the model from the session dropdown.`
|
||||
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.`
|
||||
},
|
||||
}),
|
||||
},
|
||||
|
||||
@@ -110,6 +110,7 @@ function normalizeConfig(config: PluginConfig): PluginConfig {
|
||||
dedupThreshold: config.dedupThreshold,
|
||||
logging: config.logging,
|
||||
compaction: config.compaction,
|
||||
executionModel: config.executionModel,
|
||||
}
|
||||
|
||||
if (normalized.embedding) {
|
||||
|
||||
@@ -63,6 +63,7 @@ export interface PluginConfig {
|
||||
dedupThreshold?: number
|
||||
logging?: LoggingConfig
|
||||
compaction?: CompactionConfig
|
||||
executionModel?: string
|
||||
}
|
||||
|
||||
export interface ListMemoriesFilter {
|
||||
|
||||
@@ -1 +1 @@
|
||||
export const VERSION = '0.0.9'
|
||||
export const VERSION = '0.0.10'
|
||||
Reference in new issue
Block a user