Add memory plugin with semantic search and session planning (#145)

* Add memory plugin with semantic search and session planning

* Clarify Memory Plugin is optional in docs
This commit is contained in:
Chris Scott authored and GitHub committed 2026-02-23 15:08:56 -05:00
1 parent da283a82cf
commit 3461f86556
132 files changed
+11448 -2834

No files matched your search

+3 -263
View File
@@ -7,7 +7,7 @@ import { resolveGitIdentity, createGitIdentityEnv, isSSHUrl } from '../../utils/
import { isNoUpstreamError, parseBranchNameFromError } from '../../utils/git-errors'
import { SettingsService } from '../settings'
import type { Database } from 'bun:sqlite'
import type { GitBranch, GitCommit, FileDiffResponse, GitDiffOptions, GitStatusResponse, GitFileStatus, GitFileStatusType, CommitDetails, CommitFile } from '../../types/git'
import type { GitBranch, GitCommit, FileDiffResponse, GitDiffOptions, GitStatusResponse, GitFileStatus, GitFileStatusType } from '../../types/git'
import type { GitCredential } from '@opencode-manager/shared'
import path from 'path'
@@ -269,252 +269,6 @@ export class GitService {
}
}
async discardChanges(repoId: number, paths: string[], staged: boolean, database: Database): Promise<string> {
try {
const repo = getRepoById(database, repoId)
if (!repo) {
throw new Error(`Repository not found`)
}
const repoPath = repo.fullPath
const env = this.gitAuthService.getGitEnvironment()
if (paths.length === 0) {
return ''
}
if (staged) {
const args = ['git', '-C', repoPath, 'restore', '--staged', '--worktree', '--source', 'HEAD', '--', ...paths]
return await executeCommand(args, { env })
}
const statusOutput = await executeCommand(
['git', '-C', repoPath, 'status', '--porcelain', '-u', '--', ...paths],
{ env }
)
const untrackedPaths: string[] = []
const trackedPaths: string[] = []
for (const line of statusOutput.split('\n')) {
if (!line.trim()) continue
const statusCode = line.substring(0, 2)
const filePath = line.substring(3).trim()
if (statusCode === '??') {
untrackedPaths.push(filePath)
} else {
trackedPaths.push(filePath)
}
}
const results: string[] = []
if (trackedPaths.length > 0) {
const args = ['git', '-C', repoPath, 'checkout', '--', ...trackedPaths]
results.push(await executeCommand(args, { env }))
}
if (untrackedPaths.length > 0) {
try {
const args = ['git', '-C', repoPath, 'clean', '-fd', '--', ...untrackedPaths]
results.push(await executeCommand(args, { env }))
} catch (error: unknown) {
logger.error(`Failed to clean untracked files for repo ${repoId}:`, error)
throw error
}
}
return results.join('\n')
} catch (error: unknown) {
logger.error(`Failed to discard changes for repo ${repoId}:`, error)
throw error
}
}
private normalizeRenamePath(path: string): string {
const renamePattern = /\{[^=]+=>\s*([^}]+)\}/
let normalized = path
while (renamePattern.test(normalized)) {
normalized = normalized.replace(renamePattern, '$1')
}
return normalized.trim()
}
private parseNumstatOutput(output: string): Map<string, { additions: number; deletions: number }> {
const map = new Map<string, { additions: number; deletions: number }>()
const lines = output.trim().split('\n')
for (const line of lines) {
if (!line.trim()) continue
const parts = line.split('\t')
if (parts.length >= 3) {
const additions = parts[0]
const deletions = parts[1]
const filePath = parts.slice(2).join('\t')
const normalizedPath = this.normalizeRenamePath(filePath)
if (
additions?.match(/^\d+$/) &&
deletions?.match(/^\d+$/) &&
normalizedPath
) {
map.set(normalizedPath, {
additions: parseInt(additions, 10),
deletions: parseInt(deletions, 10)
})
}
}
}
return map
}
private parseCommitFiles(
output: string,
numstatMap: Map<string, { additions: number; deletions: number }>
): CommitFile[] {
const files: CommitFile[] = []
const lines = output.trim().split('\n')
for (const line of lines) {
if (!line.trim()) continue
const parts = line.split('\t')
if (parts.length >= 2 && parts[0] && parts[0].match(/^[AMDRC]/)) {
const statusCode = parts[0]
const fromPath = parts[1] || ''
const toPath = parts[2] || parts[1] || ''
const isRename = statusCode.startsWith('R')
const isCopy = statusCode.startsWith('C')
let status: GitFileStatusType = 'modified'
switch (statusCode.charAt(0)) {
case 'A':
status = 'added'
break
case 'D':
status = 'deleted'
break
case 'R':
status = 'renamed'
break
case 'C':
status = 'copied'
break
case 'M':
status = 'modified'
break
}
const numstatData = numstatMap.get(toPath)
const additions = numstatData?.additions ?? 0
const deletions = numstatData?.deletions ?? 0
files.push({
path: toPath,
status,
oldPath: isRename || isCopy ? fromPath : undefined,
additions,
deletions
})
}
}
return files
}
async getCommitDetails(repoId: number, hash: string, database: Database): Promise<CommitDetails | null> {
try {
const repo = getRepoById(database, repoId)
if (!repo) {
throw new Error(`Repository not found: ${repoId}`)
}
const repoPath = path.resolve(repo.fullPath)
const env = this.gitAuthService.getGitEnvironment(true)
const commitOutput = await executeCommand(
['git', '-C', repoPath, 'log', '-1', '--format=%H%x00%an%x00%ae%x00%at%x00%B', hash],
{ env }
)
if (!commitOutput.trim()) {
return null
}
const parts = commitOutput.trim().split('\0')
const [commitHash, authorName, authorEmail, timestamp, message] = parts
if (!commitHash) {
return null
}
const filesOutput = await executeCommand(
['git', '-C', repoPath, 'show', '-M', '--name-status', '--format=', hash],
{ env }
)
const numstatOutput = await executeCommand(
['git', '-C', repoPath, 'show', '-M', '--numstat', '--format=', hash],
{ env }
)
const numstatMap = this.parseNumstatOutput(numstatOutput)
const files = this.parseCommitFiles(filesOutput, numstatMap)
return {
hash: commitHash,
authorName: authorName || '',
authorEmail: authorEmail || '',
date: timestamp || '',
message: message || '',
unpushed: await this.isCommitUnpushed(repoPath, commitHash, env),
files
}
} catch (error: unknown) {
logger.error(`Failed to get commit details for repo ${repoId}:`, error)
throw new Error(`Failed to get commit details: ${getErrorMessage(error)}`)
}
}
async getCommitDiff(repoId: number, hash: string, filePath: string, database: Database): Promise<FileDiffResponse> {
try {
const repo = getRepoById(database, repoId)
if (!repo) {
throw new Error(`Repository not found: ${repoId}`)
}
const repoPath = path.resolve(repo.fullPath)
const env = this.gitAuthService.getGitEnvironment(true)
const diff = await executeCommand(
['git', '-C', repoPath, 'show', '--format=', hash, '--', filePath],
{ env }
)
const status = this.detectDiffStatus(diff)
return this.parseDiffOutput(diff, status, filePath)
} catch (error: unknown) {
logger.error(`Failed to get commit diff for repo ${repoId}:`, error)
throw new Error(`Failed to get commit diff: ${getErrorMessage(error)}`)
}
}
private detectDiffStatus(diff: string): GitFileStatusType {
if (diff.includes('new file mode')) {
return 'added'
}
if (diff.includes('deleted file mode')) {
return 'deleted'
}
if (diff.includes('rename from') || diff.includes('rename to')) {
return 'renamed'
}
return 'modified'
}
private async setupSSHIfNeeded(repoUrl: string | undefined, database: Database): Promise<void> {
await this.gitAuthService.setupSSHForRepoUrl(repoUrl, database)
}
@@ -915,7 +669,6 @@ export class GitService {
let additions = 0
let deletions = 0
let isBinary = false
const MAX_DIFF_SIZE = 500 * 1024
if (typeof diff === 'string') {
if (diff.includes('Binary files') || diff.includes('GIT binary patch')) {
@@ -929,21 +682,13 @@ export class GitService {
}
}
let diffOutput = typeof diff === 'string' ? diff : ''
let truncated = false
if (diffOutput.length > MAX_DIFF_SIZE) {
diffOutput = diffOutput.substring(0, MAX_DIFF_SIZE) + '\n\n... (diff truncated due to size)'
truncated = true
}
return {
path: filePath || '',
status: status as GitFileStatusType,
diff: diffOutput,
diff: typeof diff === 'string' ? diff : '',
additions,
deletions,
isBinary,
truncated
isBinary
}
}
@@ -956,11 +701,6 @@ export class GitService {
}
}
private async isCommitUnpushed(repoPath: string, commitHash: string, env: Record<string, string>): Promise<boolean> {
const unpushedHashes = await this.getUnpushedCommitHashes(repoPath, env)
return unpushedHashes.has(commitHash)
}
private async getUnpushedCommitHashes(repoPath: string, env: Record<string, string>): Promise<Set<string>> {
try {
const output = await executeCommand(
+1 -13
View File
@@ -17,6 +17,7 @@ import { decryptSecret } from '../utils/crypto'
import { SettingsService } from './settings'
import { getWorkspacePath, getOpenCodeConfigFilePath, ENV } from '@opencode-manager/shared/config/env'
import type { Database } from 'bun:sqlite'
import { compareVersions } from '../utils/version-utils'
const OPENCODE_SERVER_PORT = ENV.OPENCODE.PORT
const OPENCODE_SERVER_HOST = ENV.OPENCODE.HOST
@@ -25,19 +26,6 @@ const OPENCODE_CONFIG_PATH = getOpenCodeConfigFilePath()
const MIN_OPENCODE_VERSION = '1.0.137'
const MAX_STDERR_SIZE = 10240
function compareVersions(v1: string, v2: string): number {
const parts1 = v1.split('.').map(Number)
const parts2 = v2.split('.').map(Number)
for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
const p1 = parts1[i] || 0
const p2 = parts2[i] || 0
if (p1 > p2) return 1
if (p1 < p2) return -1
}
return 0
}
class OpenCodeServerManager {
private static instance: OpenCodeServerManager
private serverProcess: ReturnType<typeof spawn> | null = null
+242
View File
@@ -0,0 +1,242 @@
import { Database } from 'bun:sqlite'
import path from 'path'
import { existsSync } from 'node:fs'
import { getWorkspacePath } from '@opencode-manager/shared/config/env'
export interface PluginMemory {
id: number
projectId: string
scope: 'convention' | 'decision' | 'context'
content: string
filePath: string | null
accessCount: number
lastAccessedAt: number | null
createdAt: number
updatedAt: number
}
interface DbMemoryRow {
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
}
interface MemoryFilters {
scope?: 'convention' | 'decision' | 'context'
content?: string
limit?: number
offset?: number
}
function getPluginDbPath(): string {
return path.join(getWorkspacePath(), '.opencode', 'state', 'opencode', 'memory', 'memory.db')
}
function mapRowToMemory(row: DbMemoryRow): PluginMemory {
return {
id: row.id,
projectId: row.project_id,
scope: row.scope as PluginMemory['scope'],
content: row.content,
filePath: row.file_path,
accessCount: row.access_count,
lastAccessedAt: row.last_accessed_at,
createdAt: row.created_at,
updatedAt: row.updated_at,
}
}
export class PluginMemoryService {
private db: Database | null = null
getDb(): Database | null {
if (this.db) return this.db
const dbPath = getPluginDbPath()
if (!existsSync(dbPath)) {
return null
}
try {
this.db = new Database(dbPath)
this.db.exec('PRAGMA journal_mode = WAL')
return this.db
} catch {
return null
}
}
list(projectId: string, filters?: MemoryFilters): PluginMemory[] {
const db = this.getDb()
if (!db) return []
let sql = 'SELECT * FROM memories WHERE project_id = ?'
const params: (string | number)[] = [projectId]
if (filters?.scope) {
sql += ' AND scope = ?'
params.push(filters.scope)
}
if (filters?.content) {
sql += ' AND content LIKE ?'
params.push(`%${filters.content}%`)
}
sql += ' ORDER BY updated_at DESC'
if (filters?.limit) {
sql += ' LIMIT ?'
params.push(filters.limit)
}
if (filters?.offset) {
sql += ' OFFSET ?'
params.push(filters.offset)
}
const stmt = db.prepare(sql)
const rows = stmt.all(...params) as DbMemoryRow[]
return rows.map(mapRowToMemory)
}
listAll(filters?: { projectId?: string; scope?: string; limit?: number; offset?: number }): PluginMemory[] {
const db = this.getDb()
if (!db) return []
let sql = 'SELECT * FROM memories WHERE 1=1'
const params: (string | number)[] = []
if (filters?.projectId) {
sql += ' AND project_id = ?'
params.push(filters.projectId)
}
if (filters?.scope) {
sql += ' AND scope = ?'
params.push(filters.scope)
}
sql += ' ORDER BY updated_at DESC'
if (filters?.limit) {
sql += ' LIMIT ?'
params.push(filters.limit)
}
if (filters?.offset) {
sql += ' OFFSET ?'
params.push(filters.offset)
}
const stmt = db.prepare(sql)
const rows = stmt.all(...params) as DbMemoryRow[]
return rows.map(mapRowToMemory)
}
getById(id: number): PluginMemory | undefined {
const db = this.getDb()
if (!db) return undefined
const stmt = db.prepare('SELECT * FROM memories WHERE id = ?')
const row = stmt.get(id) as DbMemoryRow | undefined
return row ? mapRowToMemory(row) : undefined
}
create(input: { projectId: string; scope: string; content: string }): number {
const db = this.getDb()
if (!db) throw new Error('Plugin database not available')
const now = Date.now()
const stmt = db.prepare(`
INSERT INTO memories (project_id, scope, content, access_count, created_at, updated_at)
VALUES (?, ?, ?, 0, ?, ?)
`)
const result = stmt.run(input.projectId, input.scope, input.content, now, now)
return result.lastInsertRowid as number
}
update(id: number, input: { content?: string; scope?: string }): void {
const db = this.getDb()
if (!db) throw new Error('Plugin database not available')
const updates: string[] = []
const params: (string | number)[] = []
if (input.content !== undefined) {
updates.push('content = ?')
params.push(input.content)
}
if (input.scope !== undefined) {
updates.push('scope = ?')
params.push(input.scope)
}
if (updates.length === 0) return
updates.push('updated_at = ?')
params.push(Date.now())
params.push(id)
const sql = `UPDATE memories SET ${updates.join(', ')} WHERE id = ?`
const stmt = db.prepare(sql)
stmt.run(...params)
try {
const deleteEmbeddings = db.prepare('DELETE FROM memory_embeddings WHERE memory_id = ?')
deleteEmbeddings.run(id)
} catch {
// table may not exist
}
}
delete(id: number): void {
const db = this.getDb()
if (!db) throw new Error('Plugin database not available')
try {
const deleteEmbeddings = db.prepare('DELETE FROM memory_embeddings WHERE memory_id = ?')
deleteEmbeddings.run(id)
} catch {
// table may not exist
}
const stmt = db.prepare('DELETE FROM memories WHERE id = ?')
stmt.run(id)
}
getStats(projectId: string): { projectId: string; total: number; byScope: Record<string, number> } {
const db = this.getDb()
if (!db) {
return { projectId, total: 0, byScope: {} }
}
const totalStmt = db.prepare('SELECT COUNT(*) as count FROM memories WHERE project_id = ?')
const totalResult = totalStmt.get(projectId) as { count: number }
const total = totalResult.count
const byScopeStmt = db.prepare('SELECT scope, COUNT(*) as count FROM memories WHERE project_id = ? GROUP BY scope')
const byScopeRows = byScopeStmt.all(projectId) as { scope: string; count: number }[]
const byScope: Record<string, number> = {}
for (const row of byScopeRows) {
byScope[row.scope] = row.count
}
return { projectId, total, byScope }
}
close(): void {
if (this.db) {
this.db.close()
this.db = null
}
}
}
@@ -0,0 +1,68 @@
import { exec } from 'child_process'
import { readFile } from 'fs/promises'
import { fileExists } from './file-operations'
const projectIdCache = new Map<string, string>()
async function executeGitCommand(cwd: string, args: string[]): Promise<string> {
return new Promise((resolve, reject) => {
exec('git ' + args.join(' '), { cwd }, (error, stdout) => {
if (error) {
reject(error)
} else {
resolve(stdout.trim())
}
})
})
}
export async function resolveProjectId(repoFullPath: string): Promise<string | null> {
if (projectIdCache.has(repoFullPath)) {
return projectIdCache.get(repoFullPath) ?? null
}
const cacheFile = `${repoFullPath}/.git/opencode`
const cacheExists = await fileExists(cacheFile)
if (cacheExists) {
try {
const cachedId = (await readFile(cacheFile, 'utf-8')).trim()
if (cachedId) {
projectIdCache.set(repoFullPath, cachedId)
return cachedId
}
} catch {
// cache file may not exist or be readable
}
}
try {
const gitDir = `${repoFullPath}/.git`
const gitDirExists = await fileExists(gitDir)
if (!gitDirExists) {
return null
}
const output = await executeGitCommand(repoFullPath, [
'rev-list',
'--max-parents=0',
'--all',
])
if (!output) {
return null
}
const commits = output.split('\n').filter(Boolean).sort()
const projectId = commits[0]
if (!projectId) {
return null
}
projectIdCache.set(repoFullPath, projectId)
return projectId
} catch {
return null
}
}
+6 -28
View File
@@ -9,6 +9,7 @@ import type { GitAuthService } from './git-auth'
import { isGitHubHttpsUrl, isSSHUrl, normalizeSSHUrl } from '../utils/git-auth'
import path from 'path'
import { parseSSHHost } from '../utils/ssh-key-manager'
import { getErrorMessage } from '../utils/error-utils'
const GIT_CLONE_TIMEOUT = 300000
@@ -38,29 +39,6 @@ function enhanceCloneError(error: unknown, repoUrl: string, originalMessage: str
return error instanceof Error ? error : new Error(originalMessage)
}
interface ErrorWithMessage {
message: string
}
function isErrorWithMessage(error: unknown): error is ErrorWithMessage {
return (
typeof error === 'object' &&
error !== null &&
'message' in error &&
typeof (error as ErrorWithMessage).message === 'string'
)
}
function getErrorMessage(error: unknown): string {
if (isErrorWithMessage(error)) {
return error.message
}
if (error instanceof Error) {
return error.message
}
return String(error)
}
async function hasCommits(repoPath: string, env: Record<string, string>): Promise<boolean> {
try {
await executeCommand(['git', '-C', repoPath, 'rev-parse', 'HEAD'], { env, silent: true })
@@ -197,7 +175,7 @@ export async function initLocalRepo(
throw new Error(`Directory exists but is not a valid Git repository. Please provide either a Git repository path or a simple directory name to create a new empty repository.`)
}
} catch (error: unknown) {
if (isErrorWithMessage(error) && getErrorMessage(error).includes('No such file or directory')) {
if (getErrorMessage(error).includes('No such file or directory')) {
throw error
}
throw new Error(`Failed to process absolute path '${normalizedInputPath}': ${getErrorMessage(error)}`)
@@ -393,12 +371,12 @@ export async function cloneRepo(
try {
await executeCommand(['git', 'clone', '-b', branch, normalizedRepoUrl, worktreeDirName], { cwd: getReposPath(), env, timeout: GIT_CLONE_TIMEOUT })
} catch (error: unknown) {
if (isErrorWithMessage(error) && getErrorMessage(error).includes('destination path') && getErrorMessage(error).includes('already exists')) {
if (getErrorMessage(error).includes('destination path') && getErrorMessage(error).includes('already exists')) {
logger.error(`Clone failed: directory still exists after cleanup attempt`)
throw new Error(`Workspace directory ${worktreeDirName} already exists. Please delete it manually or contact support.`)
}
if (branch && isErrorWithMessage(error) && (getErrorMessage(error).includes('Remote branch') || getErrorMessage(error).includes('not found'))) {
if (branch && (getErrorMessage(error).includes('Remote branch') || getErrorMessage(error).includes('not found'))) {
logger.info(`Branch '${branch}' not found, cloning default branch and creating branch locally`)
try {
await executeCommand(['git', 'clone', normalizedRepoUrl, worktreeDirName], { cwd: getReposPath(), env, timeout: GIT_CLONE_TIMEOUT })
@@ -496,12 +474,12 @@ export async function cloneRepo(
await executeCommand(cloneCmd, { cwd: getReposPath(), env, timeout: GIT_CLONE_TIMEOUT })
} catch (error: unknown) {
if (isErrorWithMessage(error) && getErrorMessage(error).includes('destination path') && getErrorMessage(error).includes('already exists')) {
if (getErrorMessage(error).includes('destination path') && getErrorMessage(error).includes('already exists')) {
logger.error(`Clone failed: directory still exists after cleanup attempt`)
throw new Error(`Workspace directory ${worktreeDirName} already exists. Please delete it manually or contact support.`)
}
if (branch && isErrorWithMessage(error) && (getErrorMessage(error).includes('Remote branch') || getErrorMessage(error).includes('not found'))) {
if (branch && (getErrorMessage(error).includes('Remote branch') || getErrorMessage(error).includes('not found'))) {
logger.info(`Branch '${branch}' not found, cloning default branch and creating branch locally`)
try {
await executeCommand(['git', 'clone', normalizedRepoUrl, worktreeDirName], { cwd: getReposPath(), env, timeout: GIT_CLONE_TIMEOUT })