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
}