chore: 初始化仓库,导入项目基线代码

Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
runny committed 2026-11-16 18:12:23 +08:00
commit 7ec21f35b0
5767 files changed
+1436788

No files matched your search

@@ -0,0 +1,37 @@
// Package database implements database initialization and migrations.
package database
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
func TestDingtalkStreamMigrationPreservesOtherChannels(t *testing.T) {
for _, migration := range []string{
"sqlite/000017_dingtalk_stream_only.up.sql",
"versioned/000096_dingtalk_stream_only.up.sql",
} {
t.Run(migration, func(t *testing.T) {
db := openSQLiteDB(t, filepath.Join(t.TempDir(), "channels.db"))
_, err := db.Exec("CREATE TABLE im_channels (id TEXT, platform TEXT, mode TEXT, updated_at TIMESTAMP)")
require.NoError(t, err)
_, err = db.Exec("INSERT INTO im_channels VALUES " +
"('d', 'dingtalk', 'webhook', NULL), " +
"('s', 'slack', 'webhook', NULL), " +
"('w', 'dingtalk', 'websocket', NULL)")
require.NoError(t, err)
script, err := os.ReadFile(filepath.Join(sqliteRepoRoot(t), "migrations", migration))
require.NoError(t, err)
_, err = db.Exec(string(script))
require.NoError(t, err)
for id, expected := range map[string]string{"d": "websocket", "s": "webhook", "w": "websocket"} {
var mode string
require.NoError(t, db.QueryRow("SELECT mode FROM im_channels WHERE id = ?", id).Scan(&mode))
require.Equal(t, expected, mode)
}
})
}
}
+326
View File
@@ -0,0 +1,326 @@
package database
import (
"context"
"database/sql"
"fmt"
"os"
"strings"
"sync"
"academy/internal/logger"
"github.com/golang-migrate/migrate/v4"
_ "github.com/golang-migrate/migrate/v4/database/postgres"
sqlite3migrate "github.com/golang-migrate/migrate/v4/database/sqlite3"
_ "github.com/golang-migrate/migrate/v4/source/file"
)
var (
migrationStateMu sync.RWMutex
currentMigrationVersion uint
currentMigrationDirty bool
migrationVersionSet bool
currentMigrationError string
)
// CachedMigrationVersion returns the migration version captured at startup.
// Returns (version, dirty, ok). ok is false if the version was never captured.
//
// Note: when migrations fail mid-way, the cache may still be populated via a
// best-effort m.Version() call inside RunMigrationsWithOptions so the system
// info endpoint can surface the partial state. Check CachedMigrationError() to
// distinguish a clean version reading from a recorded-after-failure one.
func CachedMigrationVersion() (uint, bool, bool) {
migrationStateMu.RLock()
defer migrationStateMu.RUnlock()
return currentMigrationVersion, currentMigrationDirty, migrationVersionSet
}
// CachedMigrationError returns the error message captured when the most recent
// migration attempt failed at startup. Empty string means migrations either
// succeeded or were never run.
func CachedMigrationError() string {
migrationStateMu.RLock()
defer migrationStateMu.RUnlock()
return currentMigrationError
}
// setMigrationState records the latest known migration state. Unlike the old
// sync.Once-based setter, this is intentionally idempotent-overwrite so the
// failure path (which runs after Up() errored) can replace the pre-migration
// snapshot taken from the initial m.Version() call.
func setMigrationState(version uint, dirty bool, errMsg string, versionKnown bool) {
migrationStateMu.Lock()
defer migrationStateMu.Unlock()
if versionKnown {
currentMigrationVersion = version
currentMigrationDirty = dirty
migrationVersionSet = true
}
currentMigrationError = errMsg
}
// captureMigrationFailure best-effort queries m for the current version so the
// system info endpoint can show "N (failed)" instead of vanishing the row, and
// stores the human-readable error message. Always returns the original error.
func captureMigrationFailure(m *migrate.Migrate, err error) error {
versionKnown := false
var ver uint
var dirty bool
if m != nil {
v, d, vErr := m.Version()
if vErr == nil {
versionKnown = true
ver, dirty = v, d
}
}
setMigrationState(ver, dirty, err.Error(), versionKnown)
return err
}
// RunMigrations executes all pending database migrations
// This should be called during application startup
func RunMigrations(dsn string) error {
return RunMigrationsWithOptions(dsn, MigrationOptions{AutoRecoverDirty: false})
}
// MigrationOptions configures migration behavior
type MigrationOptions struct {
// AutoRecoverDirty when true, automatically attempts to recover from dirty state
// by forcing to the previous version and retrying the migration
AutoRecoverDirty bool
// SQLiteDBPath is the raw filesystem path to the SQLite database file.
// When set, the migrator opens the DB directly via sql.Open instead of
// parsing a URL-based DSN, which avoids breakage when the path contains
// spaces (e.g. macOS "Application Support").
SQLiteDBPath string
}
// RunMigrationsWithOptions executes all pending database migrations with custom options
func RunMigrationsWithOptions(dsn string, opts MigrationOptions) error {
ctx := context.Background()
logger.Infof(ctx, "Starting database migration...")
migrationsPath := "file://migrations/versioned"
if strings.HasPrefix(dsn, "sqlite3://") {
migrationsPath = "file://migrations/sqlite"
}
var m *migrate.Migrate
if opts.SQLiteDBPath != "" {
sqlDB, err := sql.Open("sqlite3", opts.SQLiteDBPath)
if err != nil {
logger.Errorf(ctx, "Failed to open sqlite db for migration: %v", err)
wrapped := fmt.Errorf("failed to open sqlite db for migration: %w", err)
setMigrationState(0, false, wrapped.Error(), false)
return wrapped
}
driver, err := sqlite3migrate.WithInstance(sqlDB, &sqlite3migrate.Config{})
if err != nil {
sqlDB.Close()
logger.Errorf(ctx, "Failed to create sqlite3 migrate driver: %v", err)
wrapped := fmt.Errorf("failed to create sqlite3 migrate driver: %w", err)
setMigrationState(0, false, wrapped.Error(), false)
return wrapped
}
m, err = migrate.NewWithDatabaseInstance(migrationsPath, "sqlite3", driver)
if err != nil {
logger.Errorf(ctx, "Failed to create migrate instance: %v", err)
wrapped := fmt.Errorf("failed to create migrate instance: %w", err)
setMigrationState(0, false, wrapped.Error(), false)
return wrapped
}
} else {
var err error
m, err = migrate.New(migrationsPath, dsn)
if err != nil {
logger.Errorf(ctx, "Failed to create migrate instance: %v", err)
wrapped := fmt.Errorf("failed to create migrate instance: %w", err)
setMigrationState(0, false, wrapped.Error(), false)
return wrapped
}
}
defer m.Close()
// Check current version and dirty state before migration
oldVersion, oldDirty, versionErr := m.Version()
if versionErr != nil && versionErr != migrate.ErrNilVersion {
logger.Errorf(ctx, "Failed to get migration version: %v", versionErr)
return captureMigrationFailure(m, fmt.Errorf("failed to get migration version: %w", versionErr))
}
if versionErr == migrate.ErrNilVersion {
logger.Infof(ctx, "Database has no migration history, will start from version 0")
} else {
logger.Infof(ctx, "Current migration version: %d, dirty: %v", oldVersion, oldDirty)
}
// If database is in dirty state, try to recover or return error
if oldDirty {
logger.Warnf(ctx, "Database is in dirty state at version %d", oldVersion)
if opts.AutoRecoverDirty {
logger.Infof(ctx, "AutoRecoverDirty is enabled, attempting recovery...")
if err := recoverFromDirtyState(ctx, m, oldVersion); err != nil {
return captureMigrationFailure(m, err)
}
// Update oldVersion after recovery
oldVersion, _, _ = m.Version()
} else {
// Calculate the version to force to (usually the previous version)
forceVersion := int(oldVersion) - 1
if oldVersion == 0 || forceVersion < 0 {
forceVersion = 0
}
return captureMigrationFailure(m, fmt.Errorf(
"database is in dirty state at version %d. This usually means a migration failed partway through. "+
"To fix this:\n"+
"1. Check if the migration partially applied changes and manually fix if needed\n"+
"2. Use the force command to set the version to the last successful migration (usually %d):\n"+
" ./scripts/migrate.sh force %d\n"+
" Or if using make: make migrate-force version=%d\n"+
"3. After fixing, restart the application to retry the migration\n"+
"Or enable AutoRecoverDirty option to automatically retry",
oldVersion,
forceVersion,
forceVersion,
forceVersion,
))
}
}
// Run all pending migrations
logger.Infof(ctx, "Running pending migrations...")
if err := m.Up(); err != nil && err != migrate.ErrNoChange {
logger.Errorf(ctx, "Migration failed: %v", err)
// Check if error is due to dirty state (in case it became dirty during migration)
currentVersion, currentDirty, versionCheckErr := m.Version()
if versionCheckErr == nil && currentDirty {
logger.Warnf(ctx, "Migration caused dirty state at version %d", currentVersion)
if opts.AutoRecoverDirty {
logger.Infof(ctx, "Attempting to recover from dirty state...")
// Try to recover and retry
if recoverErr := recoverFromDirtyState(ctx, m, currentVersion); recoverErr != nil {
return captureMigrationFailure(m, recoverErr)
}
// Retry migration after recovery
logger.Infof(ctx, "Retrying migration after recovery...")
if retryErr := m.Up(); retryErr != nil && retryErr != migrate.ErrNoChange {
logger.Errorf(ctx, "Migration failed after recovery attempt: %v", retryErr)
return captureMigrationFailure(m, fmt.Errorf("migration failed after recovery attempt: %w", retryErr))
}
} else {
// Calculate the version to force to (usually the previous version)
forceVersion := currentVersion - 1
if currentVersion == 0 {
forceVersion = 0
}
return captureMigrationFailure(m, fmt.Errorf(
"migration failed and database is now in dirty state at version %d. "+
"To fix this:\n"+
"1. Check if the migration partially applied changes and manually fix if needed\n"+
"2. Use the force command to set the version to the last successful migration (usually %d):\n"+
" ./scripts/migrate.sh force %d\n"+
" Or if using make: make migrate-force version=%d\n"+
"3. After fixing, restart the application to retry the migration\n"+
"Or enable AutoRecoverDirty option to automatically retry",
currentVersion,
forceVersion,
forceVersion,
forceVersion,
))
}
} else {
return captureMigrationFailure(m, fmt.Errorf("failed to run migrations: %w", err))
}
}
// Get current version after migration
version, dirty, err := m.Version()
if err != nil && err != migrate.ErrNilVersion {
return captureMigrationFailure(m, fmt.Errorf("failed to get migration version: %w", err))
}
setMigrationState(version, dirty, "", true)
if oldVersion != version {
logger.Infof(ctx, "Database migrated from version %d to %d", oldVersion, version)
} else {
logger.Infof(ctx, "Database is up to date (version: %d)", version)
}
if dirty {
logger.Warnf(ctx, "Database is in dirty state! Manual intervention may be required.")
}
return nil
}
// recoverFromDirtyState attempts to recover from a dirty migration state
// by forcing to the previous version and allowing the migration to be retried
func recoverFromDirtyState(ctx context.Context, m *migrate.Migrate, dirtyVersion uint) error {
// Special case: if dirty at version 0 (init migration), we cannot go back further
// The only option is to force to version 0 and retry, but this requires the migration to be idempotent
if dirtyVersion == 0 {
logger.Warnf(ctx, "Database is in dirty state at version 0 (init migration). "+
"This is the initial migration, cannot rollback further. "+
"Will attempt to clear dirty flag and retry. "+
"Note: This only works if the init migration uses IF NOT EXISTS clauses.")
// Force to version -1 (no version) to allow re-running version 0
// This effectively tells migrate that no migrations have been applied
if err := m.Force(-1); err != nil {
return fmt.Errorf(
"failed to recover from dirty state at version 0. "+
"Manual intervention required:\n"+
"1. Check what was partially created in the database\n"+
"2. Either drop all created objects and retry, or\n"+
"3. Manually complete the migration and run: ./scripts/migrate.sh force 0\n"+
"Error: %w", err)
}
logger.Infof(ctx, "Cleared migration state, will retry from version 0")
return nil
}
forceVersion := int(dirtyVersion) - 1
logger.Warnf(ctx, "Database is in dirty state at version %d, attempting auto-recovery by forcing to version %d",
dirtyVersion, forceVersion)
// Force to previous version to clear dirty state
if err := m.Force(forceVersion); err != nil {
return fmt.Errorf("failed to force migration version during recovery: %w", err)
}
logger.Infof(ctx, "Successfully forced migration to version %d, migration will be retried", forceVersion)
return nil
}
// GetMigrationVersion returns the current migration version
func GetMigrationVersion() (uint, bool, error) {
dbURL := fmt.Sprintf(
"postgres://%s:%s@%s:%s/%s?sslmode=disable",
os.Getenv("DB_USER"),
os.Getenv("DB_PASSWORD"),
os.Getenv("DB_HOST"),
os.Getenv("DB_PORT"),
os.Getenv("DB_NAME"),
)
migrationsPath := "file://migrations/versioned"
m, err := migrate.New(migrationsPath, dbURL)
if err != nil {
return 0, false, fmt.Errorf("failed to create migrate instance: %w", err)
}
defer m.Close()
version, dirty, err := m.Version()
if err != nil {
return 0, false, err
}
return version, dirty, nil
}
@@ -0,0 +1,102 @@
package database
import (
"database/sql"
"encoding/json"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
// Exercise the migration SQL itself with legacy API-created settings, and
// preserve credentials, unrelated settings, explicit markers and other sources.
func testFeishuResyncMigration(t *testing.T, db *sql.DB, dialect string) {
t.Helper()
tx, err := db.Begin()
require.NoError(t, err)
t.Cleanup(func() { _ = tx.Rollback() })
jsonType := "TEXT"
migration := "sqlite/000040_feishu_deep_adaptation_resync"
if dialect == "postgres" {
jsonType = "JSONB"
migration = "versioned/000122_feishu_deep_adaptation_resync"
}
_, err = tx.Exec("CREATE TEMP TABLE data_sources " +
"(id TEXT PRIMARY KEY, type TEXT, config " + jsonType + ", deleted_at TEXT)")
require.NoError(t, err)
cases := []struct {
id, kind, config string
deleted bool
wantMarker bool
}{
{"missing", "feishu", `{"credentials":{"app_id":"a","app_secret":"s"},"resource_ids":["space"]}`, false, true},
{"null", "lark", `{"settings":null,"credentials":{"app_secret":"s"}}`, false, true},
{"empty", "feishu_drive", `{"settings":{}}`, false, true},
{"configured", "lark_drive", `{"settings":{"parse_mode":"export","timezone":"Asia/Shanghai"}}`, false, true},
{"false-marker", "feishu", `{"settings":{"resync_required":false,"parse_mode":"blocks"}}`, false, false},
{"true-marker", "lark", `{"settings":{"resync_required":true,"timezone":"UTC"}}`, false, true},
{"other", "gitlab", `{"settings":null}`, false, false},
{"deleted", "feishu", `{"settings":null}`, true, false},
}
for _, tt := range cases {
var deleted any
if tt.deleted {
deleted = "2026-01-01"
}
_, err = tx.Exec("INSERT INTO data_sources (id,type,config,deleted_at) VALUES ($1,$2,$3,$4)",
tt.id, tt.kind, tt.config, deleted)
require.NoError(t, err)
}
script, err := os.ReadFile(filepath.Join(sqliteRepoRoot(t), "migrations", migration+".up.sql"))
require.NoError(t, err)
for range 2 {
_, err = tx.Exec(string(script))
require.NoError(t, err)
}
for _, tt := range cases {
var raw string
require.NoError(t, tx.QueryRow("SELECT config FROM data_sources WHERE id=$1", tt.id).Scan(&raw))
var got, before map[string]any
require.NoError(t, json.Unmarshal([]byte(raw), &got))
require.NoError(t, json.Unmarshal([]byte(tt.config), &before))
if !tt.wantMarker {
require.Equal(t, before, got, tt.id)
continue
}
settings, ok := got["settings"].(map[string]any)
require.True(t, ok, tt.id)
require.Equal(t, true, settings["resync_required"], tt.id)
require.Equal(t, before["credentials"], got["credentials"], tt.id)
require.Equal(t, before["resource_ids"], got["resource_ids"], tt.id)
if old, ok := before["settings"].(map[string]any); ok {
for key, value := range old {
require.Equal(t, value, settings[key], tt.id+":"+key)
}
}
}
down, err := os.ReadFile(filepath.Join(sqliteRepoRoot(t), "migrations", migration+".down.sql"))
require.NoError(t, err)
_, err = tx.Exec(string(down))
require.NoError(t, err)
var raw string
require.NoError(t, tx.QueryRow("SELECT config FROM data_sources WHERE id='configured'").Scan(&raw))
require.JSONEq(t, `{"settings":{"parse_mode":"export","timezone":"Asia/Shanghai"}}`, raw)
}
func TestSQLiteFeishuResyncMigration(t *testing.T) {
db := openSQLiteDB(t, filepath.Join(t.TempDir(), "resync.db"))
testFeishuResyncMigration(t, db, "sqlite")
}
func TestPostgresFeishuResyncMigration(t *testing.T) {
dsn := os.Getenv("ACADEMY_MIGRATION_TEST_POSTGRES_DSN")
if dsn == "" {
t.Skip("set ACADEMY_MIGRATION_TEST_POSTGRES_DSN to run PostgreSQL migration tests")
}
db, err := sql.Open("postgres", dsn)
require.NoError(t, err)
t.Cleanup(func() { _ = db.Close() })
testFeishuResyncMigration(t, db, "postgres")
}
@@ -0,0 +1,75 @@
package database
import (
"database/sql"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"github.com/golang-migrate/migrate/v4"
"github.com/stretchr/testify/require"
)
// TestPostgresMigrationsKeepAgentToolsWhenAnEmptyListMeansNone runs the
// versioned migrations against a real PostgreSQL; see
// TestPostgresMigrationsServeAgentHistory for how to start one. It stops
// before 000116, stores every kind of allowed_tools value, and checks that
// the upgrade keeps each agent's effective tools.
func TestPostgresMigrationsKeepAgentToolsWhenAnEmptyListMeansNone(t *testing.T) {
dsn := os.Getenv("ACADEMY_MIGRATION_TEST_POSTGRES_DSN")
if dsn == "" {
t.Skip("set ACADEMY_MIGRATION_TEST_POSTGRES_DSN to run PostgreSQL migration tests")
}
root := sqliteRepoRoot(t)
chdirAndRestore(t, root)
m, err := migrate.New("file://migrations/versioned", dsn)
require.NoError(t, err)
t.Cleanup(func() { _, _ = m.Close() })
require.NoError(t, ignoreNoChange(m.Migrate(versionedMigrationBefore(t, root, 116))))
db, err := sql.Open("postgres", dsn)
require.NoError(t, err)
t.Cleanup(func() { _ = db.Close() })
const tenantID = 990116
cleanup := func() { _, _ = db.Exec(`DELETE FROM custom_agents WHERE tenant_id = $1`, tenantID) }
cleanup()
t.Cleanup(cleanup)
for id, config := range agentToolListRows {
_, err := db.Exec(`INSERT INTO custom_agents (id, name, tenant_id, config) VALUES ($1, $1, $2, $3::jsonb)`,
id, tenantID, config)
require.NoError(t, err)
}
require.NoError(t, RunMigrationsWithOptions(dsn, MigrationOptions{}))
requireAgentToolListsUpgraded(t, db,
`SELECT config::text FROM custom_agents WHERE tenant_id = 990116 AND id = $1`)
}
// versionedMigrationBefore returns the highest versioned migration below
// version, so the test does not depend on how many migrations precede it.
func versionedMigrationBefore(t *testing.T, root string, version int) uint {
t.Helper()
entries, err := os.ReadDir(filepath.Join(root, "migrations", "versioned"))
require.NoError(t, err)
before := 0
for _, e := range entries {
prefix, _, ok := strings.Cut(e.Name(), "_")
if !ok {
continue
}
if n, err := strconv.Atoi(prefix); err == nil && n < version && n > before {
before = n
}
}
require.NotZero(t, before)
return uint(before)
}
func ignoreNoChange(err error) error {
if err == migrate.ErrNoChange {
return nil
}
return err
}
@@ -0,0 +1,76 @@
package database
import (
"context"
"os"
"strings"
"testing"
"time"
"academy/internal/application/repository"
"academy/internal/types"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
// TestPostgresMCPOAuthTimesKeepTheInstant runs the versioned migrations against
// a real PostgreSQL; see TestPostgresMigrationsServeAgentHistory for how to
// start one. The application reads through a TimeZone=UTC session while token
// expiries come from the process clock, which runs in the deployment's local
// zone. A naive TIMESTAMP column drops that offset on write and returns a
// value shifted by it.
func TestPostgresMCPOAuthTimesKeepTheInstant(t *testing.T) {
dsn := os.Getenv("ACADEMY_MIGRATION_TEST_POSTGRES_DSN")
if dsn == "" {
t.Skip("set ACADEMY_MIGRATION_TEST_POSTGRES_DSN to run PostgreSQL migration tests")
}
chdirAndRestore(t, sqliteRepoRoot(t))
require.NoError(t, RunMigrationsWithOptions(dsn, MigrationOptions{}))
sep := "?"
if strings.Contains(dsn, "?") {
sep = "&"
}
db, err := gorm.Open(postgres.Open(dsn+sep+"TimeZone=UTC"), &gorm.Config{})
require.NoError(t, err)
sqlDB, err := db.DB()
require.NoError(t, err)
t.Cleanup(func() { _ = sqlDB.Close() })
serviceID := uuid.NewString()
require.NoError(t, db.Exec(
"INSERT INTO mcp_services (id, tenant_id, name, transport_type) VALUES (?, 7, 'tz', 'sse')",
serviceID).Error)
t.Cleanup(func() { db.Exec("DELETE FROM mcp_services WHERE id = ?", serviceID) })
ctx := context.Background()
repo := repository.NewMCPOAuthRepository(db)
principal := types.Principal{Type: types.PrincipalAPIExternalUser, ID: "7:tz"}
local := time.FixedZone("UTC+9", 9*60*60)
expiresAt := time.Date(2026, 10, 12, 21, 3, 32, 0, local)
require.NoError(t, repo.SaveTokenForPrincipal(ctx, &types.MCPOAuthToken{
TenantID: 7,
PrincipalType: principal.Type,
PrincipalID: principal.ID,
ServiceID: serviceID,
AccessToken: "token",
TokenType: "Bearer",
ExpiresAt: expiresAt,
}))
loaded, err := repo.GetTokenForPrincipal(ctx, 7, principal, serviceID)
require.NoError(t, err)
require.True(t, loaded.ExpiresAt.Equal(expiresAt), "expiry %s, want %s", loaded.ExpiresAt, expiresAt)
// The column itself must keep the instant, so correctness does not rest on
// every writer normalizing to UTC first.
require.NoError(t, db.Exec(
"UPDATE mcp_oauth_tokens SET expires_at = ?, updated_at = ? WHERE service_id = ?",
expiresAt, expiresAt, serviceID).Error)
loaded, err = repo.GetTokenForPrincipal(ctx, 7, principal, serviceID)
require.NoError(t, err)
require.True(t, loaded.ExpiresAt.Equal(expiresAt), "expiry %s, want %s", loaded.ExpiresAt, expiresAt)
require.True(t, loaded.UpdatedAt.Equal(expiresAt), "updated_at %s, want %s", loaded.UpdatedAt, expiresAt)
}
@@ -0,0 +1,114 @@
package database
import (
"context"
"database/sql"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"github.com/golang-migrate/migrate/v4"
"github.com/stretchr/testify/require"
)
// TestPostgresMigrationsServeAgentHistory runs the versioned migrations against
// a real PostgreSQL. Skipped unless ACADEMY_MIGRATION_TEST_POSTGRES_DSN points
// at a disposable database, for example:
//
// docker run -d --rm -e POSTGRES_PASSWORD=pg -e POSTGRES_DB=academy -p 55432:5432 \
// paradedb/paradedb:v0.25.11-pg17
// ACADEMY_MIGRATION_TEST_POSTGRES_DSN=postgres://postgres:pg@localhost:55432/academy?sslmode=disable
//
// It checks what SQLite cannot: that 000106 builds its index CONCURRENTLY
// through golang-migrate (which fails inside a transaction block), in both
// directions, and that the agent history queries walk it without sorting.
func TestPostgresMigrationsServeAgentHistory(t *testing.T) {
dsn := os.Getenv("ACADEMY_MIGRATION_TEST_POSTGRES_DSN")
if dsn == "" {
t.Skip("set ACADEMY_MIGRATION_TEST_POSTGRES_DSN to run PostgreSQL migration tests")
}
root := sqliteRepoRoot(t)
chdirAndRestore(t, root)
require.NoError(t, RunMigrationsWithOptions(dsn, MigrationOptions{}))
db, err := sql.Open("postgres", dsn)
require.NoError(t, err)
t.Cleanup(func() { _ = db.Close() })
var version int
var dirty bool
require.NoError(t, db.QueryRow("SELECT version, dirty FROM schema_migrations").Scan(&version, &dirty))
require.Equal(t, latestVersionedMigration(t, root), version)
require.False(t, dirty)
requirePostgresIndexValid(t, db)
// Down and up again: DROP/CREATE INDEX CONCURRENTLY through golang-migrate.
m, err := migrate.New("file://migrations/versioned", dsn)
require.NoError(t, err)
t.Cleanup(func() { _, _ = m.Close() })
require.NoError(t, m.Steps(-1))
var indexes int
require.NoError(t, db.QueryRow(
"SELECT count(*) FROM pg_class WHERE relname = 'idx_messages_session_created_id'").Scan(&indexes))
require.Zero(t, indexes, "the down migration drops the index")
require.NoError(t, m.Steps(1))
requirePostgresIndexValid(t, db)
ctx := context.Background()
conn, err := db.Conn(ctx)
require.NoError(t, err)
t.Cleanup(func() { _ = conn.Close() })
// An empty table is always cheapest to scan; rule the scan out to see
// which index the planner can use and whether it still has to sort.
_, err = conn.ExecContext(ctx, "SET enable_seqscan = off")
require.NoError(t, err)
for name, query := range map[string]string{
"backwards page": `SELECT * FROM messages WHERE session_id = 's'
AND (created_at < now() OR (created_at = now() AND id < 'x'))
AND deleted_at IS NULL ORDER BY created_at DESC, id DESC LIMIT 200`,
"newest checkpoint": `SELECT id FROM messages WHERE session_id = 's' AND role = 'assistant'
AND context_checkpoint IS NOT NULL AND deleted_at IS NULL
ORDER BY created_at DESC, id DESC LIMIT 1`,
} {
rows, err := conn.QueryContext(ctx, "EXPLAIN "+query)
require.NoError(t, err, name)
var plan strings.Builder
for rows.Next() {
var line string
require.NoError(t, rows.Scan(&line), name)
plan.WriteString(line + "\n")
}
require.NoError(t, rows.Close(), name)
require.Contains(t, plan.String(), "idx_messages_session_created_id", "%s plan:\n%s", name, plan.String())
require.NotContains(t, plan.String(), "Sort", "%s must not sort:\n%s", name, plan.String())
}
}
func requirePostgresIndexValid(t *testing.T, db *sql.DB) {
t.Helper()
var valid bool
require.NoError(t, db.QueryRow(`SELECT i.indisvalid FROM pg_index i
JOIN pg_class c ON c.oid = i.indexrelid
WHERE c.relname = 'idx_messages_session_created_id'`).Scan(&valid))
require.True(t, valid, "a CONCURRENTLY build that failed leaves an INVALID index")
}
func latestVersionedMigration(t *testing.T, root string) int {
t.Helper()
entries, err := os.ReadDir(filepath.Join(root, "migrations", "versioned"))
require.NoError(t, err)
latest := 0
for _, e := range entries {
prefix, _, ok := strings.Cut(e.Name(), "_")
if !ok {
continue
}
if n, err := strconv.Atoi(prefix); err == nil && n > latest {
latest = n
}
}
return latest
}
@@ -0,0 +1,22 @@
package database
import (
"path/filepath"
"testing"
"github.com/golang-migrate/migrate/v4/source"
"github.com/stretchr/testify/require"
)
// Check both migration registries without requiring a live PostgreSQL server.
// Independently merged migrations must not reuse a version in either dialect.
func TestMigrationSourcesHaveUniqueVersions(t *testing.T) {
root := sqliteRepoRoot(t)
for _, dialect := range []string{"sqlite", "versioned"} {
t.Run(dialect, func(t *testing.T) {
migrations, err := source.Open("file://" + filepath.Join(root, "migrations", dialect))
require.NoError(t, err)
require.NoError(t, migrations.Close())
})
}
}
@@ -0,0 +1,100 @@
package database
import (
"database/sql"
"encoding/json"
"path/filepath"
"testing"
"academy/internal/agent/tools"
"github.com/stretchr/testify/require"
)
// agentToolListRows is the custom_agents data both upgrade tests start from:
// every way an allowed_tools value can be stored, in both agent modes.
var agentToolListRows = map[string]string{
"reasoning-empty": `{"agent_mode":"smart-reasoning","allowed_tools":[]}`,
"reasoning-null": `{"agent_mode":"smart-reasoning","allowed_tools":null}`,
"reasoning-missing": `{"agent_mode":"smart-reasoning"}`,
"reasoning-picked": `{"agent_mode":"smart-reasoning","allowed_tools":["thinking"]}`,
"quick-empty": `{"agent_mode":"quick-answer","allowed_tools":[]}`,
// Malformed values must neither break the migration nor be rewritten.
"reasoning-string": `{"agent_mode":"smart-reasoning","allowed_tools":"thinking"}`,
"reasoning-object": `{"agent_mode":"smart-reasoning","allowed_tools":{}}`,
}
// requireAgentToolListsUpgraded checks that an upgrade keeps every agent's
// effective tools: the empty smart-reasoning list, which used to select the
// default tools, now names them, and nothing else changes.
func requireAgentToolListsUpgraded(t *testing.T, db *sql.DB, query string) {
t.Helper()
for _, id := range []string{"reasoning-string", "reasoning-object"} {
var raw string
require.NoError(t, db.QueryRow(query, id).Scan(&raw), id)
var got, want struct {
AllowedTools json.RawMessage `json:"allowed_tools"`
}
require.NoError(t, json.Unmarshal([]byte(raw), &got), id)
require.NoError(t, json.Unmarshal([]byte(agentToolListRows[id]), &want), id)
require.JSONEq(t, string(want.AllowedTools), string(got.AllowedTools), "%s must be left as it is", id)
}
// Migration 35 freezes the defaults that existed when it was written.
// Later defaults must not silently grant tools to explicit lists.
legacyDefaults := []string{"search_knowledge", "read_document", "list_documents", "search_conversations"}
want := map[string][]string{
"reasoning-empty": legacyDefaults,
"reasoning-null": nil,
"reasoning-missing": nil,
"reasoning-picked": {"thinking"},
"quick-empty": {},
}
for id, expected := range want {
var raw string
require.NoError(t, db.QueryRow(query, id).Scan(&raw), id)
var config struct {
AllowedTools []string `json:"allowed_tools"`
}
require.NoError(t, json.Unmarshal([]byte(raw), &config), id)
require.Equal(t, expected, config.AllowedTools, id)
// The default tools still apply to the agents that never set a list.
before := tools.EffectiveAllowedTools(decodeAllowedTools(t, agentToolListRows[id]))
if id == "reasoning-empty" {
before = legacyDefaults
}
require.ElementsMatch(t, before, tools.EffectiveAllowedTools(config.AllowedTools),
"%s must keep its effective tools", id)
}
}
// decodeAllowedTools reads a pre-upgrade row under the old meaning, in which
// an empty list also selected the default tools.
func decodeAllowedTools(t *testing.T, raw string) []string {
t.Helper()
var config struct {
AgentMode string `json:"agent_mode"`
AllowedTools []string `json:"allowed_tools"`
}
require.NoError(t, json.Unmarshal([]byte(raw), &config))
if config.AgentMode == "smart-reasoning" && config.AllowedTools != nil && len(config.AllowedTools) == 0 {
return nil
}
return config.AllowedTools
}
func TestSQLiteMigrationsKeepAgentToolsWhenAnEmptyListMeansNone(t *testing.T) {
repoRoot := sqliteRepoRoot(t)
chdirAndRestore(t, copySQLiteMigrationsThrough(t, repoRoot, 34))
dbPath := filepath.Join(t.TempDir(), "upgrade-agent-tools.db")
opts := MigrationOptions{SQLiteDBPath: dbPath}
require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", opts))
db := openSQLiteDB(t, dbPath)
for id, config := range agentToolListRows {
_, err := db.Exec(`INSERT INTO custom_agents (id, name, tenant_id, config) VALUES (?, ?, 1, ?)`,
id, id, config)
require.NoError(t, err)
}
chdirAndRestore(t, repoRoot)
require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", opts))
requireAgentToolListsUpgraded(t, db, `SELECT config FROM custom_agents WHERE id = ?`)
}
@@ -0,0 +1,38 @@
package database
import (
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
func TestSQLiteAutomationAssistantRemovesExecutorSelection(t *testing.T) {
repoRoot := sqliteRepoRoot(t)
chdirAndRestore(t, copySQLiteMigrationsThrough(t, repoRoot, 49))
dbPath := filepath.Join(t.TempDir(), "automations.db")
opts := MigrationOptions{SQLiteDBPath: dbPath}
require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", opts))
db := openSQLiteDB(t, dbPath)
_, err := db.Exec(`INSERT INTO automations
(id, tenant_id, owner_user_id, name, agent_id, model_id, instruction, trigger_config, created_at, updated_at)
VALUES ('task', 1, 'owner', 'Digest', 'custom-agent', 'chosen-model', 'Summarize the news', '{}',
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`)
require.NoError(t, err)
chdirAndRestore(t, repoRoot)
require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", opts))
var count int
require.NoError(t, db.QueryRow(`SELECT COUNT(*) FROM pragma_table_info('automations')
WHERE name = 'agent_id'`).Scan(&count))
require.Zero(t, count)
var model, instruction string
require.NoError(t, db.QueryRow(`SELECT model_id, instruction FROM automations
WHERE id = 'task'`).Scan(&model, &instruction))
require.Equal(t, "chosen-model", model)
require.Equal(t, "Summarize the news", instruction)
_, err = db.Exec(`INSERT INTO automations
(id, tenant_id, owner_user_id, name, instruction, trigger_config, created_at, updated_at)
VALUES ('new-task', 1, 'owner', 'Reminder', 'Take a break', '{}', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`)
require.NoError(t, err, "new automations must not need an executor field")
}
@@ -0,0 +1,36 @@
package database
import (
"fmt"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
func TestSQLiteAutomationDurationUpgradePreservesExistingRuns(t *testing.T) {
repoRoot := sqliteRepoRoot(t)
for _, version := range []int{45, 47} {
t.Run(fmt.Sprintf("from-v%d", version), func(t *testing.T) {
chdirAndRestore(t, copySQLiteMigrationsThrough(t, repoRoot, version))
dbPath := filepath.Join(t.TempDir(), "automations.db")
require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", MigrationOptions{SQLiteDBPath: dbPath}))
db := openSQLiteDB(t, dbPath)
_, err := db.Exec(`INSERT INTO automation_runs
(id, automation_id, tenant_id, scheduled_at, trigger_kind, status, answer, created_at, updated_at)
VALUES ('existing-run', 'automation', 1, CURRENT_TIMESTAMP, 'schedule',
'awaiting_approval', 'saved answer', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`)
require.NoError(t, err)
chdirAndRestore(t, repoRoot)
require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", MigrationOptions{SQLiteDBPath: dbPath}))
var duration int64
var answer, status string
require.NoError(t, db.QueryRow(`SELECT execution_duration_ms, answer, status
FROM automation_runs WHERE id = 'existing-run'`).Scan(&duration, &answer, &status))
require.Zero(t, duration)
require.Equal(t, "saved answer", answer)
require.Equal(t, "awaiting_approval", status)
})
}
}
@@ -0,0 +1,32 @@
package database
import (
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
func TestSQLiteAutomationModelUpgradePreservesDefault(t *testing.T) {
repoRoot := sqliteRepoRoot(t)
chdirAndRestore(t, copySQLiteMigrationsThrough(t, repoRoot, 48))
dbPath := filepath.Join(t.TempDir(), "automations.db")
opts := MigrationOptions{SQLiteDBPath: dbPath}
require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", opts))
db := openSQLiteDB(t, dbPath)
_, err := db.Exec(`INSERT INTO automations
(id, tenant_id, owner_user_id, name, agent_id, instruction, trigger_config, limits, created_at, updated_at)
VALUES ('task', 1, 'owner', 'Reminder', 'agent', 'Take a break', '{}', '{}',
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`)
require.NoError(t, err)
chdirAndRestore(t, repoRoot)
require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", opts))
var model, name string
require.NoError(t, db.QueryRow("SELECT model_id, name FROM automations WHERE id = 'task'").Scan(&model, &name))
require.Empty(t, model, "automations must use the assistant default")
require.Equal(t, "Reminder", name)
_, err = db.Exec("UPDATE automations SET model_id = 'chosen-model' WHERE id = 'task'")
require.NoError(t, err)
require.NoError(t, db.QueryRow("SELECT model_id FROM automations WHERE id = 'task'").Scan(&model))
require.Equal(t, "chosen-model", model)
}
@@ -0,0 +1,57 @@
package database
import (
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
func TestSQLiteMigrationsUpgradeV33PreservesMCPServices(t *testing.T) {
repoRoot := sqliteRepoRoot(t)
chdirAndRestore(t, copySQLiteMigrationsThrough(t, repoRoot, 33))
dbPath := filepath.Join(t.TempDir(), "upgrade-mcp.db")
opts := MigrationOptions{SQLiteDBPath: dbPath}
require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", opts))
db := openSQLiteDB(t, dbPath)
_, err := db.Exec(`INSERT INTO mcp_services (id, tenant_id, name, description, transport_type)
VALUES ('existing', 1, 'Existing service', 'Legacy documentation', 'sse')`)
require.NoError(t, err)
chdirAndRestore(t, repoRoot)
require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", opts))
// Starting again must not replay the column addition or change existing data.
require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", opts))
var name, description, instructions string
require.NoError(t, db.QueryRow(`SELECT name, description, usage_instructions
FROM mcp_services WHERE id = 'existing'`).Scan(&name, &description, &instructions))
require.Equal(t, "Existing service", name)
require.Equal(t, "Legacy documentation", description)
require.Empty(t, instructions)
_, err = db.Exec(`INSERT INTO mcp_services (id, tenant_id, name, transport_type, usage_instructions)
VALUES ('new', 1, 'New service', 'sse', 'Use for contracts')`)
require.NoError(t, err)
_, err = db.Exec(`UPDATE mcp_services SET usage_instructions = 'Updated instructions' WHERE id = 'new'`)
require.NoError(t, err)
require.NoError(t, db.QueryRow(`SELECT usage_instructions FROM mcp_services WHERE id = 'new'`).Scan(&instructions))
require.Equal(t, "Updated instructions", instructions)
// Directory refresh uses a tenant/service/principal upsert and JSON tool counts.
const upsert = `INSERT INTO mcp_metadata
(tenant_id, service_id, principal, config_fingerprint, tools, synced_at)
VALUES (1, 'new', ?, 'fingerprint', ?, CURRENT_TIMESTAMP)
ON CONFLICT(tenant_id, service_id, principal) DO UPDATE SET tools = excluded.tools`
_, err = db.Exec(upsert, "", `[]`)
require.NoError(t, err)
_, err = db.Exec(upsert, "", `[{"name":"contracts"}]`)
require.NoError(t, err)
_, err = db.Exec(upsert, "user-a", `[]`)
require.NoError(t, err)
var count int
require.NoError(t, db.QueryRow(`SELECT json_array_length(tools) FROM mcp_metadata
WHERE tenant_id = 1 AND service_id = 'new' AND principal = ''`).Scan(&count))
require.Equal(t, 1, count)
require.NoError(t, db.QueryRow(`SELECT COUNT(*) FROM mcp_metadata WHERE service_id = 'new'`).Scan(&count))
require.Equal(t, 2, count)
}
@@ -0,0 +1,135 @@
package database
import (
"database/sql"
"encoding/json"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/require"
)
// TestSQLiteMessageArtifactsBackfillAndRollback upgrades a v22 database that
// still keeps artifacts on messages.artifacts, checks 000023 copies them into
// message_artifacts, then replays the down migration and checks the JSON
// column is rebuilt from the table in a shape Go can decode.
func TestSQLiteMessageArtifactsBackfillAndRollback(t *testing.T) {
repoRoot := sqliteRepoRoot(t)
legacyRoot := copySQLiteMigrationsThrough(t, repoRoot, 22)
chdirAndRestore(t, legacyRoot)
dbPath := filepath.Join(t.TempDir(), "artifacts.db")
require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", MigrationOptions{SQLiteDBPath: dbPath}))
db := openSQLiteDB(t, dbPath)
legacy := `[
{"url":"local://a/report.pptx","file_name":"report.pptx","file_type":".pptx","file_size":2048,
"content_hash":"abc","source_path":"/workspace/report.pptx",
"mod_time":"2026-09-01T10:00:00.123456789+08:00","created_at":"2026-09-01T10:00:05+08:00"},
{"url":"local://a/chart.png","file_name":"chart.png","file_type":".png","file_size":10,
"source_path":"/workspace/chart.png","mod_time":"2026-09-01T10:00:00Z","created_at":"2026-09-01T02:00:06Z"}
]`
_, err := db.Exec(
`INSERT INTO messages (id, request_id, session_id, role, content, artifacts, created_at)
VALUES ('msg-1', 'req-1', 'sess-1', 'assistant', 'done', ?, '2026-09-01 02:00:00')`,
legacy,
)
require.NoError(t, err)
_, err = db.Exec(
`INSERT INTO messages (id, request_id, session_id, role, content, artifacts)
VALUES ('msg-2', 'req-2', 'sess-1', 'user', 'hi', '[]')`,
)
require.NoError(t, err)
// Malformed values must fall back instead of failing the migration.
_, err = db.Exec(
`INSERT INTO messages (id, request_id, session_id, role, content, artifacts, created_at)
VALUES ('msg-3', 'req-3', 'sess-1', 'assistant', 'dirty', ?, '2026-09-02 00:00:00')`,
`[{"file_name":"dirty.bin","file_size":"12.5x","created_at":"garbage"}, 7, "x"]`,
)
require.NoError(t, err)
require.NoError(t, db.Close())
chdirAndRestore(t, repoRoot)
require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", MigrationOptions{SQLiteDBPath: dbPath}))
db = openSQLiteDB(t, dbPath)
type row struct {
position int
fileName string
fileSize int64
sourcePath string
modTime string
createdAt time.Time
}
rows, err := db.Query(
`SELECT position, file_name, file_size, source_path, mod_time, created_at
FROM message_artifacts WHERE message_id = 'msg-1' ORDER BY position`,
)
require.NoError(t, err)
var got []row
for rows.Next() {
var r row
require.NoError(t, rows.Scan(&r.position, &r.fileName, &r.fileSize, &r.sourcePath, &r.modTime, &r.createdAt))
got = append(got, r)
}
require.NoError(t, rows.Err())
require.NoError(t, rows.Close())
require.Len(t, got, 2)
require.Equal(t, 0, got[0].position)
require.Equal(t, "report.pptx", got[0].fileName)
require.Equal(t, int64(2048), got[0].fileSize)
require.Equal(t, "/workspace/report.pptx", got[0].sourcePath)
require.Equal(t, "2026-09-01T10:00:00.123456789+08:00", got[0].modTime, "mod_time keeps the exact RFC 3339 text")
wantCreated, _ := time.Parse(time.RFC3339, "2026-09-01T02:00:05Z")
require.True(t, got[0].createdAt.Equal(wantCreated), "created_at normalised to UTC: %v", got[0].createdAt)
require.Equal(t, 1, got[1].position)
require.Equal(t, "chart.png", got[1].fileName)
var dirtySize int64
var dirtyCreated time.Time
require.NoError(t, db.QueryRow(
`SELECT file_size, created_at FROM message_artifacts WHERE message_id = 'msg-3'`,
).Scan(&dirtySize, &dirtyCreated))
require.EqualValues(t, 12, dirtySize, "SQLite CAST keeps the numeric prefix")
require.True(t, dirtyCreated.Equal(time.Date(2026, 9, 2, 0, 0, 0, 0, time.UTC)),
"an unparseable created_at falls back to the message time: %v", dirtyCreated)
var userRows int
require.NoError(t, db.QueryRow(`SELECT COUNT(*) FROM message_artifacts WHERE message_id = 'msg-2'`).Scan(&userRows))
require.Zero(t, userRows)
// The legacy column is cleared once copied, so history loads (SELECT *)
// no longer read a stale duplicate; rows without artifacts are untouched.
var legacy1, legacy2 sql.NullString
require.NoError(t, db.QueryRow(`SELECT artifacts FROM messages WHERE id = 'msg-1'`).Scan(&legacy1))
require.NoError(t, db.QueryRow(`SELECT artifacts FROM messages WHERE id = 'msg-2'`).Scan(&legacy2))
require.False(t, legacy1.Valid, "copied artifacts are cleared from messages.artifacts")
require.Equal(t, "[]", legacy2.String)
// Rollback rebuilds the legacy column from the table.
down, err := os.ReadFile(filepath.Join(repoRoot, "migrations", "sqlite", "000023_message_artifacts_table.down.sql"))
require.NoError(t, err)
_, err = db.Exec(string(down))
require.NoError(t, err)
require.False(t, sqliteTableExists(t, db, "message_artifacts"))
var restored string
require.NoError(t, db.QueryRow(`SELECT artifacts FROM messages WHERE id = 'msg-1'`).Scan(&restored))
var decoded []struct {
FileName string `json:"file_name"`
FileSize int64 `json:"file_size"`
ModTime time.Time `json:"mod_time"`
CreatedAt time.Time `json:"created_at"`
}
wantMod, _ := time.Parse(time.RFC3339Nano, "2026-09-01T10:00:00.123456789+08:00")
require.NoError(t, json.Unmarshal([]byte(restored), &decoded))
require.Len(t, decoded, 2)
require.Equal(t, "report.pptx", decoded[0].FileName)
require.Equal(t, int64(2048), decoded[0].FileSize)
require.True(t, decoded[0].CreatedAt.Equal(wantCreated))
require.True(t, decoded[0].ModTime.Equal(wantMod), "rollback keeps nanosecond mtime")
require.Equal(t, "chart.png", decoded[1].FileName)
}
@@ -0,0 +1,44 @@
package database
import (
"database/sql"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
func TestSQLiteMigrationsIncludeAutoTagConfig(t *testing.T) {
repoRoot, err := filepath.Abs(filepath.Join("..", ".."))
require.NoError(t, err)
previousDir, err := os.Getwd()
require.NoError(t, err)
require.NoError(t, os.Chdir(repoRoot))
t.Cleanup(func() { _ = os.Chdir(previousDir) })
dbPath := filepath.Join(t.TempDir(), "migration.db")
require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", MigrationOptions{SQLiteDBPath: dbPath}))
db, err := sql.Open("sqlite3", dbPath)
require.NoError(t, err)
t.Cleanup(func() { _ = db.Close() })
rows, err := db.Query("PRAGMA table_info(knowledge_bases)")
require.NoError(t, err)
defer func() { _ = rows.Close() }()
found := false
for rows.Next() {
var cid int
var name, columnType string
var notNull, primaryKey int
var defaultValue any
require.NoError(t, rows.Scan(&cid, &name, &columnType, &notNull, &defaultValue, &primaryKey))
if name == "auto_tag_config" {
found = true
}
}
require.NoError(t, rows.Err())
require.True(t, found, "SQLite migrations must create knowledge_bases.auto_tag_config")
}
@@ -0,0 +1,506 @@
package database
import (
"database/sql"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"github.com/golang-migrate/migrate/v4"
sqlite3migrate "github.com/golang-migrate/migrate/v4/database/sqlite3"
"github.com/stretchr/testify/require"
)
// versionedSQLiteTables is the set of tables that SQLite migrations must
// create to stay in sync with the versioned (PostgreSQL) migrations:
// 000041 task queue, 000053 system settings, 000055 processing spans,
// 000063 knowledge multi-tags, 000093 browser authorization, 000103 message
// artifacts.
var versionedSQLiteTables = []string{
"memory_extraction_sessions",
"task_pending_ops",
"task_dead_letters",
"system_settings",
"model_catalog_configs",
"chunk_images",
"knowledge_processing_spans",
"knowledge_tag_relations",
"browser_devices",
"browser_pairings",
"browser_task_interruptions",
"fork_snapshot_leases",
"mcp_endpoints",
"mcp_metadata",
"message_artifacts",
"tenant_skills",
"tenant_skill_snapshots",
"tenant_skill_catalog",
"tenant_user_env_vars",
"agent_prompts",
"agent_run_suspensions",
"agent_collaborations",
"agent_grants",
"automations",
"automation_runs",
"notifications",
"session_sandbox_assignments",
"sandbox_user_machines",
}
// versionedSQLiteColumns maps each existing table to the columns that the
// versioned migrations add and the SQLite baseline was missing.
var versionedSQLiteColumns = map[string][]string{
"automations": {"model_id"}, // 000049
"automation_runs": {"execution_duration_ms"}, // 000048
"model_catalog_configs": {"version", "overlay", "history", "updated_by", "updated_at"}, // 000031
"memory_subjects": {"extraction_state"}, // 000094
"memory_items": {"replaces_id"}, // 000094
"tenants": {"api_principal_config"}, // 000064
"users": {"is_system_admin"}, // 000053
"knowledges": {"pending_subtasks_count", "profile"}, // 000056, 000101
"knowledge_bases": {"profile_config", "generated_profile"}, // 000101
// 000034/085/097/105/119
"messages": {"attachments", "usage", "sandbox_checkpoint", "context_checkpoint", "run_state"},
"sessions": {
"kind",
"parent_session_id", "forked_from_message_id", "fork_bootstrap", // 000097
"sandbox_config_tenant_id", // 000027
"host_workspace_dir", // 000029
"owner_auth_source", // 000046
},
"session_sandbox_assignments": {"released_at", "cleanup_due_at"}, // 000047
"tenant_invitations": {"token", "accepted_count"}, // 000054
"embed_channels": {"allow_memory"}, // 000060
"im_channels": {"locale"}, // 000030
"chunks": {"source_locators"}, // 000033
"mcp_oauth_tokens": {"principal_type", "principal_id"}, // 000064
"mcp_tool_approvals": {"enabled", "risk", "observed_risk"}, // 000091, 000126
"mcp_services": {"usage_instructions"}, // 000092
"message_artifacts": {"deleted_at"}, // 000107
"tenant_skills": {
"envs", "served", "catalog_id", "install_session_id", "install_message_id",
}, // 000028
"tenant_skill_snapshots": {"planned_name"}, // 000028
"tenant_user_env_vars": {
"principal_type", "principal_id", "sandbox_config_id", "skill_id", "name", "value",
}, // 000028
}
const expectedSQLiteMigrationVersion = 50
func TestSQLiteMigrationsCreateVersionedSchema(t *testing.T) {
repoRoot := sqliteRepoRoot(t)
chdirAndRestore(t, repoRoot)
dbPath := filepath.Join(t.TempDir(), "fresh.db")
require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", MigrationOptions{SQLiteDBPath: dbPath}))
db := openSQLiteDB(t, dbPath)
version, dirty := sqliteMigrationState(t, db)
require.Equal(t, expectedSQLiteMigrationVersion, version)
require.False(t, dirty)
for _, table := range versionedSQLiteTables {
require.Truef(t, sqliteTableExists(t, db, table), "SQLite migrations must create table %s", table)
}
for table, columns := range versionedSQLiteColumns {
for _, column := range columns {
require.Truef(
t,
sqliteColumnExists(t, db, table, column),
"SQLite migrations must add column %s.%s",
table,
column,
)
}
}
require.True(t, sqliteIndexExists(t, db, "idx_messages_session_created_id"),
"SQLite migrations must add the session/created_at index") // 000106
require.True(t, sqliteIndexExists(t, db, "idx_messages_live_attachments"),
"SQLite migrations must index live user message references")
assertSQLiteAgentHistoryQueriesUseTheIndex(t, db)
var catalogVersion int
var catalogOverlay string
catalogRow := db.QueryRow("SELECT version, overlay FROM model_catalog_configs WHERE id = 1")
require.NoError(t, catalogRow.Scan(&catalogVersion, &catalogOverlay))
require.Zero(t, catalogVersion)
require.JSONEq(t, `{"providers":{}}`, catalogOverlay)
assertSQLiteShareLinkInvitationsWork(t, db)
assertSQLiteMCPOAuthPrincipalUpsertWorks(t, db)
require.False(t, sqliteColumnExists(t, db, "knowledges", "tag_id"),
"SQLite migrations must drop legacy knowledges.tag_id after multi-tag migration")
}
func TestSQLiteMigrationsUpgradeV4PreservesData(t *testing.T) {
repoRoot := sqliteRepoRoot(t)
// Build a legacy v4 migration root (000000_init .. 000004_memory) so we
// can prove the new migrations upgrade an existing Lite database without
// replaying the baseline.
legacyRoot := copySQLiteMigrationsV4(t, repoRoot)
chdirAndRestore(t, legacyRoot)
dbPath := filepath.Join(t.TempDir(), "upgrade.db")
require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", MigrationOptions{SQLiteDBPath: dbPath}))
db := openSQLiteDB(t, dbPath)
versionBefore, dirtyBefore := sqliteMigrationState(t, db)
require.Equal(t, 4, versionBefore)
require.False(t, dirtyBefore)
_, err := db.Exec("INSERT INTO tenants (name, business) VALUES (?, ?)", "upgrade-sentinel", "migration-test")
require.NoError(t, err)
_, err = db.Exec(
"INSERT INTO knowledges (id, tenant_id, knowledge_base_id, type, title, source, tag_id) "+
"VALUES (?, 1, ?, 'document', 'tagged-doc', 'manual', ?)",
"legacy-knowledge-1", "legacy-kb-1", "legacy-tag-1",
)
require.NoError(t, err)
// Run the full migration set from the repo root.
chdirAndRestore(t, repoRoot)
require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", MigrationOptions{SQLiteDBPath: dbPath}))
db = openSQLiteDB(t, dbPath)
versionAfter, dirtyAfter := sqliteMigrationState(t, db)
require.Equal(t, expectedSQLiteMigrationVersion, versionAfter)
require.False(t, dirtyAfter)
for _, table := range versionedSQLiteTables {
require.Truef(t, sqliteTableExists(t, db, table), "upgraded SQLite DB must have table %s", table)
}
for table, columns := range versionedSQLiteColumns {
for _, column := range columns {
require.Truef(
t,
sqliteColumnExists(t, db, table, column),
"upgraded SQLite DB must have column %s.%s",
table,
column,
)
}
}
var sentinelName string
require.NoError(t, db.QueryRow("SELECT name FROM tenants WHERE business = ?", "migration-test").Scan(&sentinelName))
require.Equal(t, "upgrade-sentinel", sentinelName)
var relationCount int
require.NoError(t, db.QueryRow(
"SELECT COUNT(*) FROM knowledge_tag_relations WHERE knowledge_id = ? AND tag_id = ?",
"legacy-knowledge-1", "legacy-tag-1",
).Scan(&relationCount))
require.Equal(t, 1, relationCount)
require.False(t, sqliteColumnExists(t, db, "knowledges", "tag_id"))
}
func TestSQLiteMigrationsUpgradeV16AddsSessionForkColumns(t *testing.T) {
repoRoot := sqliteRepoRoot(t)
legacyRoot := copySQLiteMigrationsThrough(t, repoRoot, 16)
chdirAndRestore(t, legacyRoot)
dbPath := filepath.Join(t.TempDir(), "upgrade-v16.db")
require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", MigrationOptions{SQLiteDBPath: dbPath}))
db := openSQLiteDB(t, dbPath)
versionBefore, dirtyBefore := sqliteMigrationState(t, db)
require.Equal(t, 16, versionBefore)
require.False(t, dirtyBefore)
require.False(t, sqliteColumnExists(t, db, "sessions", "parent_session_id"))
require.False(t, sqliteColumnExists(t, db, "sessions", "forked_from_message_id"))
require.False(t, sqliteColumnExists(t, db, "sessions", "fork_bootstrap"))
require.False(t, sqliteColumnExists(t, db, "messages", "sandbox_checkpoint"))
chdirAndRestore(t, repoRoot)
require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", MigrationOptions{SQLiteDBPath: dbPath}))
db = openSQLiteDB(t, dbPath)
versionAfter, dirtyAfter := sqliteMigrationState(t, db)
require.Equal(t, expectedSQLiteMigrationVersion, versionAfter)
require.False(t, dirtyAfter)
for _, column := range versionedSQLiteColumns["sessions"] {
require.Truef(
t,
sqliteColumnExists(t, db, "sessions", column),
"upgraded SQLite DB must have column sessions.%s",
column,
)
}
require.True(t, sqliteColumnExists(t, db, "messages", "sandbox_checkpoint"))
}
// The allocation migration must come back off cleanly: both tables disappear,
// and applying it again restores them including the partial indexes.
func TestSQLiteSandboxAllocationMigrationRollsBack(t *testing.T) {
repoRoot := sqliteRepoRoot(t)
chdirAndRestore(t, repoRoot)
dbPath := filepath.Join(t.TempDir(), "down.db")
require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", MigrationOptions{SQLiteDBPath: dbPath}))
db := openSQLiteDB(t, dbPath)
version, dirty := sqliteMigrationState(t, db)
require.Equal(t, expectedSQLiteMigrationVersion, version)
require.False(t, dirty)
for _, table := range []string{"session_sandbox_assignments", "sandbox_user_machines"} {
require.Truef(t, sqliteTableExists(t, db, table), "up must create %s", table)
}
require.True(t, sqliteIndexExists(t, db, "idx_session_sandbox_assignments_live_machine"))
require.True(t, sqliteIndexExists(t, db, "idx_session_sandbox_assignments_cleanup_due"))
require.True(t, sqliteIndexExists(t, db, "idx_sandbox_user_machines_empty"))
require.NoError(t, db.Close())
sqlDB, err := sql.Open("sqlite3", dbPath)
require.NoError(t, err)
t.Cleanup(func() { _ = sqlDB.Close() })
driver, err := sqlite3migrate.WithInstance(sqlDB, &sqlite3migrate.Config{})
require.NoError(t, err)
m, err := migrate.NewWithDatabaseInstance("file://migrations/sqlite", "sqlite3", driver)
require.NoError(t, err)
t.Cleanup(func() { _, _ = m.Close() })
// Target the allocation migration even when newer migrations exist.
require.NoError(t, m.Migrate(46))
version, dirty = sqliteMigrationState(t, sqlDB)
require.Equal(t, 46, version)
require.False(t, dirty)
for _, table := range []string{"session_sandbox_assignments", "sandbox_user_machines"} {
require.Falsef(t, sqliteTableExists(t, sqlDB, table), "down must drop %s", table)
}
require.True(t, sqliteColumnExists(t, sqlDB, "sessions", "owner_auth_source"),
"rolling back the allocation tables keeps the owner source of 000046")
require.NoError(t, m.Migrate(47))
version, dirty = sqliteMigrationState(t, sqlDB)
require.Equal(t, 47, version)
require.False(t, dirty)
require.True(t, sqliteTableExists(t, sqlDB, "session_sandbox_assignments"))
require.True(t, sqliteTableExists(t, sqlDB, "sandbox_user_machines"))
require.True(t, sqliteIndexExists(t, sqlDB, "idx_session_sandbox_assignments_live_machine"))
}
func sqliteRepoRoot(t *testing.T) string {
t.Helper()
repoRoot, err := filepath.Abs(filepath.Join("..", ".."))
require.NoError(t, err)
return repoRoot
}
func chdirAndRestore(t *testing.T, dir string) {
t.Helper()
previousDir, err := os.Getwd()
require.NoError(t, err)
require.NoError(t, os.Chdir(dir))
t.Cleanup(func() { _ = os.Chdir(previousDir) })
}
func openSQLiteDB(t *testing.T, dbPath string) *sql.DB {
t.Helper()
db, err := sql.Open("sqlite3", dbPath)
require.NoError(t, err)
t.Cleanup(func() { _ = db.Close() })
return db
}
func sqliteMigrationState(t *testing.T, db *sql.DB) (version int, dirty bool) {
t.Helper()
require.NoError(t, db.QueryRow("SELECT version, dirty FROM schema_migrations").Scan(&version, &dirty))
return version, dirty
}
func sqliteTableExists(t *testing.T, db *sql.DB, table string) bool {
t.Helper()
var n int
require.NoError(t, db.QueryRow(
"SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = ?",
table,
).Scan(&n))
return n == 1
}
// assertSQLiteAgentHistoryQueriesUseTheIndex checks the two per-turn agent
// history queries walk idx_messages_session_created_id in order instead of
// sorting every message of the session.
func assertSQLiteAgentHistoryQueriesUseTheIndex(t *testing.T, db *sql.DB) {
t.Helper()
for name, query := range map[string]string{
"backwards page": `SELECT * FROM messages WHERE session_id = 's'
AND (created_at < '2026-01-01' OR (created_at = '2026-01-01' AND id < 'x'))
AND deleted_at IS NULL ORDER BY created_at DESC, id DESC LIMIT 200`,
"newest checkpoint": `SELECT id FROM messages WHERE session_id = 's' AND role = 'assistant'
AND context_checkpoint IS NOT NULL AND deleted_at IS NULL
ORDER BY created_at DESC, id DESC LIMIT 1`,
} {
rows, err := db.Query("EXPLAIN QUERY PLAN " + query)
require.NoError(t, err, name)
var plan strings.Builder
for rows.Next() {
var id, parent, unused int
var detail string
require.NoError(t, rows.Scan(&id, &parent, &unused, &detail), name)
plan.WriteString(detail + "\n")
}
require.NoError(t, rows.Err(), name)
require.NoError(t, rows.Close(), name)
require.Contains(t, plan.String(), "idx_messages_session_created_id", "%s plan:\n%s", name, plan.String())
require.NotContains(t, plan.String(), "TEMP B-TREE", "%s must not sort:\n%s", name, plan.String())
}
}
func sqliteIndexExists(t *testing.T, db *sql.DB, index string) bool {
t.Helper()
var n int
require.NoError(t, db.QueryRow(
"SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = ?",
index,
).Scan(&n))
return n == 1
}
func sqliteColumnExists(t *testing.T, db *sql.DB, table, column string) bool {
t.Helper()
var n int
require.NoError(t, db.QueryRow(
"SELECT COUNT(*) FROM pragma_table_info(?) WHERE name = ?",
table,
column,
).Scan(&n))
return n == 1
}
func assertSQLiteShareLinkInvitationsWork(t *testing.T, db *sql.DB) {
t.Helper()
_, err := db.Exec("INSERT INTO tenants (name, business) VALUES (?, ?)", "share-link-tenant", "share-link-test")
require.NoError(t, err)
expiresAt := "2099-01-01 00:00:00"
shareLinkInsert := "INSERT INTO tenant_invitations " +
"(tenant_id, invitee_user_id, token, role, status, expires_at) " +
"VALUES (1, '', ?, 'member', 'pending', ?)"
_, err = db.Exec(shareLinkInsert, "token-a", expiresAt)
require.NoError(t, err)
_, err = db.Exec(shareLinkInsert, "token-b", expiresAt)
require.NoError(t, err)
var count int
require.NoError(t, db.QueryRow(
"SELECT COUNT(*) FROM tenant_invitations WHERE tenant_id = 1 AND invitee_user_id = '' AND status = 'pending'",
).Scan(&count))
require.Equal(t, 2, count)
}
func assertSQLiteMCPOAuthPrincipalUpsertWorks(t *testing.T, db *sql.DB) {
t.Helper()
_, err := db.Exec(
"INSERT INTO mcp_services (id, tenant_id, name, transport_type) VALUES (?, 1, 'svc', 'http')",
"svc-migration-1",
)
require.NoError(t, err)
tokenInsertPrefix := "INSERT INTO mcp_oauth_tokens " +
"(id, tenant_id, user_id, service_id, principal_type, principal_id, access_token) "
_, err = db.Exec(
tokenInsertPrefix +
"VALUES ('tok-1', 1, 'u1', 'svc-migration-1', 'web_user', 'u1', 'token-1')",
)
require.NoError(t, err)
_, err = db.Exec(
tokenInsertPrefix +
"VALUES ('tok-2', 1, 'u1', 'svc-migration-1', 'web_user', 'u1', 'token-2') " +
"ON CONFLICT(tenant_id, principal_type, principal_id, service_id) " +
"DO UPDATE SET access_token = excluded.access_token",
)
require.NoError(t, err)
var accessToken string
require.NoError(t, db.QueryRow(
"SELECT access_token FROM mcp_oauth_tokens "+
"WHERE tenant_id = 1 AND principal_type = 'web_user' "+
"AND principal_id = 'u1' AND service_id = 'svc-migration-1'",
).Scan(&accessToken))
require.Equal(t, "token-2", accessToken)
var rowCount int
require.NoError(t, db.QueryRow(
"SELECT COUNT(*) FROM mcp_oauth_tokens WHERE tenant_id = 1 AND service_id = 'svc-migration-1'",
).Scan(&rowCount))
require.Equal(t, 1, rowCount)
}
func copySQLiteMigrationsV4(t *testing.T, repoRoot string) string {
t.Helper()
return copySQLiteMigrationsThrough(t, repoRoot, 4)
}
func copySQLiteMigrationsThrough(t *testing.T, repoRoot string, maxVersion int) string {
t.Helper()
dest := t.TempDir()
srcDir := filepath.Join(repoRoot, "migrations", "sqlite")
destDir := filepath.Join(dest, "migrations", "sqlite")
require.NoError(t, os.MkdirAll(destDir, 0o755))
entries, err := os.ReadDir(srcDir)
require.NoError(t, err)
copied := 0
for _, entry := range entries {
name := entry.Name()
if entry.IsDir() || !strings.HasSuffix(name, ".up.sql") {
continue
}
var version int
_, scanErr := fmt.Sscanf(name, "%d_", &version)
require.NoError(t, scanErr, "sqlite migration filename %s", name)
if version > maxVersion {
continue
}
data, readErr := os.ReadFile(filepath.Join(srcDir, name))
require.NoError(t, readErr)
require.NoError(t, os.WriteFile(filepath.Join(destDir, name), data, 0o600))
copied++
}
require.Greater(t, copied, 0)
return dest
}
func TestSQLiteSessionKindBackfillAndRollback(t *testing.T) {
repoRoot := sqliteRepoRoot(t)
chdirAndRestore(t, copySQLiteMigrationsThrough(t, repoRoot, 38))
dbPath := filepath.Join(t.TempDir(), "session-kind.db")
require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", MigrationOptions{SQLiteDBPath: dbPath}))
db := openSQLiteDB(t, dbPath)
configs := []any{
nil, "invalid JSON", `{"agent_id":"builtin-academy-assistant"}`, `{}`, `null`, `[]`,
`{"agent_id":"another-agent"}`, `{"agent_id":`,
}
for i, config := range configs {
_, err := db.Exec("INSERT INTO sessions (id, tenant_id, agent_config) VALUES (?, 1, ?)", fmt.Sprint(i), config)
require.NoError(t, err)
}
chdirAndRestore(t, repoRoot)
require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", MigrationOptions{SQLiteDBPath: dbPath}))
for i := range configs {
var kind string
require.NoError(t, db.QueryRow("SELECT kind FROM sessions WHERE id = ?", fmt.Sprint(i)).Scan(&kind))
if i == 2 {
require.Equal(t, "assistant", kind)
} else {
require.Empty(t, kind)
}
}
require.True(t, sqliteIndexExists(t, db, "idx_sessions_tenant_kind_user_updated"))
down, err := os.ReadFile(filepath.Join(repoRoot, "migrations/sqlite/000039_session_kind.down.sql"))
require.NoError(t, err)
_, err = db.Exec(string(down))
require.NoError(t, err)
require.False(t, sqliteColumnExists(t, db, "sessions", "kind"))
require.False(t, sqliteIndexExists(t, db, "idx_sessions_tenant_kind_user_updated"))
var count int
require.NoError(t, db.QueryRow("SELECT COUNT(*) FROM sessions").Scan(&count))
require.Equal(t, len(configs), count)
}
@@ -0,0 +1,24 @@
package database
import (
"path/filepath"
"testing"
"github.com/golang-migrate/migrate/v4/source"
_ "github.com/golang-migrate/migrate/v4/source/file"
"github.com/stretchr/testify/require"
)
// Two pull requests that each take the next migration number both pass their
// own checks and collide once both are merged: golang-migrate refuses to load
// a directory with a duplicate version, so every deployment fails to migrate.
// 000104 did exactly that. Loading each directory catches it, since pull
// request CI runs on the merge with the current main.
func TestMigrationDirectoriesLoad(t *testing.T) {
root := sqliteRepoRoot(t)
for _, dir := range []string{"versioned", "sqlite"} {
src, err := source.Open("file://" + filepath.Join(root, "migrations", dir))
require.NoError(t, err, "migrations/%s must load", dir)
require.NoError(t, src.Close())
}
}