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:
Chris Scott authored and GitHub committed 2026-03-03 20:08:36 -05:00
1 parent e5b2cab9d9
commit c15e53fb98
22 files changed
+1719 -783

No files matched your search

+67 -1
View File
@@ -61,7 +61,8 @@ The file is only created if it does not already exist. The config is validated o
"inlinePlanning": true,
"maxContextTokens": 4000,
"snapshotToKV": true
}
},
"executionModel": ""
}
```
@@ -105,6 +106,7 @@ Set `baseUrl` to point at any OpenAI-compatible self-hosted service (vLLM, Ollam
| `compaction.inlinePlanning` | Include planning state in compaction context | `true` |
| `compaction.maxContextTokens` | Max tokens for injected memory context | `4000` |
| `compaction.snapshotToKV` | Save pre-compaction snapshot for recovery | `true` |
| `executionModel` | Model override for plan execution sessions (`provider/model`). Falls back to OpenCode's default model. | — |
---
@@ -364,6 +366,8 @@ Create a new Code session and send an implementation plan as the first prompt. D
Saves planning state (objective, phases, findings) for the Architect session, creates a new session via the OpenCode API, then sends the plan as the first message to the Code agent. Returns the session ID and title. Only the Architect agent has access to this tool — it is excluded from Code and Memory agents.
The model used for the new Code session is determined by `executionModel` in the plugin config (format: `provider/model`, e.g. `anthropic/claude-sonnet-4-20250514`). If not set, OpenCode's default model resolution is used — typically the `model` field from `opencode.json`.
---
## Planning State
@@ -564,6 +568,68 @@ The cleanup function is idempotent — calling it multiple times is safe.
---
## CLI
The plugin includes the `ocm-mem` CLI for managing memories outside of OpenCode sessions. The CLI auto-detects the project ID from git and resolves the database path automatically.
```bash
ocm-mem <command> [options]
```
### Global Options
| Flag | Description |
|------|-------------|
| `--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 |
### Commands
| Command | Description |
|---------|-------------|
| `export` | Export memories to file (JSON or Markdown) |
| `import` | Import memories from file |
| `list` | List projects with memory and session state counts |
| `stats` | Show memory statistics for a project |
| `cleanup` | Delete memories or session states by criteria |
### Usage Examples
```bash
# Export all memories as markdown
ocm-mem export --format markdown --output memories.md
# Export filtered by scope
ocm-mem export --project my-project --scope convention
# Import from JSON
ocm-mem import memories.json --project my-project
# Import from Markdown, skip duplicate detection
ocm-mem import memories.md --project my-project --force
# List all projects
ocm-mem list
# Show stats for current project
ocm-mem stats
# Preview cleanup of old memories (dry run)
ocm-mem cleanup --older-than 90 --dry-run
# Delete specific memories
ocm-mem cleanup --ids 1,2,3 --force
# Clean up expired session states
ocm-mem cleanup --sessions --older-than 30
```
Run `ocm-mem <command> --help` for full options on each command.
---
## Troubleshooting
### Plugin shows "degraded" status
@@ -1,11 +1,15 @@
import { useState, useEffect } from 'react'
import { useState, useEffect, useMemo } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Combobox } from '@/components/ui/combobox'
import type { ComboboxOption } from '@/components/ui/combobox'
import { getProviders } from '@/api/providers'
import { useModelStore } from '@/stores/modelStore'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { ChevronDown, ChevronRight, Save, Loader2, Database, Brain, AlertCircle, RefreshCw, Play } from 'lucide-react'
import { ChevronDown, ChevronRight, Save, Loader2, Database, Brain, AlertCircle, RefreshCw, Play, Cpu } from 'lucide-react'
import { getPluginConfig, updatePluginConfig, reindexMemories, testEmbeddingConfig } from '@/api/memory'
import { FetchError } from '@/api/fetchWrapper'
import { settingsApi } from '@/api/settings'
@@ -41,6 +45,54 @@ export function MemoryPluginConfig({ memoryPluginEnabled, onToggle }: MemoryPlug
enabled: memoryPluginEnabled && expanded,
})
const { data: providersData } = useQuery({
queryKey: ['providers-for-execution-model'],
queryFn: getProviders,
staleTime: 60000,
enabled: memoryPluginEnabled && expanded,
})
const recentModels = useModelStore((s) => s.recentModels)
const executionModelOptions = useMemo<ComboboxOption[]>(() => {
if (!providersData?.providers) return []
const connectedProviders = providersData.providers.filter((p) => p.isConnected)
const recentSet = new Set<string>()
const recentOptions: ComboboxOption[] = []
for (const recent of recentModels) {
const modelValue = `${recent.providerID}/${recent.modelID}`
const provider = connectedProviders.find((p) => p.id === recent.providerID)
const model = provider?.models[recent.modelID]
if (!model || !provider) continue
recentSet.add(modelValue)
recentOptions.push({
value: modelValue,
label: model.name || model.id,
description: provider.name,
group: 'Recent',
})
}
const providerOptions: ComboboxOption[] = []
for (const provider of connectedProviders.sort((a, b) => a.name.localeCompare(b.name))) {
for (const [modelId, model] of Object.entries(provider.models)) {
const modelValue = `${provider.id}/${modelId}`
if (recentSet.has(modelValue)) continue
providerOptions.push({
value: modelValue,
label: model.name || model.id,
description: modelId,
group: provider.name,
})
}
}
return [...recentOptions, ...providerOptions]
}, [providersData, recentModels])
const config = data?.config
const [localConfig, setLocalConfig] = useState<PluginConfig | null>(null)
@@ -66,12 +118,8 @@ export function MemoryPluginConfig({ memoryPluginEnabled, onToggle }: MemoryPlug
const updateMutation = useMutation({
mutationFn: updatePluginConfig,
onSuccess: (data) => {
showToast.success('Memory plugin configuration saved')
queryClient.setQueryData(['memory-plugin-config'], { config: data.config })
},
onError: () => {
showToast.error('Failed to save configuration')
},
})
const reindexMutation = useMutation({
@@ -112,16 +160,20 @@ export function MemoryPluginConfig({ memoryPluginEnabled, onToggle }: MemoryPlug
const handleSave = async () => {
if (!localConfig) return
showToast.loading('Saving configuration...', { id: 'memory-save' })
updateMutation.mutate(localConfig, {
onSuccess: async () => {
showToast.loading('Restarting OpenCode server...', { id: 'memory-restart' })
showToast.loading('Restarting OpenCode server...', { id: 'memory-save' })
try {
await settingsApi.restartOpenCodeServer()
showToast.success('Configuration saved and server restarted', { id: 'memory-restart' })
showToast.success('Configuration saved and server restarted', { id: 'memory-save' })
} catch {
showToast.error('Failed to restart server', { id: 'memory-restart' })
showToast.error('Failed to restart server', { id: 'memory-save' })
}
},
onError: () => {
showToast.error('Failed to save configuration', { id: 'memory-save' })
},
})
}
@@ -262,40 +314,93 @@ export function MemoryPluginConfig({ memoryPluginEnabled, onToggle }: MemoryPlug
</div>
</>
)}
<div className="space-y-2">
<div className="flex items-center gap-2">
<RefreshCw className="h-4 w-4 text-purple-500" />
<span className="text-sm font-medium">Reindex</span>
</div>
<Button
variant="outline"
size="sm"
onClick={handleReindex}
disabled={reindexMutation.isPending}
className="w-full justify-start"
>
{reindexMutation.isPending ? (
<Loader2 className="h-4 w-4 animate-spin mr-2" />
) : (
<RefreshCw className="h-4 w-4 mr-2" />
)}
Reindex
</Button>
<p className="text-xs text-muted-foreground">
Regenerate embeddings for all memories
</p>
</div>
</div>
</div>
<div className="space-y-4 border-t pt-4">
<div className="flex items-center gap-2 mb-3">
<Database className="h-4 w-4 text-green-500" />
<span className="text-sm font-medium">Storage</span>
<div className="grid gap-4 md:grid-cols-2 border-t pt-4">
<div className="space-y-4">
<div className="flex items-center gap-2 mb-3">
<Database className="h-4 w-4 text-green-500" />
<span className="text-sm font-medium">Storage</span>
</div>
<div className="space-y-2">
<Label htmlFor="dedupThreshold">Deduplication Threshold</Label>
<div className="flex items-center gap-4">
<input
id="dedupThreshold"
type="range"
min="0"
max="0.4"
step="0.05"
value={displayConfig.dedupThreshold ?? 0.25}
onChange={(e) => {
setLocalConfig({
...displayConfig,
dedupThreshold: parseFloat(e.target.value),
})
}}
className="flex-1"
/>
<span className="text-sm text-muted-foreground w-12">
{(displayConfig.dedupThreshold ?? 0.25).toFixed(2)}
</span>
</div>
<p className="text-xs text-muted-foreground">
Lower values = more aggressive deduplication (0.0 - 0.4)
</p>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="dedupThreshold">Deduplication Threshold</Label>
<div className="flex items-center gap-4">
<input
id="dedupThreshold"
type="range"
min="0"
max="0.4"
step="0.05"
value={displayConfig.dedupThreshold ?? 0.25}
onChange={(e) => {
<div className="space-y-4">
<div className="flex items-center gap-2 mb-3">
<Cpu className="h-4 w-4 text-orange-500" />
<span className="text-sm font-medium">Plan Execution</span>
</div>
<div className="space-y-2">
<Label htmlFor="executionModel">Execution Model</Label>
<Combobox
value={displayConfig.executionModel ?? ''}
onChange={(value) => {
setLocalConfig({
...displayConfig,
dedupThreshold: parseFloat(e.target.value),
executionModel: value || undefined,
})
}}
className="flex-1"
options={executionModelOptions}
placeholder="default model"
allowCustomValue
showClear
/>
<span className="text-sm text-muted-foreground w-12">
{(displayConfig.dedupThreshold ?? 0.25).toFixed(2)}
</span>
<p className="text-xs text-muted-foreground">
Model used when executing plans from the Architect. Format: provider/model. Leave empty to use the current session's model.
</p>
</div>
<p className="text-xs text-muted-foreground">
Lower values = more aggressive deduplication (0.0 - 0.4)
</p>
</div>
</div>
@@ -306,31 +411,6 @@ export function MemoryPluginConfig({ memoryPluginEnabled, onToggle }: MemoryPlug
</div>
)}
<div className="space-y-4 border-t pt-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<RefreshCw className="h-4 w-4 text-purple-500" />
<span className="text-sm font-medium">Reindex</span>
</div>
<Button
variant="outline"
size="sm"
onClick={handleReindex}
disabled={reindexMutation.isPending}
>
{reindexMutation.isPending ? (
<Loader2 className="h-4 w-4 animate-spin mr-1" />
) : (
<RefreshCw className="h-4 w-4 mr-1" />
)}
Reindex
</Button>
</div>
<p className="text-xs text-muted-foreground">
Regenerate embeddings for all memories. Use when changing embedding model or if embeddings are missing.
</p>
</div>
<div className="flex items-center justify-between pt-2">
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<AlertCircle className="h-3 w-3" />
+23 -2
View File
@@ -1,6 +1,6 @@
import { useState, useRef, useEffect, useCallback } from 'react'
import { cn } from '@/lib/utils'
import { ChevronDown } from 'lucide-react'
import { ChevronDown, X } from 'lucide-react'
export interface ComboboxOption {
value: string
@@ -17,6 +17,7 @@ interface ComboboxProps {
disabled?: boolean
className?: string
allowCustomValue?: boolean
showClear?: boolean
}
export function Combobox({
@@ -27,6 +28,7 @@ export function Combobox({
disabled = false,
className,
allowCustomValue = true,
showClear = false,
}: ComboboxProps) {
const [isOpen, setIsOpen] = useState(false)
const [inputValue, setInputValue] = useState(() => {
@@ -181,6 +183,22 @@ export function Combobox({
'pr-8'
)}
/>
{showClear && value && (
<button
type="button"
onClick={() => {
if (!disabled) {
onChange('')
setInputValue('')
inputRef.current?.focus()
}
}}
className="absolute right-7 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
tabIndex={-1}
>
<X className="h-3.5 w-3.5" />
</button>
)}
<button
type="button"
onClick={() => {
@@ -189,7 +207,10 @@ export function Combobox({
inputRef.current?.focus()
}
}}
className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
className={cn(
'absolute top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground',
showClear && value ? 'right-1' : 'right-2'
)}
tabIndex={-1}
>
<ChevronDown className={cn('h-4 w-4 transition-transform', isOpen && 'rotate-180')} />
+2 -1
View File
@@ -1,10 +1,11 @@
{
"name": "opencode-manager",
"version": "0.9.05",
"version": "0.9.06",
"private": false,
"type": "module",
"packageManager": "pnpm@10.28.1",
"scripts": {
"memory": "pnpm --filter @opencode-manager/memory cli",
"predev": "bash scripts/setup-dev.sh",
"dev": "concurrently \"pnpm:dev:backend\" \"pnpm:dev:frontend\"",
"dev:backend": "bun --watch backend/src/index.ts",
+72 -32
View File
@@ -9,7 +9,7 @@ Memory management plugin for OpenCode that enables semantic search and persisten
- **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
- **CLI Tools** - Export, import, list, stats, and cleanup commands via `ocm-mem` binary
- **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
@@ -45,57 +45,93 @@ The Architect agent operates in read-only mode (`temperature: 0.0`, all edits de
## 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
Manage memories using the `ocm-mem` CLI. The CLI auto-detects the project ID from git and resolves the database path automatically.
```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
ocm-mem <command> [options]
```
**Export options:**
**Global options** (apply to all commands):
| Flag | Description |
|------|-------------|
| `--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 |
### Commands
#### export
Export memories to file (JSON or Markdown).
```bash
ocm-mem export --format markdown --output memories.md
ocm-mem export --project my-project --scope convention
ocm-mem export --limit 50 --offset 100
```
| 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
#### import
Import memories from file.
```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
ocm-mem import memories.json --project my-project
ocm-mem import memories.md --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 |
#### list
List all projects with memory and session state counts.
```bash
ocm-mem list
```
#### stats
Show memory statistics for a project (scope breakdown, session state counts).
```bash
ocm-mem stats
ocm-mem stats --project my-project
```
#### cleanup
Delete memories or session states by criteria.
```bash
ocm-mem cleanup --older-than 90
ocm-mem cleanup --ids 1,2,3 --force
ocm-mem cleanup --scope context --dry-run
ocm-mem cleanup --sessions --older-than 30
ocm-mem cleanup --all --project my-project
```
| Flag | Description |
|------|-------------|
| `--older-than <days>` | Delete memories older than N days |
| `--ids <id,id,...>` | Delete specific memory IDs |
| `--scope <scope>` | Filter by scope: `convention`, `decision`, or `context` |
| `--sessions` | Clean up session states instead of memories |
| `--all` | Delete all memories for the project |
| `--dry-run` | Preview what would be deleted without deleting |
| `--force` | Skip confirmation prompt |
## Installation
@@ -143,7 +179,8 @@ You can edit this file to customize settings. The file is created only if it doe
"inlinePlanning": true,
"maxContextTokens": 4000,
"snapshotToKV": true
}
},
"executionModel": ""
}
```
@@ -187,6 +224,9 @@ When enabled, logs are written to the specified file with timestamps. The log fi
- `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`)
#### Execution
- `executionModel` - Model override for plan execution sessions, format: `provider/model` (e.g. `anthropic/claude-sonnet-4-20250514`). When set, `memory-plan-execute` uses this model for the new Code session. When empty or omitted, OpenCode's default model is used (typically the `model` field from `opencode.json`).
## Development
```bash
+2 -1
View File
@@ -16,5 +16,6 @@
"inlinePlanning": true,
"maxContextTokens": 4000,
"snapshotToKV": true
}
},
"executionModel": ""
}
+6 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@opencode-manager/memory",
"version": "0.0.9",
"version": "0.0.10",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
@@ -16,6 +16,9 @@
"scripts",
"README.md"
],
"bin": {
"ocm-mem": "./dist/cli/index.js"
},
"repository": {
"type": "git",
"url": "https://github.com/chriswritescode-dev/opencode-manager.git"
@@ -53,6 +56,7 @@
"postinstall": "node scripts/download-models.js",
"prepublishOnly": "pnpm build",
"test": "bun test",
"typecheck": "tsc --noEmit"
"typecheck": "tsc --noEmit",
"cli": "bun src/cli/index.ts"
}
}
+1 -1
View File
@@ -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
+277
View File
@@ -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.`)
}
+205
View File
@@ -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)
}
+279
View File
@@ -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)
}
+116
View File
@@ -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()
}
}
+136
View File
@@ -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()
}
}
-667
View File
@@ -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()
}
+154
View File
@@ -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)
})
+206
View File
@@ -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
}
+15 -1
View File
@@ -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.`
},
}),
},
+1
View File
@@ -110,6 +110,7 @@ function normalizeConfig(config: PluginConfig): PluginConfig {
dedupThreshold: config.dedupThreshold,
logging: config.logging,
compaction: config.compaction,
executionModel: config.executionModel,
}
if (normalized.embedding) {
+1
View File
@@ -63,6 +63,7 @@ export interface PluginConfig {
dedupThreshold?: number
logging?: LoggingConfig
compaction?: CompactionConfig
executionModel?: string
}
export interface ListMemoriesFilter {
+1 -1
View File
@@ -1 +1 @@
export const VERSION = '0.0.9'
export const VERSION = '0.0.10'
+17 -17
View File
@@ -72,12 +72,12 @@ describe('CLI Export - formatAsJson', () => {
})
test('exports formatAsJson function', async () => {
const { formatAsJson } = await import('../src/cli/export.ts')
const { formatAsJson } = await import('../src/cli/commands/export.ts')
expect(typeof formatAsJson).toBe('function')
})
test('formatAsJson converts memories to valid JSON', async () => {
const { formatAsJson } = await import('../src/cli/export.ts')
const { formatAsJson } = await import('../src/cli/commands/export.ts')
const memories: PluginMemory[] = [
{
@@ -103,7 +103,7 @@ describe('CLI Export - formatAsJson', () => {
})
test('formatAsJson handles empty array', async () => {
const { formatAsJson } = await import('../src/cli/export.ts')
const { formatAsJson } = await import('../src/cli/commands/export.ts')
const jsonOutput = formatAsJson([])
const parsed = JSON.parse(jsonOutput)
@@ -126,12 +126,12 @@ describe('CLI Export - formatAsMarkdown', () => {
})
test('exports formatAsMarkdown function', async () => {
const { formatAsMarkdown } = await import('../src/cli/export.ts')
const { formatAsMarkdown } = await import('../src/cli/commands/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 { formatAsMarkdown } = await import('../src/cli/commands/export.ts')
const memories: PluginMemory[] = [
{
@@ -168,7 +168,7 @@ describe('CLI Export - formatAsMarkdown', () => {
})
test('formatAsMarkdown groups memories by scope', async () => {
const { formatAsMarkdown } = await import('../src/cli/export.ts')
const { formatAsMarkdown } = await import('../src/cli/commands/export.ts')
const db = createTestDb(tempDir)
insertTestMemories(db, TEST_PROJECT_ID)
@@ -211,7 +211,7 @@ describe('CLI Export - formatAsMarkdown', () => {
})
test('formatAsMarkdown only includes scopes with memories', async () => {
const { formatAsMarkdown } = await import('../src/cli/export.ts')
const { formatAsMarkdown } = await import('../src/cli/commands/export.ts')
const memories: PluginMemory[] = [
{
@@ -249,12 +249,12 @@ describe('CLI Export - parseJsonImport', () => {
})
test('exports parseJsonImport function', async () => {
const { parseJsonImport } = await import('../src/cli/export.ts')
const { parseJsonImport } = await import('../src/cli/commands/import.ts')
expect(typeof parseJsonImport).toBe('function')
})
test('parseJsonImport parses valid JSON array', async () => {
const { parseJsonImport } = await import('../src/cli/export.ts')
const { parseJsonImport } = await import('../src/cli/commands/import.ts')
const input = [
{
@@ -279,7 +279,7 @@ describe('CLI Export - parseJsonImport', () => {
})
test('parseJsonImport uses default values for missing fields', async () => {
const { parseJsonImport } = await import('../src/cli/export.ts')
const { parseJsonImport } = await import('../src/cli/commands/import.ts')
const input = [
{
@@ -296,13 +296,13 @@ describe('CLI Export - parseJsonImport', () => {
})
test('parseJsonImport throws on invalid JSON', async () => {
const { parseJsonImport } = await import('../src/cli/export.ts')
const { parseJsonImport } = await import('../src/cli/commands/import.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')
const { parseJsonImport } = await import('../src/cli/commands/import.ts')
expect(() => parseJsonImport('{"invalid": "object"}', TEST_PROJECT_ID)).toThrow()
expect(() => parseJsonImport('{}', TEST_PROJECT_ID)).toThrow()
@@ -323,12 +323,12 @@ describe('CLI Export - parseMarkdownImport', () => {
})
test('exports parseMarkdownImport function', async () => {
const { parseMarkdownImport } = await import('../src/cli/export.ts')
const { parseMarkdownImport } = await import('../src/cli/commands/import.ts')
expect(typeof parseMarkdownImport).toBe('function')
})
test('parseMarkdownImport parses scoped sections', async () => {
const { parseMarkdownImport } = await import('../src/cli/export.ts')
const { parseMarkdownImport } = await import('../src/cli/commands/import.ts')
const markdownContent = `# Memory Export
@@ -353,7 +353,7 @@ Adopted Prettier for formatting
})
test('parseMarkdownImport falls back to parsing any content', async () => {
const { parseMarkdownImport } = await import('../src/cli/export.ts')
const { parseMarkdownImport } = await import('../src/cli/commands/import.ts')
const markdownContent = `# My Memories
@@ -381,7 +381,7 @@ describe('CLI Export - database integration', () => {
})
test('can query memories from database', async () => {
const { formatAsJson } = await import('../src/cli/export.ts')
const { formatAsJson } = await import('../src/cli/commands/export.ts')
const db = createTestDb(tempDir)
insertTestMemories(db, TEST_PROJECT_ID)
@@ -404,7 +404,7 @@ describe('CLI Export - database integration', () => {
})
test('can filter by scope', async () => {
const { formatAsJson } = await import('../src/cli/export.ts')
const { formatAsJson } = await import('../src/cli/commands/export.ts')
const db = createTestDb(tempDir)
insertTestMemories(db, TEST_PROJECT_ID)
+1
View File
@@ -68,5 +68,6 @@ export const PluginConfigSchema = z.object({
embedding: EmbeddingConfigSchema,
dedupThreshold: z.number().min(0).max(1).default(0.25),
logging: LoggingConfigSchema.optional(),
executionModel: z.string().optional(),
})
export type PluginConfig = z.infer<typeof PluginConfigSchema>