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

+118
View File
@@ -0,0 +1,118 @@
import { Database } from 'bun:sqlite'
import { logger } from '../utils/logger'
export interface Migration {
version: number
name: string
up(db: Database): void
down(db: Database): void
}
interface MigrationRecord {
version: number
name: string
applied_at: number
}
function ensureMigrationsTable(db: Database): void {
db.run(`
CREATE TABLE IF NOT EXISTS schema_migrations (
version INTEGER PRIMARY KEY,
name TEXT NOT NULL,
applied_at INTEGER NOT NULL
)
`)
}
function getAppliedVersions(db: Database): Set<number> {
const rows = db.prepare('SELECT version FROM schema_migrations ORDER BY version').all() as MigrationRecord[]
return new Set(rows.map(r => r.version))
}
function markApplied(db: Database, migration: Migration): void {
db.prepare('INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)')
.run(migration.version, migration.name, Date.now())
}
function markReverted(db: Database, version: number): void {
db.prepare('DELETE FROM schema_migrations WHERE version = ?').run(version)
}
export function migrate(db: Database, migrations: Migration[]): void {
ensureMigrationsTable(db)
const applied = getAppliedVersions(db)
const sorted = [...migrations].sort((a, b) => a.version - b.version)
const pending = sorted.filter(m => !applied.has(m.version))
if (pending.length === 0) {
logger.info('Database schema is up to date')
return
}
logger.info(`Running ${pending.length} pending migration(s)`)
for (const migration of pending) {
logger.info(`Applying migration ${migration.version}: ${migration.name}`)
db.run('BEGIN TRANSACTION')
try {
migration.up(db)
markApplied(db, migration)
db.run('COMMIT')
logger.info(`Migration ${migration.version} applied successfully`)
} catch (error) {
db.run('ROLLBACK')
logger.error(`Migration ${migration.version} failed:`, error)
throw error
}
}
logger.info('All migrations applied successfully')
}
export function rollback(db: Database, migrations: Migration[], targetVersion?: number): void {
ensureMigrationsTable(db)
const applied = getAppliedVersions(db)
const sorted = [...migrations]
.filter(m => applied.has(m.version))
.sort((a, b) => b.version - a.version)
if (sorted.length === 0) {
logger.info('No migrations to rollback')
return
}
const latest = sorted[0]
if (!latest) {
logger.info('No migrations to rollback')
return
}
const target = targetVersion ?? latest.version - 1
const toRevert = sorted.filter(m => m.version > target)
if (toRevert.length === 0) {
logger.info('No migrations to rollback')
return
}
logger.info(`Rolling back ${toRevert.length} migration(s) to version ${target}`)
for (const migration of toRevert) {
logger.info(`Reverting migration ${migration.version}: ${migration.name}`)
db.run('BEGIN TRANSACTION')
try {
migration.down(db)
markReverted(db, migration.version)
db.run('COMMIT')
logger.info(`Migration ${migration.version} reverted successfully`)
} catch (error) {
db.run('ROLLBACK')
logger.error(`Rollback of migration ${migration.version} failed:`, error)
throw error
}
}
logger.info('Rollback completed successfully')
}
-188
View File
@@ -1,188 +0,0 @@
import { Database } from 'bun:sqlite'
import { logger } from '../utils/logger'
interface ColumnInfo {
cid: number
name: string
type: string
notnull: number
dflt_value: unknown
pk: number
}
export function runMigrations(db: Database): void {
try {
const tableInfo = db.prepare("PRAGMA table_info(repos)").all() as ColumnInfo[]
const repoUrlColumn = tableInfo.find((col: ColumnInfo) => col.name === 'repo_url')
if (repoUrlColumn && repoUrlColumn.notnull === 1) {
logger.info('Migrating repos table to allow nullable repo_url for local repos')
db.run('BEGIN TRANSACTION')
try {
db.run(`
CREATE TABLE repos_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
repo_url TEXT,
local_path TEXT NOT NULL,
branch TEXT,
default_branch TEXT,
clone_status TEXT NOT NULL,
cloned_at INTEGER NOT NULL,
last_pulled INTEGER,
opencode_config_name TEXT,
is_worktree BOOLEAN DEFAULT FALSE,
is_local BOOLEAN DEFAULT FALSE
)
`)
const existingColumns = tableInfo.map((col: ColumnInfo) => col.name)
const columnsToCopy = ['id', 'repo_url', 'local_path', 'branch', 'default_branch', 'clone_status', 'cloned_at', 'last_pulled', 'opencode_config_name', 'is_worktree', 'is_local']
.filter(col => existingColumns.includes(col))
const columnsStr = columnsToCopy.join(', ')
db.run(`INSERT INTO repos_new (${columnsStr}) SELECT ${columnsStr} FROM repos`)
db.run('DROP TABLE repos')
db.run('ALTER TABLE repos_new RENAME TO repos')
db.run('COMMIT')
logger.info('Successfully migrated repos table to allow nullable repo_url')
} catch (migrationError) {
db.run('ROLLBACK')
throw migrationError
}
}
const hasBranchColumn = tableInfo.some(col => col.name === 'branch')
if (!hasBranchColumn) {
logger.info('Adding missing branch column to repos table')
db.run('ALTER TABLE repos ADD COLUMN branch TEXT')
}
try {
db.run(`
CREATE UNIQUE INDEX IF NOT EXISTS idx_repo_url_branch
ON repos(repo_url, branch)
WHERE branch IS NOT NULL
`)
} catch (error) {
logger.warn('Index already exists or could not be created', error)
}
try {
db.run(`
CREATE UNIQUE INDEX IF NOT EXISTS idx_local_path
ON repos(local_path)
`)
} catch (error) {
logger.warn('Local path index already exists or could not be created', error)
}
const requiredColumns = [
{ name: 'default_branch', sql: 'ALTER TABLE repos ADD COLUMN default_branch TEXT' },
{ name: 'clone_status', sql: 'ALTER TABLE repos ADD COLUMN clone_status TEXT NOT NULL DEFAULT "cloning"' },
{ name: 'cloned_at', sql: 'ALTER TABLE repos ADD COLUMN cloned_at INTEGER NOT NULL DEFAULT 0' },
{ name: 'last_pulled', sql: 'ALTER TABLE repos ADD COLUMN last_pulled INTEGER' },
{ name: 'opencode_config_name', sql: 'ALTER TABLE repos ADD COLUMN opencode_config_name TEXT' },
{ name: 'is_worktree', sql: 'ALTER TABLE repos ADD COLUMN is_worktree BOOLEAN DEFAULT FALSE' },
{ name: 'is_local', sql: 'ALTER TABLE repos ADD COLUMN is_local BOOLEAN DEFAULT FALSE' }
]
for (const column of requiredColumns) {
const hasColumn = tableInfo.some(col => col.name === column.name)
if (!hasColumn) {
logger.info(`Adding missing column: ${column.name}`)
try {
db.run(column.sql)
} catch (error) {
logger.debug(`Column ${column.name} might already exist:`, error)
}
}
}
const indexes = [
'CREATE INDEX IF NOT EXISTS idx_repo_clone_status ON repos(clone_status)',
'CREATE INDEX IF NOT EXISTS idx_user_id ON user_preferences(user_id)',
'CREATE INDEX IF NOT EXISTS idx_opencode_user_id ON opencode_configs(user_id)',
'CREATE INDEX IF NOT EXISTS idx_opencode_default ON opencode_configs(user_id, is_default)'
]
for (const indexSql of indexes) {
try {
db.run(indexSql)
} catch (error) {
logger.warn('Index already exists:', error)
}
}
try {
const repos = db.prepare("SELECT id, local_path FROM repos WHERE local_path LIKE 'repos/%'").all() as Array<{
id: number
local_path: string
}>
if (repos.length > 0) {
logger.info(`Migrating ${repos.length} repos to remove 'repos/' prefix from local_path`)
const updateStmt = db.prepare("UPDATE repos SET local_path = ? WHERE id = ?")
for (const repo of repos) {
const newPath = repo.local_path.replace(/^repos\//, '')
updateStmt.run(newPath, repo.id)
logger.info(`Updated repo ${repo.id}: ${repo.local_path} -> ${newPath}`)
}
}
} catch (error) {
logger.error('Failed to migrate local_path format:', error)
}
migrateGitTokenToCredentials(db)
logger.info('Database migrations completed successfully')
} catch (error) {
logger.error('Failed to run database migrations:', error)
throw error
}
}
function migrateGitTokenToCredentials(db: Database): void {
try {
const rows = db.prepare('SELECT user_id, preferences FROM user_preferences').all() as Array<{
user_id: string
preferences: string
}>
for (const row of rows) {
try {
const parsed = JSON.parse(row.preferences) as Record<string, unknown>
const gitToken = parsed.gitToken as string | undefined
const existingCredentials = parsed.gitCredentials as Array<unknown> | undefined
if (!gitToken) {
continue
}
if (existingCredentials && existingCredentials.length > 0) {
continue
}
const { gitToken: _, ...rest } = parsed
void _
const migrated = {
...rest,
gitCredentials: [{
name: 'GitHub',
host: 'https://github.com/',
token: gitToken,
}],
}
db.prepare('UPDATE user_preferences SET preferences = ? WHERE user_id = ?')
.run(JSON.stringify(migrated), row.user_id)
logger.info(`Migrated gitToken to gitCredentials for user: ${row.user_id}`)
} catch (parseError) {
logger.error(`Failed to parse preferences for user ${row.user_id}:`, parseError)
}
}
} catch (error) {
logger.error('Failed to migrate gitToken to gitCredentials:', error)
}
}
@@ -0,0 +1,177 @@
import type { Migration } from '../migration-runner'
const migration: Migration = {
version: 1,
name: 'base-schema',
up(db) {
db.run(`
CREATE TABLE IF NOT EXISTS repos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
repo_url TEXT,
local_path TEXT NOT NULL,
branch TEXT,
default_branch TEXT,
clone_status TEXT NOT NULL,
cloned_at INTEGER NOT NULL,
last_pulled INTEGER,
opencode_config_name TEXT,
is_worktree BOOLEAN DEFAULT FALSE,
is_local BOOLEAN DEFAULT FALSE
)
`)
db.run('CREATE INDEX IF NOT EXISTS idx_repo_clone_status ON repos(clone_status)')
db.run(`
CREATE TABLE IF NOT EXISTS user_preferences (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL DEFAULT 'default',
preferences TEXT NOT NULL,
updated_at INTEGER NOT NULL,
UNIQUE(user_id)
)
`)
db.run('CREATE INDEX IF NOT EXISTS idx_user_id ON user_preferences(user_id)')
db.run(`
CREATE TABLE IF NOT EXISTS opencode_configs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL DEFAULT 'default',
config_name TEXT NOT NULL,
config_content TEXT NOT NULL,
is_default BOOLEAN DEFAULT FALSE,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
UNIQUE(user_id, config_name)
)
`)
db.run('CREATE INDEX IF NOT EXISTS idx_opencode_user_id ON opencode_configs(user_id)')
db.run('CREATE INDEX IF NOT EXISTS idx_opencode_default ON opencode_configs(user_id, is_default)')
db.run(`
CREATE TABLE IF NOT EXISTS "user" (
id TEXT PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
emailVerified INTEGER NOT NULL DEFAULT 0,
image TEXT,
createdAt INTEGER NOT NULL,
updatedAt INTEGER NOT NULL,
role TEXT DEFAULT 'user'
)
`)
db.run(`
CREATE TABLE IF NOT EXISTS "session" (
id TEXT PRIMARY KEY NOT NULL,
expiresAt INTEGER NOT NULL,
token TEXT NOT NULL UNIQUE,
createdAt INTEGER NOT NULL,
updatedAt INTEGER NOT NULL,
ipAddress TEXT,
userAgent TEXT,
userId TEXT NOT NULL REFERENCES "user"(id) ON DELETE CASCADE
)
`)
db.run('CREATE INDEX IF NOT EXISTS idx_session_userId ON "session"(userId)')
db.run('CREATE INDEX IF NOT EXISTS idx_session_token ON "session"(token)')
db.run(`
CREATE TABLE IF NOT EXISTS "account" (
id TEXT PRIMARY KEY NOT NULL,
accountId TEXT NOT NULL,
providerId TEXT NOT NULL,
userId TEXT NOT NULL REFERENCES "user"(id) ON DELETE CASCADE,
accessToken TEXT,
refreshToken TEXT,
idToken TEXT,
accessTokenExpiresAt INTEGER,
refreshTokenExpiresAt INTEGER,
scope TEXT,
password TEXT,
createdAt INTEGER NOT NULL,
updatedAt INTEGER NOT NULL
)
`)
db.run('CREATE INDEX IF NOT EXISTS idx_account_userId ON "account"(userId)')
db.run('CREATE UNIQUE INDEX IF NOT EXISTS idx_account_provider ON "account"(providerId, accountId)')
db.run(`
CREATE TABLE IF NOT EXISTS "verification" (
id TEXT PRIMARY KEY NOT NULL,
identifier TEXT NOT NULL,
value TEXT NOT NULL,
expiresAt INTEGER NOT NULL,
createdAt INTEGER,
updatedAt INTEGER
)
`)
db.run('CREATE INDEX IF NOT EXISTS idx_verification_identifier ON "verification"(identifier)')
db.run(`
CREATE TABLE IF NOT EXISTS "passkey" (
id TEXT PRIMARY KEY NOT NULL,
name TEXT,
publicKey TEXT NOT NULL,
userId TEXT NOT NULL REFERENCES "user"(id) ON DELETE CASCADE,
credentialID TEXT NOT NULL,
counter INTEGER NOT NULL,
deviceType TEXT NOT NULL,
backedUp INTEGER NOT NULL DEFAULT 0,
transports TEXT,
createdAt INTEGER,
aaguid TEXT
)
`)
db.run('CREATE INDEX IF NOT EXISTS idx_passkey_userId ON "passkey"(userId)')
db.run('CREATE INDEX IF NOT EXISTS idx_passkey_credentialID ON "passkey"(credentialID)')
db.run(`
CREATE TABLE IF NOT EXISTS trusted_ssh_hosts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
host TEXT NOT NULL UNIQUE,
key_type TEXT NOT NULL,
public_key TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
)
`)
db.run('CREATE INDEX IF NOT EXISTS idx_trusted_ssh_hosts_host ON trusted_ssh_hosts(host)')
db.run(`
CREATE TABLE IF NOT EXISTS repo_settings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
repo_id INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,
key TEXT NOT NULL,
value TEXT NOT NULL,
updated_at INTEGER NOT NULL,
UNIQUE(repo_id, key)
)
`)
db.run('CREATE INDEX IF NOT EXISTS idx_repo_settings_repo ON repo_settings(repo_id)')
},
down(db) {
db.run('DROP TABLE IF EXISTS repo_settings')
db.run('DROP TABLE IF EXISTS trusted_ssh_hosts')
db.run('DROP TABLE IF EXISTS "passkey"')
db.run('DROP TABLE IF EXISTS "verification"')
db.run('DROP TABLE IF EXISTS "account"')
db.run('DROP TABLE IF EXISTS "session"')
db.run('DROP TABLE IF EXISTS "user"')
db.run('DROP TABLE IF EXISTS opencode_configs')
db.run('DROP TABLE IF EXISTS user_preferences')
db.run('DROP TABLE IF EXISTS repos')
},
}
export default migration
@@ -0,0 +1,84 @@
import type { Migration } from '../migration-runner'
interface ColumnInfo {
name: string
notnull: number
}
const migration: Migration = {
version: 2,
name: 'repos-nullable-url',
up(db) {
const tableInfo = db.prepare('PRAGMA table_info(repos)').all() as ColumnInfo[]
const repoUrlColumn = tableInfo.find(col => col.name === 'repo_url')
if (!repoUrlColumn || repoUrlColumn.notnull !== 1) return
const existingColumns = tableInfo.map(col => col.name)
db.run(`
CREATE TABLE repos_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
repo_url TEXT,
local_path TEXT NOT NULL,
branch TEXT,
default_branch TEXT,
clone_status TEXT NOT NULL,
cloned_at INTEGER NOT NULL,
last_pulled INTEGER,
opencode_config_name TEXT,
is_worktree BOOLEAN DEFAULT FALSE,
is_local BOOLEAN DEFAULT FALSE
)
`)
const targetColumns = [
'id', 'repo_url', 'local_path', 'branch', 'default_branch',
'clone_status', 'cloned_at', 'last_pulled', 'opencode_config_name',
'is_worktree', 'is_local'
]
const columnsToCopy = targetColumns.filter(col => existingColumns.includes(col))
const columnsStr = columnsToCopy.join(', ')
db.run(`INSERT INTO repos_new (${columnsStr}) SELECT ${columnsStr} FROM repos`)
db.run('DROP TABLE repos')
db.run('ALTER TABLE repos_new RENAME TO repos')
db.run('CREATE INDEX IF NOT EXISTS idx_repo_clone_status ON repos(clone_status)')
},
down(db) {
const tableInfo = db.prepare('PRAGMA table_info(repos)').all() as ColumnInfo[]
const existingColumns = tableInfo.map(col => col.name)
db.run(`
CREATE TABLE repos_old (
id INTEGER PRIMARY KEY AUTOINCREMENT,
repo_url TEXT NOT NULL,
local_path TEXT NOT NULL,
branch TEXT,
default_branch TEXT,
clone_status TEXT NOT NULL,
cloned_at INTEGER NOT NULL,
last_pulled INTEGER,
opencode_config_name TEXT,
is_worktree BOOLEAN DEFAULT FALSE,
is_local BOOLEAN DEFAULT FALSE
)
`)
const targetColumns = [
'id', 'repo_url', 'local_path', 'branch', 'default_branch',
'clone_status', 'cloned_at', 'last_pulled', 'opencode_config_name',
'is_worktree', 'is_local'
]
const columnsToCopy = targetColumns.filter(col => existingColumns.includes(col))
const columnsStr = columnsToCopy.join(', ')
db.run(`INSERT INTO repos_old (${columnsStr}) SELECT ${columnsStr} FROM repos WHERE repo_url IS NOT NULL`)
db.run('DROP TABLE repos')
db.run('ALTER TABLE repos_old RENAME TO repos')
db.run('CREATE INDEX IF NOT EXISTS idx_repo_clone_status ON repos(clone_status)')
},
}
export default migration
@@ -0,0 +1,38 @@
import type { Migration } from '../migration-runner'
interface ColumnInfo {
name: string
}
const COLUMNS = [
{ name: 'branch', sql: 'ALTER TABLE repos ADD COLUMN branch TEXT' },
{ name: 'default_branch', sql: 'ALTER TABLE repos ADD COLUMN default_branch TEXT' },
{ name: 'clone_status', sql: 'ALTER TABLE repos ADD COLUMN clone_status TEXT NOT NULL DEFAULT "cloning"' },
{ name: 'cloned_at', sql: 'ALTER TABLE repos ADD COLUMN cloned_at INTEGER NOT NULL DEFAULT 0' },
{ name: 'last_pulled', sql: 'ALTER TABLE repos ADD COLUMN last_pulled INTEGER' },
{ name: 'opencode_config_name', sql: 'ALTER TABLE repos ADD COLUMN opencode_config_name TEXT' },
{ name: 'is_worktree', sql: 'ALTER TABLE repos ADD COLUMN is_worktree BOOLEAN DEFAULT FALSE' },
{ name: 'is_local', sql: 'ALTER TABLE repos ADD COLUMN is_local BOOLEAN DEFAULT FALSE' },
]
const migration: Migration = {
version: 3,
name: 'repos-add-columns',
up(db) {
const tableInfo = db.prepare('PRAGMA table_info(repos)').all() as ColumnInfo[]
const existing = new Set(tableInfo.map(col => col.name))
for (const col of COLUMNS) {
if (!existing.has(col.name)) {
db.run(col.sql)
}
}
},
down(db) {
void db
},
}
export default migration
@@ -0,0 +1,22 @@
import type { Migration } from '../migration-runner'
const migration: Migration = {
version: 4,
name: 'repos-indexes',
up(db) {
db.run(`
CREATE UNIQUE INDEX IF NOT EXISTS idx_repo_url_branch
ON repos(repo_url, branch)
WHERE branch IS NOT NULL
`)
db.run('CREATE UNIQUE INDEX IF NOT EXISTS idx_local_path ON repos(local_path)')
},
down(db) {
db.run('DROP INDEX IF EXISTS idx_repo_url_branch')
db.run('DROP INDEX IF EXISTS idx_local_path')
},
}
export default migration
@@ -0,0 +1,28 @@
import type { Migration } from '../migration-runner'
import { logger } from '../../utils/logger'
const migration: Migration = {
version: 5,
name: 'repos-local-path-prefix',
up(db) {
const repos = db.prepare("SELECT id, local_path FROM repos WHERE local_path LIKE 'repos/%'").all() as Array<{
id: number
local_path: string
}>
if (repos.length === 0) return
logger.info(`Stripping 'repos/' prefix from ${repos.length} repo local_path(s)`)
const stmt = db.prepare('UPDATE repos SET local_path = ? WHERE id = ?')
for (const repo of repos) {
stmt.run(repo.local_path.replace(/^repos\//, ''), repo.id)
}
},
down(db) {
void db
},
}
export default migration
@@ -0,0 +1,74 @@
import type { Migration } from '../migration-runner'
import { logger } from '../../utils/logger'
const migration: Migration = {
version: 6,
name: 'git-token-to-credentials',
up(db) {
const rows = db.prepare('SELECT user_id, preferences FROM user_preferences').all() as Array<{
user_id: string
preferences: string
}>
for (const row of rows) {
try {
const parsed = JSON.parse(row.preferences) as Record<string, unknown>
const gitToken = parsed.gitToken as string | undefined
const existingCredentials = parsed.gitCredentials as Array<unknown> | undefined
if (!gitToken) continue
if (existingCredentials && existingCredentials.length > 0) continue
const { gitToken: _, ...rest } = parsed
void _
const migrated = {
...rest,
gitCredentials: [{
name: 'GitHub',
host: 'https://github.com/',
token: gitToken,
}],
}
db.prepare('UPDATE user_preferences SET preferences = ? WHERE user_id = ?')
.run(JSON.stringify(migrated), row.user_id)
logger.info(`Migrated gitToken to gitCredentials for user: ${row.user_id}`)
} catch (parseError) {
logger.error(`Failed to parse preferences for user ${row.user_id}:`, parseError)
}
}
},
down(db) {
const rows = db.prepare('SELECT user_id, preferences FROM user_preferences').all() as Array<{
user_id: string
preferences: string
}>
for (const row of rows) {
try {
const parsed = JSON.parse(row.preferences) as Record<string, unknown>
const credentials = parsed.gitCredentials as Array<{ token: string }> | undefined
const firstCredential = credentials?.[0]
if (!firstCredential) continue
const { gitCredentials: _, ...rest } = parsed
void _
const reverted = {
...rest,
gitToken: firstCredential.token,
}
db.prepare('UPDATE user_preferences SET preferences = ? WHERE user_id = ?')
.run(JSON.stringify(reverted), row.user_id)
} catch (parseError) {
logger.error(`Failed to revert preferences for user ${row.user_id}:`, parseError)
}
}
},
}
export default migration
+16
View File
@@ -0,0 +1,16 @@
import type { Migration } from '../migration-runner'
import migration001 from './001-base-schema'
import migration002 from './002-repos-nullable-url'
import migration003 from './003-repos-add-columns'
import migration004 from './004-repos-indexes'
import migration005 from './005-repos-local-path-prefix'
import migration006 from './006-git-token-to-credentials'
export const allMigrations: Migration[] = [
migration001,
migration002,
migration003,
migration004,
migration005,
migration006,
]
-7
View File
@@ -94,13 +94,6 @@ export function getRepoById(db: Database, id: number): Repo | null {
return row ? rowToRepo(row) : null
}
export function getRepoByUrl(db: Database, repoUrl: string): Repo | null {
const stmt = db.prepare('SELECT * FROM repos WHERE repo_url = ?')
const row = stmt.get(repoUrl) as RepoRow | undefined
return row ? rowToRepo(row) : null
}
export function getRepoByUrlAndBranch(db: Database, repoUrl: string, branch?: string): Repo | null {
const query = branch
? 'SELECT * FROM repos WHERE repo_url = ? AND branch = ?'
+5 -130
View File
@@ -2,144 +2,19 @@ import { Database } from 'bun:sqlite'
import { logger } from '../utils/logger'
import { mkdirSync } from 'fs'
import { dirname } from 'path'
import { runMigrations } from './migrations'
import { migrate } from './migration-runner'
import { allMigrations } from './migrations'
export function initializeDatabase(dbPath: string = './data/opencode.db'): Database {
mkdirSync(dirname(dbPath), { recursive: true })
const db = new Database(dbPath)
db.run(`
CREATE TABLE IF NOT EXISTS repos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
repo_url TEXT,
local_path TEXT NOT NULL,
branch TEXT,
default_branch TEXT,
clone_status TEXT NOT NULL,
cloned_at INTEGER NOT NULL,
last_pulled INTEGER,
opencode_config_name TEXT,
is_worktree BOOLEAN DEFAULT FALSE,
is_local BOOLEAN DEFAULT FALSE
);
CREATE INDEX IF NOT EXISTS idx_repo_clone_status ON repos(clone_status);
CREATE TABLE IF NOT EXISTS user_preferences (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL DEFAULT 'default',
preferences TEXT NOT NULL,
updated_at INTEGER NOT NULL,
UNIQUE(user_id)
);
CREATE INDEX IF NOT EXISTS idx_user_id ON user_preferences(user_id);
CREATE TABLE IF NOT EXISTS opencode_configs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL DEFAULT 'default',
config_name TEXT NOT NULL,
config_content TEXT NOT NULL,
is_default BOOLEAN DEFAULT FALSE,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
UNIQUE(user_id, config_name)
);
CREATE INDEX IF NOT EXISTS idx_opencode_user_id ON opencode_configs(user_id);
CREATE INDEX IF NOT EXISTS idx_opencode_default ON opencode_configs(user_id, is_default);
-- Better Auth tables
CREATE TABLE IF NOT EXISTS "user" (
id TEXT PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
emailVerified INTEGER NOT NULL DEFAULT 0,
image TEXT,
createdAt INTEGER NOT NULL,
updatedAt INTEGER NOT NULL,
role TEXT DEFAULT 'user'
);
CREATE TABLE IF NOT EXISTS "session" (
id TEXT PRIMARY KEY NOT NULL,
expiresAt INTEGER NOT NULL,
token TEXT NOT NULL UNIQUE,
createdAt INTEGER NOT NULL,
updatedAt INTEGER NOT NULL,
ipAddress TEXT,
userAgent TEXT,
userId TEXT NOT NULL REFERENCES "user"(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_session_userId ON "session"(userId);
CREATE INDEX IF NOT EXISTS idx_session_token ON "session"(token);
CREATE TABLE IF NOT EXISTS "account" (
id TEXT PRIMARY KEY NOT NULL,
accountId TEXT NOT NULL,
providerId TEXT NOT NULL,
userId TEXT NOT NULL REFERENCES "user"(id) ON DELETE CASCADE,
accessToken TEXT,
refreshToken TEXT,
idToken TEXT,
accessTokenExpiresAt INTEGER,
refreshTokenExpiresAt INTEGER,
scope TEXT,
password TEXT,
createdAt INTEGER NOT NULL,
updatedAt INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_account_userId ON "account"(userId);
CREATE UNIQUE INDEX IF NOT EXISTS idx_account_provider ON "account"(providerId, accountId);
CREATE TABLE IF NOT EXISTS "verification" (
id TEXT PRIMARY KEY NOT NULL,
identifier TEXT NOT NULL,
value TEXT NOT NULL,
expiresAt INTEGER NOT NULL,
createdAt INTEGER,
updatedAt INTEGER
);
CREATE INDEX IF NOT EXISTS idx_verification_identifier ON "verification"(identifier);
CREATE TABLE IF NOT EXISTS "passkey" (
id TEXT PRIMARY KEY NOT NULL,
name TEXT,
publicKey TEXT NOT NULL,
userId TEXT NOT NULL REFERENCES "user"(id) ON DELETE CASCADE,
credentialID TEXT NOT NULL,
counter INTEGER NOT NULL,
deviceType TEXT NOT NULL,
backedUp INTEGER NOT NULL DEFAULT 0,
transports TEXT,
createdAt INTEGER,
aaguid TEXT
);
CREATE INDEX IF NOT EXISTS idx_passkey_userId ON "passkey"(userId);
CREATE INDEX IF NOT EXISTS idx_passkey_credentialID ON "passkey"(credentialID);
CREATE TABLE IF NOT EXISTS trusted_ssh_hosts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
host TEXT NOT NULL UNIQUE,
key_type TEXT NOT NULL,
public_key TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
migrate(db, allMigrations)
CREATE INDEX IF NOT EXISTS idx_trusted_ssh_hosts_host ON trusted_ssh_hosts(host);
`)
runMigrations(db)
db.prepare('INSERT OR IGNORE INTO user_preferences (user_id, preferences, updated_at) VALUES (?, ?, ?)')
.run('default', '{}', Date.now())
logger.info('Database initialized successfully')
return db
}
+3
View File
@@ -31,6 +31,7 @@ import { createTitleRoutes } from './routes/title'
import { createSSERoutes } from './routes/sse'
import { createSSHRoutes } from './routes/ssh'
import { createNotificationRoutes } from './routes/notifications'
import { createMemoryRoutes } from './routes/memory'
import { createMcpOauthProxyRoutes } from './routes/mcp-oauth-proxy'
import { createAuthRoutes, createAuthInfoRoutes, syncAdminFromEnv } from './routes/auth'
import { createAuth } from './auth'
@@ -41,6 +42,7 @@ import { SettingsService } from './services/settings'
import { opencodeServerManager } from './services/opencode-single-server'
import { proxyRequest, proxyMcpAuthStart, proxyMcpAuthAuthenticate } from './services/proxy'
import { NotificationService } from './services/notification'
import { logger } from './utils/logger'
import {
getWorkspacePath,
@@ -254,6 +256,7 @@ protectedApi.route('/generate-title', createTitleRoutes())
protectedApi.route('/sse', createSSERoutes())
protectedApi.route('/ssh', createSSHRoutes(gitAuthService))
protectedApi.route('/notifications', createNotificationRoutes(notificationService))
protectedApi.route('/memory', createMemoryRoutes(db))
app.route('/api', protectedApi)
+1 -15
View File
@@ -2,25 +2,11 @@ import { Hono } from 'hono'
import type { Database } from 'bun:sqlite'
import { readFile } from 'fs/promises'
import { opencodeServerManager } from '../services/opencode-single-server'
import { compareVersions } from '../utils/version-utils'
const GITHUB_REPO_OWNER = 'chriswritescode-dev'
const GITHUB_REPO_NAME = 'opencode-manager'
function compareVersions(a: string, b: string): number {
const cleanA = a.replace(/^v/, '')
const cleanB = b.replace(/^v/, '')
const partsA = cleanA.split('.').map(Number)
const partsB = cleanB.split('.').map(Number)
for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) {
const partA = partsA[i] ?? 0
const partB = partsB[i] ?? 0
if (partA > partB) return 1
if (partA < partB) return -1
}
return 0
}
interface CachedRelease {
tagName: string
htmlUrl: string
+446
View File
@@ -0,0 +1,446 @@
import { Hono } from 'hono'
import { Database } from 'bun:sqlite'
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs'
import { join } from 'path'
import { logger } from '../utils/logger'
import { PluginMemoryService } from '../services/plugin-memory'
import { resolveProjectId } from '../services/project-id-resolver'
import { getRepoById } from '../db/queries'
import { getWorkspacePath } from '@opencode-manager/shared/config/env'
import {
CreateMemoryRequestSchema,
UpdateMemoryRequestSchema,
MemoryListQuerySchema,
PluginConfigSchema,
type PluginConfig,
} from '@opencode-manager/shared/schemas'
function resolveMemoryDataDir(): string {
return join(getWorkspacePath(), '.opencode', 'state', 'opencode', 'memory')
}
function resolvePluginConfigPath(): string {
return join(resolveMemoryDataDir(), 'config.json')
}
function getDefaultPluginConfig(): PluginConfig {
return {
embedding: {
provider: 'local',
model: 'all-MiniLM-L6-v2',
dimensions: 384,
},
dedupThreshold: 0.25,
}
}
function loadPluginConfigFromDisk(): PluginConfig {
const configPath = resolvePluginConfigPath()
if (!existsSync(configPath)) {
return getDefaultPluginConfig()
}
try {
const content = readFileSync(configPath, 'utf-8')
const parsed = JSON.parse(content)
const result = PluginConfigSchema.safeParse(parsed)
if (!result.success) {
logger.error('Invalid plugin config:', result.error)
return getDefaultPluginConfig()
}
return result.data
} catch (error) {
logger.error('Failed to load plugin config:', error)
return getDefaultPluginConfig()
}
}
function savePluginConfigToDisk(config: PluginConfig): void {
const configPath = resolvePluginConfigPath()
const dataDir = resolveMemoryDataDir()
if (!existsSync(dataDir)) {
mkdirSync(dataDir, { recursive: true })
}
writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8')
}
export function createMemoryRoutes(db: Database): Hono {
const app = new Hono()
const pluginMemory = new PluginMemoryService()
app.get('/', async (c) => {
const query = c.req.query()
const parsed = MemoryListQuerySchema.safeParse({
projectId: query.projectId,
scope: query.scope,
content: query.content,
limit: query.limit ? parseInt(query.limit, 10) : undefined,
offset: query.offset ? parseInt(query.offset, 10) : undefined,
})
if (!parsed.success) {
return c.json({ error: 'Invalid query parameters', details: parsed.error }, 400)
}
const filters = parsed.data
if (!filters.projectId) {
return c.json({ memories: [] })
}
const memories = pluginMemory.list(filters.projectId, {
scope: filters.scope,
content: filters.content,
limit: filters.limit,
offset: filters.offset,
})
return c.json({ memories })
})
app.post('/', async (c) => {
const body = await c.req.json()
const parsed = CreateMemoryRequestSchema.safeParse(body)
if (!parsed.success) {
return c.json({ error: 'Invalid request', details: parsed.error }, 400)
}
try {
const id = pluginMemory.create(parsed.data)
const memory = pluginMemory.getById(id)
if (!memory) {
return c.json({ error: 'Failed to retrieve created memory' }, 500)
}
return c.json({ memory }, 201)
} catch (error) {
logger.error('Failed to create memory:', error)
return c.json({ error: 'Failed to create memory' }, 500)
}
})
app.get('/project-summary', async (c) => {
const repoIdParam = c.req.query('repoId')
if (!repoIdParam) {
return c.json({ error: 'Missing repoId parameter' }, 400)
}
const repoId = parseInt(repoIdParam, 10)
if (isNaN(repoId)) {
return c.json({ error: 'Invalid repoId' }, 400)
}
try {
const repo = getRepoById(db, repoId)
if (!repo) {
return c.json({ projectId: null, stats: { total: 0, byScope: {} }, error: 'Repository not found' }, 404)
}
const projectId = await resolveProjectId(repo.fullPath)
if (!projectId) {
return c.json({ projectId: null, stats: { total: 0, byScope: {} } })
}
const stats = pluginMemory.getStats(projectId)
return c.json({ projectId, stats })
} catch (error) {
logger.error('Failed to get project summary:', error)
return c.json({ projectId: null, stats: { total: 0, byScope: {} }, error: 'Failed to get project summary' }, 500)
}
})
app.get('/stats', async (c) => {
const projectId = c.req.query('projectId')
if (!projectId) {
return c.json({ error: 'Missing projectId parameter' }, 400)
}
try {
const stats = pluginMemory.getStats(projectId)
return c.json(stats)
} catch (error) {
logger.error('Failed to get memory stats:', error)
return c.json({ error: 'Failed to get stats' }, 500)
}
})
app.get('/resolve-project', async (c) => {
const repoIdParam = c.req.query('repoId')
if (!repoIdParam) {
return c.json({ error: 'Missing repoId parameter' }, 400)
}
const repoId = parseInt(repoIdParam, 10)
if (isNaN(repoId)) {
return c.json({ error: 'Invalid repoId' }, 400)
}
try {
const repo = getRepoById(db, repoId)
if (!repo) {
return c.json({ projectId: null, error: 'Repository not found' }, 404)
}
const projectId = await resolveProjectId(repo.fullPath)
return c.json({ projectId })
} catch (error) {
logger.error('Failed to resolve project ID:', error)
return c.json({ projectId: null, error: 'Failed to resolve project ID' }, 500)
}
})
app.get('/plugin-config', async (c) => {
try {
const config = loadPluginConfigFromDisk()
return c.json({ config })
} catch (error) {
logger.error('Failed to get plugin config:', error)
return c.json({ error: 'Failed to get plugin config' }, 500)
}
})
app.put('/plugin-config', async (c) => {
try {
const body = await c.req.json()
const parsed = PluginConfigSchema.safeParse(body)
if (!parsed.success) {
return c.json({ error: 'Invalid config', details: parsed.error.flatten() }, 400)
}
const config = parsed.data
config.dedupThreshold = Math.max(0.05, Math.min(0.4, config.dedupThreshold ?? 0.25))
savePluginConfigToDisk(config)
return c.json({ success: true, config })
} catch (error) {
logger.error('Failed to save plugin config:', error)
return c.json({ error: 'Failed to save plugin config' }, 500)
}
})
app.post('/test-embedding', async (c) => {
try {
const config = loadPluginConfigFromDisk()
if (config.embedding.provider === 'local') {
const validModels = ['all-MiniLM-L6-v2']
if (!validModels.includes(config.embedding.model)) {
return c.json({
success: false,
error: `Invalid model: ${config.embedding.model}. Valid models: ${validModels.join(', ')}`
}, 400)
}
return c.json({
success: true,
message: 'Local provider configured. Model will be loaded on server restart.',
dimensions: config.embedding.dimensions ?? 384,
})
}
const endpoints: Record<string, string> = {
openai: 'https://api.openai.com/v1/embeddings',
voyage: 'https://api.voyageai.com/v1/embeddings',
}
const extractHost = (url: string): string => {
const protocolEnd = url.indexOf('://')
if (protocolEnd === -1) return url
const pathStart = url.indexOf('/', protocolEnd + 3)
return pathStart === -1 ? url : url.slice(0, pathStart)
}
const baseUrl = extractHost(config.embedding.baseUrl || '')
const endpoint = baseUrl
? `${baseUrl}/v1/embeddings`
: endpoints[config.embedding.provider] ?? ''
if (!endpoint) {
return c.json({ success: false, error: 'No endpoint configured' }, 400)
}
if (!config.embedding.apiKey) {
return c.json({ success: false, error: 'API key not configured. Please save your API key first.' }, 400)
}
const testBody = {
model: config.embedding.model,
input: ['test'],
}
const headers: Record<string, string> = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${config.embedding.apiKey}`,
}
const response = await fetch(endpoint, {
method: 'POST',
headers,
body: JSON.stringify(testBody),
})
if (!response.ok) {
const errorText = await response.text()
return c.json({
success: false,
error: `API error: ${response.status}`,
message: errorText,
}, 400)
}
const data = await response.json() as {
data?: Array<{ embedding: number[] }>
embeddings?: Array<{ embedding: number[] }>
}
const embeddings = data.data || data.embeddings
if (!embeddings || embeddings.length === 0 || !embeddings[0]) {
return c.json({ success: false, error: 'Invalid response from API' }, 400)
}
const firstEmbedding = embeddings[0]
const actualDimensions = firstEmbedding.embedding.length
return c.json({
success: true,
message: `Embedding test successful. Generated ${actualDimensions}d embedding.`,
dimensions: actualDimensions,
})
} catch (error) {
logger.error('Failed to test embedding config:', error)
return c.json({
success: false,
error: 'Failed to test embedding configuration',
message: error instanceof Error ? error.message : 'Unknown error'
}, 500)
}
})
app.get('/:id', async (c) => {
const id = parseInt(c.req.param('id'), 10)
if (isNaN(id)) {
return c.json({ error: 'Invalid memory ID' }, 400)
}
const memory = pluginMemory.getById(id)
if (!memory) {
return c.json({ error: 'Memory not found' }, 404)
}
return c.json({ memory })
})
app.put('/:id', async (c) => {
const id = parseInt(c.req.param('id'), 10)
if (isNaN(id)) {
return c.json({ error: 'Invalid memory ID' }, 400)
}
const body = await c.req.json()
const parsed = UpdateMemoryRequestSchema.safeParse(body)
if (!parsed.success) {
return c.json({ error: 'Invalid request', details: parsed.error }, 400)
}
try {
pluginMemory.update(id, parsed.data)
const memory = pluginMemory.getById(id)
return c.json({ memory })
} catch (error) {
logger.error('Failed to update memory:', error)
return c.json({ error: 'Failed to update memory' }, 500)
}
})
app.delete('/:id', async (c) => {
const id = parseInt(c.req.param('id'), 10)
if (isNaN(id)) {
return c.json({ error: 'Invalid memory ID' }, 400)
}
try {
pluginMemory.delete(id)
return c.json({ success: true })
} catch (error) {
logger.error('Failed to delete memory:', error)
return c.json({ error: 'Failed to delete memory' }, 500)
}
})
app.post('/reindex', async (c) => {
try {
const db = pluginMemory.getDb()
if (!db) {
return c.json({
error: 'Memory database not found. Make sure the memory plugin has been initialized.',
total: 0,
embedded: 0,
failed: 0
}, 404)
}
const memories = pluginMemory.listAll()
if (memories.length === 0) {
return c.json({
success: true,
message: 'No memories to reindex',
total: 0,
embedded: 0,
failed: 0
})
}
try {
db.exec('DELETE FROM memory_embeddings')
} catch {
return c.json({
success: true,
message: 'Cleared embeddings. Server restart required to regenerate embeddings with new model.',
total: memories.length,
embedded: 0,
failed: 0,
requiresRestart: true
})
}
return c.json({
success: true,
message: `Cleared ${memories.length} embeddings. Server restart required to regenerate embeddings.`,
total: memories.length,
embedded: 0,
failed: 0,
requiresRestart: true
})
} catch (error) {
logger.error('Failed to reindex memories:', error)
return c.json({ error: 'Failed to reindex memories', details: error instanceof Error ? error.message : 'Unknown error' }, 500)
}
})
return app
}
-92
View File
@@ -303,98 +303,6 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS
}
})
app.post('/:id/git/discard', async (c) => {
try {
const id = parseInt(c.req.param('id'))
const repo = db.getRepoById(database, id)
if (!repo) {
return c.json({ error: 'Repo not found' }, 404)
}
const body = await c.req.json()
const { paths, staged } = body
if (!paths || !Array.isArray(paths)) {
return c.json({ error: 'paths is required and must be an array' }, 400)
}
await git.discardChanges(id, paths, staged ?? false, database)
const status = await git.getStatus(id, database)
return c.json(status)
} catch (error: unknown) {
logger.error('Failed to discard changes:', error)
const gitError = parseGitError(error)
return c.json(
{ error: gitError.summary, detail: gitError.detail, code: gitError.code },
gitError.statusCode as ContentfulStatusCode
)
}
})
app.get('/:id/git/commit/:hash', async (c) => {
try {
const id = parseInt(c.req.param('id'))
const hash = c.req.param('hash')
const repo = db.getRepoById(database, id)
if (!repo) {
return c.json({ error: 'Repo not found' }, 404)
}
if (!hash) {
return c.json({ error: 'hash is required' }, 400)
}
const commitDetails = await git.getCommitDetails(id, hash, database)
if (!commitDetails) {
return c.json({ error: 'Commit not found' }, 404)
}
return c.json(commitDetails)
} catch (error: unknown) {
logger.error('Failed to get commit details:', error)
const gitError = parseGitError(error)
return c.json(
{ error: gitError.summary, detail: gitError.detail, code: gitError.code },
gitError.statusCode as ContentfulStatusCode
)
}
})
app.get('/:id/git/commit/:hash/diff', async (c) => {
try {
const id = parseInt(c.req.param('id'))
const hash = c.req.param('hash')
const filePath = c.req.query('path')
const repo = db.getRepoById(database, id)
if (!repo) {
return c.json({ error: 'Repo not found' }, 404)
}
if (!hash) {
return c.json({ error: 'hash is required' }, 400)
}
if (!filePath) {
return c.json({ error: 'path query parameter is required' }, 400)
}
const diff = await git.getCommitDiff(id, hash, filePath, database)
return c.json(diff)
} catch (error: unknown) {
logger.error('Failed to get commit diff:', error)
const gitError = parseGitError(error)
return c.json(
{ error: gitError.summary, detail: gitError.detail, code: gitError.code },
gitError.statusCode as ContentfulStatusCode
)
}
})
app.get('/:id/git/log', async (c) => {
try {
const id = parseInt(c.req.param('id'))
+14 -13
View File
@@ -18,19 +18,7 @@ import { opencodeServerManager } from '../services/opencode-single-server'
import { DEFAULT_AGENTS_MD } from '../constants'
import { validateSSHPrivateKey } from '../utils/ssh-validation'
import { encryptSecret } from '../utils/crypto'
function compareVersions(v1: string, v2: string): number {
const parts1 = v1.split('.').map(s => Number(s))
const parts2 = v2.split('.').map(s => Number(s))
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
}
import { compareVersions } from '../utils/version-utils'
function getOpenCodeInstallMethod(): string {
const homePath = process.env.HOME || ''
@@ -156,6 +144,19 @@ export function createSettingsRoutes(db: Database) {
}
})
app.get('/memory-plugin-status', async (c) => {
try {
const userId = c.req.query('userId') || 'default'
const configs = settingsService.getOpenCodeConfigs(userId)
const defaultConfig = configs.configs.find((cfg: { isDefault: boolean }) => cfg.isDefault)
const isEnabled = defaultConfig?.content?.plugin?.includes('@opencode-manager/memory') ?? false
return c.json({ memoryPluginEnabled: isEnabled })
} catch (error) {
logger.error('Failed to get memory plugin status:', error)
return c.json({ error: 'Failed to get memory plugin status' }, 500)
}
})
app.patch('/', async (c) => {
try {
const userId = c.req.query('userId') || 'default'
+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 })
-13
View File
@@ -31,7 +31,6 @@ export interface FileDiffResponse {
additions: number
deletions: number
isBinary: boolean
truncated?: boolean
}
export interface GitDiffOptions {
@@ -49,15 +48,3 @@ export interface GitBranch {
behind?: number
isWorktree?: boolean
}
export interface CommitFile {
path: string
status: GitFileStatusType
oldPath?: string
additions: number
deletions: number
}
export interface CommitDetails extends GitCommit {
files: CommitFile[]
}
-4
View File
@@ -103,10 +103,6 @@ export function createGitEnv(credentials: GitCredential[]): Record<string, strin
return env
}
export function createGitHubGitEnv(gitToken: string): Record<string, string> {
return createGitEnv([{ name: 'GitHub', host: 'https://github.com/', token: gitToken, type: 'pat' }])
}
export function findGitHubCredential(credentials: GitCredential[]): GitCredential | null {
if (!credentials || credentials.length === 0) return null
+12
View File
@@ -0,0 +1,12 @@
export function compareVersions(v1: string, v2: string): number {
const parts1 = v1.replace(/^v/, '').split('.').map(Number)
const parts2 = v2.replace(/^v/, '').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
}