Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

93.6 KB
Raw Blame
use super::*;

#[test]
fn project_memory_is_path_scoped_and_bounded() {
    let dir = tempfile::tempdir().unwrap();
    let first = dir.path().join("first");
    let second = dir.path().join("second");
    std::fs::create_dir_all(&first).unwrap();
    std::fs::create_dir_all(&second).unwrap();
    let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();

    assert_eq!(
        db.get_project_memory(first.to_str().unwrap())
            .unwrap()
            .content,
        ""
    );
    let saved = db
        .set_project_memory(first.to_str().unwrap(), "Keep the API stable.")
        .unwrap();
    assert_eq!(saved.content, "Keep the API stable.");
    assert!(saved.updated_at > 0);
    assert_eq!(
        db.get_project_memory(&format!("{}/", first.to_string_lossy()))
            .unwrap()
            .content,
        "Keep the API stable."
    );
    assert_eq!(
        db.get_project_memory(second.to_str().unwrap())
            .unwrap()
            .content,
        ""
    );
    let structured = serde_json::json!([
        {
            "id": "api",
            "title": "API",
            "content": "Keep the API stable."
        },
        {
            "id": "blank",
            "title": "Ignored",
            "content": "  "
        }
    ]);
    let structured_saved = db
        .set_project_memory_entries(first.to_str().unwrap(), &structured)
        .unwrap();
    assert_eq!(structured_saved.content, "## API\n\nKeep the API stable.");
    assert_eq!(structured_saved.entries.as_ref().unwrap().len(), 1);
    assert_eq!(
        db.get_project_memory(first.to_str().unwrap())
            .unwrap()
            .entries
            .unwrap()[0]
            .title,
        "API"
    );
    let oversized = "x".repeat(MAX_PROJECT_MEMORY_BYTES + 1);
    assert!(db
        .set_project_memory(first.to_str().unwrap(), &oversized)
        .is_err());
    assert_eq!(
        db.get_project_memory(first.to_str().unwrap())
            .unwrap()
            .content,
        "## API\n\nKeep the API stable."
    );
}

fn table_exists(conn: &Connection, name: &str) -> bool {
    conn.query_row(
        "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = ?1",
        params![name],
        |r| r.get::<_, i64>(0),
    )
    .map(|n| n > 0)
    .unwrap_or(false)
}

#[test]
fn v14_database_migrates_to_v15_with_the_turn_queue() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("pi.sqlite");
    {
        let db = Database::open(&path).unwrap();
        db.conn()
            .execute_batch(
                "DROP INDEX idx_turn_queue_idempotency;
                     DROP INDEX idx_turn_queue_session;
                     DROP TABLE turn_queue;",
            )
            .unwrap();
        db.conn().pragma_update(None, "user_version", 14).unwrap();
    }
    let db = Database::open(&path).unwrap();
    assert_eq!(schema_version(db.conn()), SCHEMA_VERSION);
    assert!(table_exists(db.conn(), "turn_queue"));
    assert!(migration_backup_path(&path, 14).exists());
}

#[test]
fn v18_database_migrates_session_thinking_omit() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("pi.sqlite");
    {
        let db = Database::open(&path).unwrap();
        db.conn().pragma_update(None, "user_version", 18).unwrap();
    }
    let db = Database::open(&path).unwrap();
    assert_eq!(schema_version(db.conn()), SCHEMA_VERSION);
    assert!(migration_backup_path(&path, 18).exists());
    let sql: String = db
        .conn()
        .query_row(
            "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'sessions'",
            [],
            |row| row.get(0),
        )
        .unwrap();
    assert!(sql.contains("'omit'"), "{sql}");
}

/// Historical v22 databases lack provenance metadata to distinguish whether
/// a title was an untouched placeholder or a deliberate manual rename to that
/// same text. Schema v23 leaves pre-existing sessions classified as `legacy`
/// with their original titles preserved, safely protecting deliberate renames
/// (such as lowercase "new task") from being overwritten by subsequent prompts.
#[test]
fn v22_database_migrates_session_title_sources_without_losing_titles() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("pi.sqlite");
    let (default_id, lowercase_id, renamed_v22_id, manual_id) = {
        let db = Database::open(&path).unwrap();
        // 1. Untouched session created with the default placeholder.
        let default_session =
            crate::sessions::create_session(&db, None, None, None, None, None).unwrap();
        // 2. Untouched session created with the lowercase placeholder.
        let lowercase_session =
            crate::sessions::create_session(&db, Some("new task".into()), None, None, None, None)
                .unwrap();
        // 3. Session that will be renamed while the fixture is at v22.
        let renamed_session = crate::sessions::create_session(
            &db,
            Some("Initial task name".into()),
            None,
            None,
            None,
            None,
        )
        .unwrap();
        // 4. Ordinary manual title.
        let manual_session = crate::sessions::create_session(
            &db,
            Some("A title chosen by the user".into()),
            None,
            None,
            None,
            None,
        )
        .unwrap();

        // Downgrade fixture to schema v22 (no title_source column).
        db.conn()
            .execute_batch("ALTER TABLE sessions DROP COLUMN title_source;")
            .unwrap();
        db.conn().pragma_update(None, "user_version", 22).unwrap();
        // Use the historical title-only rename: v22 has no title_source column.
        db.conn()
            .execute(
                "UPDATE sessions SET title = 'new task' WHERE id = ?1",
                params![renamed_session.id],
            )
            .unwrap();
        (
            default_session.id,
            lowercase_session.id,
            renamed_session.id,
            manual_session.id,
        )
    };

    // Reopen walks the real v22 -> v23 migration.
    let db = Database::open(&path).unwrap();
    assert_eq!(schema_version(db.conn()), SCHEMA_VERSION);
    assert!(migration_backup_path(&path, 22).exists());

    let sources: (String, String, String, String) = db
        .conn()
        .query_row(
            "SELECT
                (SELECT title_source FROM sessions WHERE id = ?1),
                (SELECT title_source FROM sessions WHERE id = ?2),
                (SELECT title_source FROM sessions WHERE id = ?3),
                (SELECT title_source FROM sessions WHERE id = ?4)",
            params![default_id, lowercase_id, renamed_v22_id, manual_id],
            |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
        )
        .unwrap();
    assert_eq!(
        sources,
        (
            "legacy".into(),
            "legacy".into(),
            "legacy".into(),
            "legacy".into()
        )
    );

    // Stored titles are preserved exactly as they were in v22.
    let titles: (String, String, String) = db
        .conn()
        .query_row(
            "SELECT
                (SELECT title FROM sessions WHERE id = ?1),
                (SELECT title FROM sessions WHERE id = ?2),
                (SELECT title FROM sessions WHERE id = ?3)",
            params![lowercase_id, renamed_v22_id, manual_id],
            |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
        )
        .unwrap();
    assert_eq!(titles.0, "new task");
    assert_eq!(titles.1, "new task");
    assert_eq!(titles.2, "A title chosen by the user");

    // Because legacy rows are protected, automatic derivation refuses to overwrite them.
    assert!(!crate::sessions::derive_session_title(&db, &renamed_v22_id, "Fix the login").unwrap());
    assert_eq!(
        crate::sessions::get_session(&db, &renamed_v22_id)
            .unwrap()
            .unwrap()
            .summary
            .title,
        "new task"
    );

    // Automatic title plugin CAS write also refuses legacy rows.
    assert!(!crate::sessions::set_automatic_session_title(
        &db,
        &renamed_v22_id,
        "new task",
        "Plugin generated title",
    )
    .unwrap());
    assert_eq!(
        crate::sessions::get_session(&db, &renamed_v22_id)
            .unwrap()
            .unwrap()
            .summary
            .title,
        "new task"
    );

    // Newly created sessions after upgrade correctly set default or manual.
    let new_default = crate::sessions::create_session(&db, None, None, None, None, None).unwrap();
    assert_eq!(
        db.conn()
            .query_row(
                "SELECT title_source FROM sessions WHERE id = ?1",
                params![new_default.id],
                |row| row.get::<_, String>(0)
            )
            .unwrap(),
        "default"
    );
    assert!(crate::sessions::derive_session_title(&db, &new_default.id, "New turn title").unwrap());
    assert_eq!(
        crate::sessions::get_session(&db, &new_default.id)
            .unwrap()
            .unwrap()
            .summary
            .title,
        "New turn title"
    );
}

#[test]
fn manual_placeholder_title_is_never_overwritten_after_upgrade() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("pi.sqlite");
    let session_id = {
        let db = Database::open(&path).unwrap();
        let session = crate::sessions::create_session(&db, None, None, None, None, None).unwrap();
        // The user explicitly renamed the session to a placeholder title like "New task".
        assert!(crate::sessions::rename_session(&db, &session.id, "New task").unwrap());
        // Stamp as schema v23, simulating a database that already migrated past v22.
        db.conn().pragma_update(None, "user_version", 23).unwrap();
        session.id
    };

    // Reopen walks the real v23 -> v24 upgrade path.
    let db = Database::open(&path).unwrap();
    assert_eq!(schema_version(db.conn()), SCHEMA_VERSION);
    let (title, source): (String, String) = db
        .conn()
        .query_row(
            "SELECT title, title_source FROM sessions WHERE id = ?1",
            params![session_id],
            |row| Ok((row.get(0)?, row.get(1)?)),
        )
        .unwrap();
    assert_eq!(source, "manual");
    assert_eq!(title, "New task");

    // The user-selected title must not be overwritten on the next prompt.
    assert!(!crate::sessions::derive_session_title(&db, &session_id, "Fix the login").unwrap());
    assert_eq!(
        crate::sessions::get_session(&db, &session_id)
            .unwrap()
            .unwrap()
            .summary
            .title,
        "New task"
    );
}

/// v24 adds the isolated-session worktree registry (ADR 0329). A v23 database
/// keeps its projects and sessions, gains the nullable setup-command column
/// and the `worktrees` table, and leaves a pre-migration backup.
#[test]
fn v23_database_gains_worktree_registry_without_losing_projects() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("pi.sqlite");
    let session_id = {
        let db = Database::open(&path).unwrap();
        db.conn()
            .execute(
                "INSERT INTO projects (path, name, pinned, created_at, last_opened_at)
                 VALUES ('/work/app', 'app', 1, 1, 2)",
                [],
            )
            .unwrap();
        let session =
            crate::sessions::create_session(&db, Some("Kept".into()), None, None, None, None)
                .unwrap();
        db.conn()
            .execute_batch(
                "DROP TABLE worktrees;
                 ALTER TABLE projects DROP COLUMN worktree_setup_command;",
            )
            .unwrap();
        db.conn().pragma_update(None, "user_version", 23).unwrap();
        session.id
    };

    let db = Database::open(&path).unwrap();
    assert_eq!(schema_version(db.conn()), SCHEMA_VERSION);
    assert!(migration_backup_path(&path, 23).exists());
    let (name, pinned, command): (String, i64, Option<String>) = db
        .conn()
        .query_row(
            "SELECT name, pinned, worktree_setup_command FROM projects WHERE path = '/work/app'",
            [],
            |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
        )
        .unwrap();
    assert_eq!((name.as_str(), pinned, command), ("app", 1, None));
    assert!(crate::sessions::get_session(&db, &session_id)
        .unwrap()
        .is_some());
    let worktrees: i64 = db
        .conn()
        .query_row("SELECT COUNT(*) FROM worktrees", [], |row| row.get(0))
        .unwrap();
    assert_eq!(worktrees, 0);
}

/// Deleting a session through any path must keep the worktree row, with its
/// session cleared, so the orphan cleanup can still remove the directory and
/// branch that exist on disk.
#[test]
fn deleting_a_session_orphans_its_worktree_rows_instead_of_dropping_them() {
    let dir = tempfile::tempdir().unwrap();
    let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();
    let session = crate::sessions::create_session(&db, None, None, None, None, None).unwrap();
    db.conn()
        .execute(
            "INSERT INTO worktrees (id, session_id, delegation_id, path, common_dir, branch,
                                    owner_branch, status, created_at, updated_at)
             VALUES ('w1', ?1, NULL, '/data/worktrees/p/s1', '/repo/.git', 'pi-desktop/s1',
                     'main', 'active', 1, 1)",
            params![session.id],
        )
        .unwrap();
    assert!(crate::sessions::delete_session(&db, &session.id).unwrap());
    let session_id: Option<String> = db
        .conn()
        .query_row(
            "SELECT session_id FROM worktrees WHERE id = 'w1'",
            [],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(session_id, None);
}

/// A session owns at most one worktree of its own plus one per delegation,
/// and two active worktrees never share a port block.
#[test]
fn worktree_registry_enforces_one_row_per_owner_and_unique_ports() {
    let dir = tempfile::tempdir().unwrap();
    let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();
    let session = crate::sessions::create_session(&db, None, None, None, None, None).unwrap();
    let insert = |id: &str, delegation: Option<&str>, port: Option<i64>| {
        db.conn().execute(
            "INSERT INTO worktrees (id, session_id, delegation_id, path, common_dir, branch,
                                    owner_branch, status, port_base, created_at, updated_at)
             VALUES (?1, ?2, ?3, '/w/' || ?1, '/repo/.git', 'pi-desktop/' || ?1, 'main',
                     'active', ?4, 1, 1)",
            params![id, session.id, delegation, port],
        )
    };
    insert("a", None, Some(41000)).unwrap();
    assert!(
        insert("b", None, Some(41010)).is_err(),
        "second own worktree"
    );
    insert("c", Some("d1"), Some(41010)).unwrap();
    assert!(
        insert("e", Some("d1"), None).is_err(),
        "second worktree for one delegation"
    );
    assert!(
        insert("f", Some("d2"), Some(41000)).is_err(),
        "shared port block"
    );
}

/// v27 adds the per-session `/fast` column (ADR 0334). Existing sessions keep
/// their configuration, default to the normal tier, and a backup remains.
#[test]
fn v25_database_gains_session_fast_mode_defaulting_off() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("pi.sqlite");
    let session_id = {
        let db = Database::open(&path).unwrap();
        let session = crate::sessions::create_session_with_thinking(
            &db,
            Some("Kept".into()),
            None,
            None,
            None,
            None,
            Some("high".into()),
        )
        .unwrap();
        db.conn()
            .execute_batch("ALTER TABLE sessions DROP COLUMN fast_mode;")
            .unwrap();
        db.conn().pragma_update(None, "user_version", 25).unwrap();
        session.id
    };

    let db = Database::open(&path).unwrap();
    assert_eq!(schema_version(db.conn()), SCHEMA_VERSION);
    assert!(migration_backup_path(&path, 25).exists());
    let summary = crate::sessions::get_session(&db, &session_id)
        .unwrap()
        .unwrap()
        .summary;
    assert_eq!(summary.title, "Kept");
    assert_eq!(summary.thinking_level, "high");
    assert!(!summary.fast_mode);
}

/// v21 owns the session checklist. A real v20 database has neither the
/// `sessions` stamps nor the `session_todo` table, so the upgrade must add
/// both, keep the v20 rows, leave a readable pre-migration backup, and stay
/// idempotent when a fixture downgrades the same file in place.
#[test]
fn v20_database_migrates_the_session_checklist_with_a_backup() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("pi.sqlite");
    let session_id = {
        let db = Database::open(&path).unwrap();
        let session = crate::sessions::create_session(
            &db,
            Some("v20 session".into()),
            Some("agent".into()),
            None,
            None,
            None,
        )
        .unwrap();
        db.conn()
            .execute(
                "INSERT INTO artifacts (session_id, path, op, updated_at)
                     VALUES (?1, 'kept.txt', 'write', 1)",
                params![session.id],
            )
            .unwrap();
        session.id
    };

    let downgrade_to_v20 = |path: &Path| {
        let conn = Connection::open(path).unwrap();
        conn.execute_batch(
            "PRAGMA foreign_keys = OFF;
             DROP TABLE IF EXISTS session_todo;
             ALTER TABLE sessions DROP COLUMN todo_revision;
             ALTER TABLE sessions DROP COLUMN todo_updated_at;
             DROP INDEX IF EXISTS idx_sessions_updated_id;
             CREATE INDEX idx_sessions_updated ON sessions(updated_at DESC);
             PRAGMA user_version = 20;",
        )
        .unwrap();
        drop(conn);
    };
    downgrade_to_v20(&path);

    let db = Database::open(&path).unwrap();
    assert_eq!(schema_version(db.conn()), SCHEMA_VERSION);
    assert!(table_exists(db.conn(), "session_todo"));
    assert!(migration_backup_path(&path, 20).exists());
    assert_readable_migration_backup(&path, 20);
    let todo_columns: i64 = db
        .conn()
        .query_row(
            "SELECT COUNT(*) FROM pragma_table_info('sessions')
                 WHERE name IN ('todo_revision', 'todo_updated_at')",
            [],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(todo_columns, 2, "both v21 session stamps are present");
    let (title, revision, updated_at): (String, i64, Option<i64>) = db
        .conn()
        .query_row(
            "SELECT title, todo_revision, todo_updated_at FROM sessions WHERE id = ?1",
            params![session_id],
            |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
        )
        .unwrap();
    assert_eq!(title, "v20 session");
    assert_eq!(revision, 0, "a migrated session starts at revision zero");
    assert!(updated_at.is_none());
    let kept: String = db
        .conn()
        .query_row(
            "SELECT path FROM artifacts WHERE session_id = ?1",
            params![session_id],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(kept, "kept.txt");

    // A second run over the same file, both with and without the v21 objects
    // already in place, must not fail or duplicate anything.
    drop(db);
    downgrade_to_v20(&path);
    let db = Database::open(&path).unwrap();
    assert_eq!(schema_version(db.conn()), SCHEMA_VERSION);
    assert!(table_exists(db.conn(), "session_todo"));
    drop(db);
    {
        let conn = Connection::open(&path).unwrap();
        conn.pragma_update(None, "user_version", 20).unwrap();
    }
    let db = Database::open(&path).unwrap();
    assert_eq!(schema_version(db.conn()), SCHEMA_VERSION);
    assert!(table_exists(db.conn(), "session_todo"));
    assert_eq!(
        db.conn()
            .query_row("SELECT COUNT(*) FROM session_todo", [], |row| row
                .get::<_, i64>(0))
            .unwrap(),
        0
    );
}

fn schema_version(conn: &Connection) -> i64 {
    conn.query_row("PRAGMA user_version", [], |row| row.get(0))
        .unwrap()
}

fn insert_raw_app_settings(db: &Database, raw: &str) {
    db.conn()
        .execute(
            "INSERT INTO kv (ns, key, value_json, updated_at)
                 VALUES ('app', 'app', ?1, 1)
                 ON CONFLICT(ns, key) DO UPDATE SET value_json = excluded.value_json",
            params![raw],
        )
        .unwrap();
}

fn assert_readable_migration_backup(path: &Path, version: i64) {
    let backup_path = migration_backup_path(path, version);
    assert!(
        backup_path.exists(),
        "missing {} backup",
        backup_path.display()
    );
    let backup = Connection::open(&backup_path).unwrap();
    assert_eq!(schema_version(&backup), version);
    let integrity: String = backup
        .query_row("PRAGMA integrity_check", [], |row| row.get(0))
        .unwrap();
    assert_eq!(integrity, "ok");
    drop(backup);
}

fn fail_v8_migration(path: &Path) -> String {
    let error = match Database::open(path) {
        Ok(db) => {
            drop(db);
            panic!("schema v8 migration unexpectedly succeeded")
        }
        Err(error) => error,
    };
    let source = Connection::open(path).unwrap();
    assert_eq!(schema_version(&source), 8);
    drop(source);
    assert_readable_migration_backup(path, 8);
    error.to_string()
}

#[test]
fn fresh_open_creates_latest_schema() {
    let dir = tempfile::tempdir().unwrap();
    let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();
    let version: i64 = db
        .conn()
        .query_row("PRAGMA user_version", [], |r| r.get(0))
        .unwrap();
    assert_eq!(version, SCHEMA_VERSION);
    for table in [
        "kv",
        "projects",
        "providers",
        "models",
        "sessions",
        "turns",
        "notifications",
        "messages",
        "message_revisions",
        "artifacts",
        "scheduled_tasks",
        "task_runs",
        "secrets_meta",
        "audit_log",
        "plan_approvals",
        "session_import_origins",
        "session_todo",
    ] {
        assert!(table_exists(db.conn(), table), "missing {table}");
    }
    let thinking_column: (String, String) = db
        .conn()
        .query_row(
            "SELECT name, dflt_value
                 FROM pragma_table_info('sessions')
                 WHERE name = 'thinking_level'",
            [],
            |row| Ok((row.get(0)?, row.get(1)?)),
        )
        .unwrap();
    assert_eq!(thinking_column, ("thinking_level".into(), "'off'".into()));

    let index_count: i64 = db
        .conn()
        .query_row(
            "SELECT COUNT(*) FROM sqlite_master
                 WHERE type = 'index' AND name IN (
                   'idx_plan_approvals_session',
                   'idx_plan_approvals_pending',
                   'idx_plan_approvals_one_pending_session',
                   'idx_plan_approvals_execution_queue',
                   'idx_plan_approvals_execution_id'
                 )",
            [],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(index_count, 5);
    let running_turn_index: i64 = db
        .conn()
        .query_row(
            "SELECT COUNT(*) FROM sqlite_master
                 WHERE type = 'index' AND name = 'idx_turns_one_running_session'",
            [],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(running_turn_index, 1);

    let scheduled_mode_columns: i64 = db
        .conn()
        .query_row(
            "SELECT COUNT(*)
                 FROM pragma_table_info('scheduled_tasks')
                 WHERE name = 'mode'",
            [],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(scheduled_mode_columns, 0);

    // v7: transcript payloads live in per-session files, not columns.
    for (table, column) in [
        ("messages", "content_json"),
        ("messages", "meta_json"),
        ("message_revisions", "messages_json"),
    ] {
        let n: i64 = db
            .conn()
            .query_row(
                &format!("SELECT COUNT(*) FROM pragma_table_info('{table}') WHERE name = ?1"),
                params![column],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(n, 0, "{table}.{column} must not exist in v7");
    }
}

#[test]
fn migrates_v13_plugin_session_schema() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("pi.sqlite");
    {
        let db = Database::open(&path).unwrap();
        db.conn()
            .execute(
                "INSERT INTO sessions (id, created_at, updated_at)
                     VALUES ('existing-core', 1, 1)",
                [],
            )
            .unwrap();
        db.conn()
            .execute_batch(
                "DROP TABLE session_import_origins;
                     DROP INDEX idx_sessions_deleted;
                     ALTER TABLE sessions DROP COLUMN deleted_at;",
            )
            .unwrap();
        db.conn().pragma_update(None, "user_version", 13).unwrap();
    }

    let db = Database::open(&path).unwrap();
    assert_eq!(schema_version(db.conn()), SCHEMA_VERSION);
    assert!(table_exists(db.conn(), "session_import_origins"));
    assert_eq!(
        db.conn()
            .query_row(
                "SELECT COUNT(*) FROM pragma_table_info('sessions')
                     WHERE name = 'deleted_at'",
                [],
                |row| row.get::<_, i64>(0),
            )
            .unwrap(),
        1
    );
    assert_eq!(
        db.conn()
            .query_row(
                "SELECT deleted_at FROM sessions WHERE id = 'existing-core'",
                [],
                |row| row.get::<_, Option<i64>>(0),
            )
            .unwrap(),
        None
    );
    assert_readable_migration_backup(&path, 13);
}

#[test]
fn archives_pre_v7_database_and_starts_fresh() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("pi.sqlite");
    {
        let conn = Connection::open(&path).unwrap();
        conn.execute_batch(
            "CREATE TABLE sessions (id TEXT PRIMARY KEY);
                 INSERT INTO sessions (id) VALUES ('legacy');",
        )
        .unwrap();
        conn.pragma_update(None, "user_version", 6).unwrap();
    }

    let db = Database::open(&path).unwrap();
    let version: i64 = db
        .conn()
        .query_row("PRAGMA user_version", [], |r| r.get(0))
        .unwrap();
    assert_eq!(version, SCHEMA_VERSION);
    let sessions: i64 = db
        .conn()
        .query_row("SELECT COUNT(*) FROM sessions", [], |r| r.get(0))
        .unwrap();
    assert_eq!(sessions, 0, "fresh database starts empty");

    let bak = dir.path().join("pi.sqlite.v6.bak");
    assert!(bak.exists(), "legacy file is archived for manual recovery");
    let old = Connection::open(&bak).unwrap();
    let preserved: i64 = old
        .query_row("SELECT COUNT(*) FROM sessions", [], |r| r.get(0))
        .unwrap();
    assert_eq!(preserved, 1, "archive keeps the legacy data");

    // Reopening the fresh v7 file is a plain open, not another reset.
    drop(db);
    let db = Database::open(&path).unwrap();
    let version: i64 = db
        .conn()
        .query_row("PRAGMA user_version", [], |r| r.get(0))
        .unwrap();
    assert_eq!(version, SCHEMA_VERSION);
    assert!(table_exists(db.conn(), "messages"));
}

#[test]
fn kv_roundtrip_and_delete() {
    let dir = tempfile::tempdir().unwrap();
    let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();
    db.kv_set("plugin:demo", "cfg", &serde_json::json!({ "on": true }))
        .unwrap();
    assert_eq!(
        db.kv_get("plugin:demo", "cfg").unwrap().unwrap(),
        serde_json::json!({ "on": true })
    );
    db.kv_delete("plugin:demo", "cfg").unwrap();
    assert!(db.kv_get("plugin:demo", "cfg").unwrap().is_none());
}

#[test]
fn migrates_v7_chat_modes_settings_and_scheduled_values_to_plan() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("pi.sqlite");
    {
        let db = Database::open(&path).unwrap();
        db.conn()
            .execute(
                "INSERT INTO sessions (id, mode, created_at, updated_at)
                     VALUES ('legacy-session', 'chat', 1, 1)",
                [],
            )
            .unwrap();
        db.kv_set(
            "app",
            "app",
            &serde_json::json!({
                "defaultMode": "chat",
                "theme": "dark",
                "planApprovalPermissionMode": "auto",
                "notification": { "mode": "silent" },
                "plugin": { "mode": "plugin", "defaultMode": "extension" }
            }),
        )
        .unwrap();
        db.conn()
                .execute(
                    "INSERT INTO scheduled_tasks
                        (id, title, prompt, config_json, created_at, updated_at)
                     VALUES (
                         'task-1', 'legacy', 'run',
                         '{\"mode\":\"chat\",\"notification\":{\"mode\":\"silent\"},\"plugin\":{\"defaultMode\":\"extension\",\"mode\":\"plugin\"}}',
                         1, 1
                     )",
                    [],
                )
                .unwrap();
        db.kv_set(
            "plugin:test",
            "config",
            &serde_json::json!({
                "mode": "chat",
                "defaultMode": "chat",
                "nested": { "operatingMode": "chat" }
            }),
        )
        .unwrap();
        // Simulate a real v7 file: the approval table did not exist until
        // the migration itself creates the canonical table and indexes.
        db.conn()
            .execute_batch("DROP TABLE plan_approvals;")
            .unwrap();
        db.conn().pragma_update(None, "user_version", 7).unwrap();
    }

    let db = Database::open(&path).unwrap();
    let version: i64 = db
        .conn()
        .query_row("PRAGMA user_version", [], |row| row.get(0))
        .unwrap();
    assert_eq!(version, SCHEMA_VERSION);
    let mode: String = db
        .conn()
        .query_row(
            "SELECT mode FROM sessions WHERE id = 'legacy-session'",
            [],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(mode, "plan");
    assert_eq!(
        db.get_setting("app").unwrap().unwrap()["defaultMode"],
        serde_json::json!("plan")
    );
    let settings = db.get_setting("app").unwrap().unwrap();
    assert_eq!(settings["theme"], serde_json::json!("dark"));
    assert_eq!(settings["notification"]["mode"], "silent");
    assert_eq!(
        settings["plugin"],
        serde_json::json!({ "mode": "plugin", "defaultMode": "extension" })
    );
    assert!(settings
        .get(OBSOLETE_PLAN_APPROVAL_PERMISSION_MODE)
        .is_none());
    let raw_settings = db.kv_get("app", "app").unwrap().unwrap();
    assert!(raw_settings
        .get(OBSOLETE_PLAN_APPROVAL_PERMISSION_MODE)
        .is_none());
    let config: String = db
        .conn()
        .query_row(
            "SELECT config_json FROM scheduled_tasks WHERE id = 'task-1'",
            [],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(
        serde_json::from_str::<Value>(&config).unwrap()["mode"],
        "plan"
    );
    let config_value = serde_json::from_str::<Value>(&config).unwrap();
    assert_eq!(config_value["notification"]["mode"], "silent");
    assert_eq!(
        config_value["plugin"],
        serde_json::json!({ "defaultMode": "extension", "mode": "plugin" })
    );
    assert_eq!(
        db.kv_get("plugin:test", "config").unwrap().unwrap(),
        serde_json::json!({
            "mode": "chat",
            "defaultMode": "chat",
            "nested": { "operatingMode": "chat" }
        })
    );
    assert!(table_exists(db.conn(), "plan_approvals"));
    let index_count: i64 = db
        .conn()
        .query_row(
            "SELECT COUNT(*) FROM sqlite_master
                 WHERE type = 'index' AND name IN (
                   'idx_plan_approvals_session',
                   'idx_plan_approvals_pending',
                   'idx_plan_approvals_one_pending_session',
                   'idx_plan_approvals_execution_queue',
                   'idx_plan_approvals_execution_id'
                 )",
            [],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(index_count, 5);
    drop(db);
    assert_readable_migration_backup(&path, 8);
}

#[test]
fn migrates_v8_approvals_without_expiring_new_work() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("pi.sqlite");
    {
        let db = Database::open(&path).unwrap();
        db.conn()
            .execute(
                "INSERT INTO sessions (id, mode, created_at, updated_at)
                     VALUES ('v8-session', 'plan', 1, 1)",
                [],
            )
            .unwrap();
        db.conn()
            .execute_batch("DROP TABLE plan_approvals;")
            .unwrap();
        db.kv_set(
            "app",
            "app",
            &serde_json::json!({
                "theme": "light",
                "planApprovalPermissionMode": "accept-edits"
            }),
        )
        .unwrap();
        db.conn()
            .execute_batch(
                "CREATE TABLE plan_approvals (
                       request_id TEXT PRIMARY KEY,
                       session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
                       turn_id TEXT NOT NULL,
                       tool_call_id TEXT NOT NULL UNIQUE,
                       plan_json TEXT NOT NULL,
                       status TEXT NOT NULL CHECK (status IN (
                         'pending', 'approved', 'changes_requested', 'rejected',
                         'expired', 'interrupted'
                       )),
                       action TEXT CHECK (action IN ('approve', 'request_changes', 'reject')),
                       target_permission_mode TEXT CHECK (
                         target_permission_mode IN ('ask', 'accept-edits', 'auto')
                       ),
                       feedback TEXT,
                       created_at INTEGER NOT NULL,
                       expires_at INTEGER NOT NULL,
                       resolved_at INTEGER,
                       error_code TEXT
                     );
                     INSERT INTO plan_approvals (
                       request_id, session_id, turn_id, tool_call_id, plan_json,
                       status, created_at, expires_at
                     ) VALUES
                       ('terminal-v8', 'v8-session', 'turn-terminal', 'call-terminal',
                        'terminal plan', 'approved', 10, 20),
                       ('pending-v8', 'v8-session', 'turn-pending', 'call-pending',
                        'pending plan', 'pending', 11, 21);",
            )
            .unwrap();
        db.conn().pragma_update(None, "user_version", 8).unwrap();
    }

    let db = Database::open(&path).unwrap();
    let version: i64 = db
        .conn()
        .query_row("PRAGMA user_version", [], |row| row.get(0))
        .unwrap();
    assert_eq!(version, SCHEMA_VERSION);
    let terminal: (String, Option<String>, i64) = db
        .conn()
        .query_row(
            "SELECT status, error_code, version FROM plan_approvals
                 WHERE request_id = 'terminal-v8'",
            [],
            |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
        )
        .unwrap();
    assert_eq!(terminal, ("approved".into(), None, 1));
    let pending: (String, Option<String>, Option<String>, i64) = db
        .conn()
        .query_row(
            "SELECT status, error_code, artifact_relative_path, version
                 FROM plan_approvals WHERE request_id = 'pending-v8'",
            [],
            |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
        )
        .unwrap();
    assert_eq!(
        pending,
        (
            "interrupted".into(),
            Some("PLAN_APPROVAL_INTERRUPTED".into()),
            None,
            2
        )
    );
    let settings = db.get_setting("app").unwrap().unwrap();
    assert_eq!(settings["theme"], serde_json::json!("light"));
    assert!(settings
        .get(OBSOLETE_PLAN_APPROVAL_PERMISSION_MODE)
        .is_none());
    let raw_settings = db.kv_get("app", "app").unwrap().unwrap();
    assert!(raw_settings
        .get(OBSOLETE_PLAN_APPROVAL_PERMISSION_MODE)
        .is_none());
    drop(db);
    assert_readable_migration_backup(&path, 8);
}

#[test]
fn v8_migration_rejects_malformed_app_settings_and_preserves_source() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("pi.sqlite");
    {
        let db = Database::open(&path).unwrap();
        db.conn()
            .execute(
                "INSERT INTO sessions (id, mode, created_at, updated_at)
                     VALUES ('malformed-app-session', 'agent', 1, 1)",
                [],
            )
            .unwrap();
        insert_raw_app_settings(&db, "{not-json");
        db.conn().pragma_update(None, "user_version", 8).unwrap();
    }

    let error = fail_v8_migration(&path);
    assert!(error.contains("app settings JSON is malformed"), "{error}");
    let source = Connection::open(&path).unwrap();
    let mode: String = source
        .query_row(
            "SELECT mode FROM sessions WHERE id = 'malformed-app-session'",
            [],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(mode, "agent");
    drop(source);
}

#[test]
fn v8_migration_rejects_malformed_scheduled_config_and_preserves_source() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("pi.sqlite");
    {
        let db = Database::open(&path).unwrap();
        db.conn()
            .execute(
                "INSERT INTO scheduled_tasks
                        (id, title, prompt, config_json, created_at, updated_at)
                     VALUES ('malformed-config-task', 'broken', 'run', '{not-json', 1, 1)",
                [],
            )
            .unwrap();
        db.conn().pragma_update(None, "user_version", 8).unwrap();
    }

    let error = fail_v8_migration(&path);
    assert!(
        error.contains("scheduled task 'malformed-config-task' config_json is malformed"),
        "{error}"
    );
    let source = Connection::open(&path).unwrap();
    let config: String = source
        .query_row(
            "SELECT config_json FROM scheduled_tasks
                 WHERE id = 'malformed-config-task'",
            [],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(config, "{not-json");
    drop(source);
}

#[test]
fn v8_migration_rejects_invalid_session_mode_and_preserves_source() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("pi.sqlite");
    {
        let db = Database::open(&path).unwrap();
        db.conn()
            .execute(
                "INSERT INTO sessions (id, mode, created_at, updated_at)
                     VALUES ('invalid-mode-session', 'invalid', 1, 1)",
                [],
            )
            .unwrap();
        db.conn().pragma_update(None, "user_version", 8).unwrap();
    }

    let error = fail_v8_migration(&path);
    assert!(
        error.contains("session 'invalid-mode-session' has invalid mode 'invalid'"),
        "{error}"
    );
    let source = Connection::open(&path).unwrap();
    let mode: String = source
        .query_row(
            "SELECT mode FROM sessions WHERE id = 'invalid-mode-session'",
            [],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(mode, "invalid");
    drop(source);
}

#[test]
fn v8_migration_rejects_invalid_shell_and_preserves_source() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("pi.sqlite");
    let invalid_shell = if cfg!(windows) {
        crate::tools::shell::BASH_ID
    } else {
        crate::tools::shell::WINDOWS_POWERSHELL_ID
    };
    {
        let db = Database::open(&path).unwrap();
        insert_raw_app_settings(
            &db,
            &serde_json::json!({
                "defaultCommandShell": invalid_shell,
                "theme": "dark"
            })
            .to_string(),
        );
        db.conn().pragma_update(None, "user_version", 8).unwrap();
    }

    let error = fail_v8_migration(&path);
    assert!(
        error.contains("app settings defaultCommandShell")
            && error.contains("unavailable on this platform"),
        "{error}"
    );
    let source = Connection::open(&path).unwrap();
    let raw: String = source
        .query_row(
            "SELECT value_json FROM kv WHERE ns = 'app' AND key = 'app'",
            [],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(
        serde_json::from_str::<Value>(&raw).unwrap()["defaultCommandShell"],
        invalid_shell
    );
    drop(source);
}

#[test]
fn v8_migration_rejects_unknown_shell_and_preserves_source() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("pi.sqlite");
    let unknown_shell = "not-a-real-command-shell";
    {
        let db = Database::open(&path).unwrap();
        insert_raw_app_settings(
            &db,
            &serde_json::json!({
                "defaultCommandShell": unknown_shell,
                "theme": "dark"
            })
            .to_string(),
        );
        db.conn().pragma_update(None, "user_version", 8).unwrap();
    }

    let error = fail_v8_migration(&path);
    assert!(
        error.contains("app settings defaultCommandShell has unknown shell ID")
            && error.contains(unknown_shell),
        "{error}"
    );
    let source = Connection::open(&path).unwrap();
    let raw: String = source
        .query_row(
            "SELECT value_json FROM kv WHERE ns = 'app' AND key = 'app'",
            [],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(
        serde_json::from_str::<Value>(&raw).unwrap()["defaultCommandShell"],
        unknown_shell
    );
    drop(source);
}

#[test]
fn migration_accepts_current_platform_shell_when_catalog_marks_it_unavailable() {
    let conn = Connection::open_in_memory().unwrap();
    conn.execute_batch(
        "CREATE TABLE kv (
                ns TEXT NOT NULL,
                key TEXT NOT NULL,
                value_json TEXT NOT NULL,
                updated_at INTEGER NOT NULL,
                PRIMARY KEY (ns, key)
            ) WITHOUT ROWID;",
    )
    .unwrap();
    let shell_id = crate::tools::shell::default_shell_id();
    conn.execute(
        "INSERT INTO kv (ns, key, value_json, updated_at)
             VALUES ('app', 'app', ?1, 1)",
        params![serde_json::json!({
            "defaultCommandShell": shell_id,
            "defaultMode": "chat"
        })
        .to_string()],
    )
    .unwrap();
    let catalog = crate::tools::shell::catalog_for_platform(
        crate::tools::shell::current_platform(),
        Some(shell_id),
        |_| false,
    );
    assert!(catalog
        .choices
        .iter()
        .any(|choice| { choice.id == shell_id && !choice.available }));

    let tx = conn.unchecked_transaction().unwrap();
    migrate_app_settings(&tx, &catalog).unwrap();
    tx.commit().unwrap();

    let raw: String = conn
        .query_row(
            "SELECT value_json FROM kv WHERE ns = 'app' AND key = 'app'",
            [],
            |row| row.get(0),
        )
        .unwrap();
    let settings = serde_json::from_str::<Value>(&raw).unwrap();
    assert_eq!(settings["defaultCommandShell"], shell_id);
    assert_eq!(settings["defaultMode"], "plan");
}

#[test]
fn boot_interrupts_pending_and_queued_plan_work_without_replaying_it() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("pi.sqlite");
    {
        let db = Database::open(&path).unwrap();
        db.conn()
            .execute(
                "INSERT INTO sessions (id, mode, permission_mode, created_at, updated_at)
                     VALUES ('execution-session', 'agent', 'auto', 1, 1)",
                [],
            )
            .unwrap();
        db.conn()
                .execute(
                    "INSERT INTO plan_approvals (
                       request_id, session_id, turn_id, tool_call_id, plan_json,
                       title, question, status, created_at, updated_at,
                       artifact_relative_path, artifact_sha256, artifact_size_bytes,
                       version, execution_id, execution_state, target_permission_mode
                     ) VALUES
                       ('running-proposal', 'execution-session', 'turn-1', 'call-1',
                        'running', 'Running', '?', 'approved', 1, 1,
                        '.pi/plan/running.md', 'hash', 7, 1, 'running-execution', 'running', 'auto'),
                       ('queued-proposal', 'execution-session', 'turn-2', 'call-2',
                        'queued', 'Queued', '?', 'approved', 2, 2,
                        '.pi/plan/queued.md', 'hash', 6, 1, 'queued-execution', 'queued', 'auto'),
                       ('pending-proposal', 'execution-session', 'turn-3', 'call-3',
                        'pending', 'Pending', '?', 'pending', 3, 3,
                        '.pi/plan/pending.md', 'hash', 7, 1, NULL, NULL, 'auto')",
                    [],
                )
                .unwrap();
    }
    let db = Database::open(&path).unwrap();
    let running: (String, Option<String>) = db
        .conn()
        .query_row(
            "SELECT execution_state, error_code FROM plan_approvals
                 WHERE execution_id = 'running-execution'",
            [],
            |row| Ok((row.get(0)?, row.get(1)?)),
        )
        .unwrap();
    assert_eq!(
        running,
        (
            "interrupted".into(),
            Some("PLAN_EXECUTION_INTERRUPTED".into())
        )
    );
    let queued: String = db
        .conn()
        .query_row(
            "SELECT execution_state FROM plan_approvals
                 WHERE execution_id = 'queued-execution'",
            [],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(queued, "interrupted");
    let pending: (String, Option<String>) = db
        .conn()
        .query_row(
            "SELECT status, error_code FROM plan_approvals
                 WHERE request_id = 'pending-proposal'",
            [],
            |row| Ok((row.get(0)?, row.get(1)?)),
        )
        .unwrap();
    assert_eq!(
        pending,
        (
            "interrupted".into(),
            Some("PLAN_APPROVAL_INTERRUPTED".into())
        )
    );
    let execution_audits: i64 = db
        .conn()
        .query_row(
            "SELECT COUNT(*) FROM audit_log
                 WHERE kind = 'plan_execution_interrupted'",
            [],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(execution_audits, 2);
    let approval_audits: i64 = db
        .conn()
        .query_row(
            "SELECT COUNT(*) FROM audit_log
                 WHERE kind = 'plan_approval_interrupted'",
            [],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(approval_audits, 1);
    let session_config: (String, String) = db
        .conn()
        .query_row(
            "SELECT mode, permission_mode FROM sessions
                 WHERE id = 'execution-session'",
            [],
            |row| Ok((row.get(0)?, row.get(1)?)),
        )
        .unwrap();
    assert_eq!(session_config, ("agent".into(), "auto".into()));
}

#[test]
fn migrates_v9_running_turns_before_creating_single_turn_index() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("pi.sqlite");
    {
        let db = Database::open(&path).unwrap();
        db.conn()
            .execute_batch("DROP INDEX idx_turns_one_running_session;")
            .unwrap();
        db.conn()
            .execute(
                "INSERT INTO sessions (id, created_at, updated_at)
                     VALUES ('migration-session', 1, 1)",
                [],
            )
            .unwrap();
        db.conn()
            .execute(
                "INSERT INTO turns (id, session_id, started_at)
                     VALUES ('old-turn-1', 'migration-session', 1),
                            ('old-turn-2', 'migration-session', 2)",
                [],
            )
            .unwrap();
        db.conn()
            .execute(
                "INSERT INTO scheduled_tasks
                        (id, title, prompt, config_json, created_at, updated_at)
                     VALUES ('migration-task', 'legacy', 'run', '{\"mode\":\"chat\"}', 1, 1)",
                [],
            )
            .unwrap();
        db.conn().pragma_update(None, "user_version", 9).unwrap();
    }

    let db = Database::open(&path).unwrap();
    let states: Vec<(String, Option<String>, Option<i64>)> = {
        let mut stmt = db
            .conn()
            .prepare(
                "SELECT status, error_code, ended_at FROM turns
                     WHERE session_id = 'migration-session' ORDER BY id",
            )
            .unwrap();
        stmt.query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))
            .unwrap()
            .collect::<rusqlite::Result<Vec<_>>>()
            .unwrap()
    };
    assert_eq!(states.len(), 2);
    for (status, error_code, ended_at) in states {
        assert_eq!(status, "aborted");
        assert_eq!(error_code.as_deref(), Some("TURN_ABORTED"));
        assert!(ended_at.is_some());
    }
    let index_exists: bool = db
        .conn()
        .query_row(
            "SELECT EXISTS(
                   SELECT 1 FROM sqlite_master
                   WHERE type = 'index' AND name = 'idx_turns_one_running_session'
                 )",
            [],
            |row| row.get(0),
        )
        .unwrap();
    assert!(index_exists);
    let config: String = db
        .conn()
        .query_row(
            "SELECT config_json FROM scheduled_tasks WHERE id = 'migration-task'",
            [],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(
        serde_json::from_str::<Value>(&config).unwrap()["mode"],
        "plan"
    );
    drop(db);
    assert_readable_migration_backup(&path, 9);
}

#[test]
fn migrates_v10_approvals_by_labelling_them_plan_contracts() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("pi.sqlite");
    {
        let db = Database::open(&path).unwrap();
        db.conn()
            .execute_batch(
                "ALTER TABLE plan_approvals DROP COLUMN kind;
                     INSERT INTO sessions (id, mode, created_at, updated_at)
                     VALUES ('legacy-session', 'plan', 1, 1);
                     INSERT INTO plan_approvals
                        (request_id, session_id, turn_id, tool_call_id, plan_json,
                         status, created_at, updated_at)
                     VALUES ('legacy-approval', 'legacy-session', 'legacy-turn',
                             'legacy-call', '# Plan', 'approved', 1, 1);",
            )
            .unwrap();
        db.conn().pragma_update(None, "user_version", 10).unwrap();
    }

    let db = Database::open(&path).unwrap();
    let version: i64 = db
        .conn()
        .query_row("PRAGMA user_version", [], |row| row.get(0))
        .unwrap();
    assert_eq!(version, SCHEMA_VERSION);
    let kind: String = db
        .conn()
        .query_row(
            "SELECT kind FROM plan_approvals WHERE request_id = 'legacy-approval'",
            [],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(kind, "plan");
    // The new column still refuses anything outside the two contracts.
    assert!(db
        .conn()
        .execute(
            "UPDATE plan_approvals SET kind = 'sprint' WHERE request_id = 'legacy-approval'",
            [],
        )
        .is_err());
    db.conn()
        .execute(
            "UPDATE plan_approvals SET kind = 'goal' WHERE request_id = 'legacy-approval'",
            [],
        )
        .unwrap();
    drop(db);
    assert_readable_migration_backup(&path, 10);
}

#[test]
fn migrates_v12_by_dropping_a2a_tables() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("pi.sqlite");
    {
        let db = Database::open(&path).unwrap();
        db.conn()
            .execute_batch(
                "CREATE TABLE a2a_tasks (id TEXT PRIMARY KEY);
                     CREATE TABLE a2a_messages (id TEXT PRIMARY KEY);
                     CREATE TABLE a2a_artifacts (id TEXT PRIMARY KEY);
                     CREATE TABLE a2a_push_configs (id TEXT PRIMARY KEY);",
            )
            .unwrap();
        db.conn().pragma_update(None, "user_version", 12).unwrap();
    }

    let db = Database::open(&path).unwrap();
    let version: i64 = db
        .conn()
        .query_row("PRAGMA user_version", [], |row| row.get(0))
        .unwrap();
    assert_eq!(version, SCHEMA_VERSION);
    for table in [
        "a2a_tasks",
        "a2a_messages",
        "a2a_artifacts",
        "a2a_push_configs",
    ] {
        assert!(!table_exists(db.conn(), table), "leftover {table}");
    }
    drop(db);
    assert_readable_migration_backup(&path, 12);
}

#[test]
fn goal_is_a_valid_persisted_session_mode() {
    let dir = tempfile::tempdir().unwrap();
    let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();
    db.conn()
        .execute(
            "INSERT INTO sessions (id, mode, created_at, updated_at)
                 VALUES ('goal-session', 'goal', 1, 1)",
            [],
        )
        .unwrap();
    let tx = db.conn().unchecked_transaction().unwrap();
    validate_session_modes(&tx).unwrap();
    let mut settings = serde_json::json!({ "defaultMode": "goal" });
    migrate_and_validate_top_level_mode(&mut settings, "defaultMode", "app settings").unwrap();
    assert_eq!(settings["defaultMode"], "goal");
    let mut invalid = serde_json::json!({ "defaultMode": "sprint" });
    assert!(
        migrate_and_validate_top_level_mode(&mut invalid, "defaultMode", "app settings").is_err()
    );
}

#[test]
fn project_group_roundtrips_roots_and_shared_context() {
    let dir = tempfile::tempdir().unwrap();
    let first = dir.path().join("app");
    let second = dir.path().join("docs");
    std::fs::create_dir_all(&first).unwrap();
    std::fs::create_dir_all(&second).unwrap();
    let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();

    let group = db
        .create_project_group(
            "Acme workspace",
            &[
                first.to_string_lossy().into(),
                second.to_string_lossy().into(),
            ],
        )
        .unwrap();
    assert!(!group.legacy);
    assert_eq!(group.name, "Acme workspace");
    let canonical_first = crate::db::canonical_project_path(&first.to_string_lossy()).unwrap();
    assert_eq!(group.primary_path, canonical_first);
    assert_eq!(group.roots.len(), 2);
    assert_eq!(db.list_project_groups().unwrap().len(), 1);

    let memory = db
        .set_project_group_memory(
            &group.id,
            &serde_json::json!([{
                "id": "stack",
                "title": "Stack",
                "content": "Use Rust for services."
            }]),
        )
        .unwrap();
    assert_eq!(memory.content, "## Stack\n\nUse Rust for services.");
    assert_eq!(
        db.set_project_group_instructions(&group.id, "Keep changes backwards compatible.")
            .unwrap(),
        "Keep changes backwards compatible."
    );
    let context = db
        .project_group_context_for_path(&second.to_string_lossy())
        .unwrap()
        .unwrap();
    assert_eq!(context.group_id, group.id);
    assert_eq!(context.instructions, "Keep changes backwards compatible.");
    assert_eq!(context.memory.content, "## Stack\n\nUse Rust for services.");

    let renamed = db
        .rename_project_group(&group.id, "Renamed workspace")
        .unwrap();
    assert_eq!(renamed.name, "Renamed workspace");
    assert!(db
        .create_project_group("Duplicate", &[first.to_string_lossy().into()])
        .is_err());
}

#[test]
fn project_group_update_detaches_roots_with_chats_without_orphaning_them() {
    let dir = tempfile::tempdir().unwrap();
    let primary = dir.path().join("primary");
    let first = dir.path().join("first");
    let second = dir.path().join("second");
    std::fs::create_dir_all(&primary).unwrap();
    std::fs::create_dir_all(&first).unwrap();
    std::fs::create_dir_all(&second).unwrap();
    let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();
    let group = db
        .create_project_group(
            "Editable",
            &[
                primary.to_string_lossy().into(),
                first.to_string_lossy().into(),
            ],
        )
        .unwrap();

    let updated = db
        .update_project_group(
            &group.id,
            "Adjusted",
            &[
                primary.to_string_lossy().into(),
                second.to_string_lossy().into(),
            ],
            None,
        )
        .unwrap();
    assert_eq!(updated.name, "Adjusted");
    assert_eq!(updated.roots.len(), 2);
    assert_eq!(updated.roots[0].path, group.primary_path);
    assert_eq!(
        updated.roots[1].path,
        crate::db::canonical_project_path(&second.to_string_lossy()).unwrap()
    );
    assert_eq!(updated.detached_paths.len(), 1);
    assert_eq!(db.list_project_groups().unwrap().len(), 1);

    let session = crate::sessions::create_session(
        &db,
        Some("Existing chat".into()),
        Some("agent".into()),
        None,
        None,
        Some(second.to_string_lossy().into_owned()),
    )
    .unwrap();
    assert!(db
        .update_project_group(
            &updated.id,
            "Adjusted again",
            &[second.to_string_lossy().into()],
            None,
        )
        .unwrap_err()
        .to_string()
        .contains("primary folder"));
    let canonical_second = crate::db::canonical_project_path(&second.to_string_lossy()).unwrap();
    assert_eq!(
        session.project_path.as_deref(),
        Some(canonical_second.as_str())
    );

    let detached = db
        .update_project_group(
            &updated.id,
            "Adjusted again",
            &[primary.to_string_lossy().into()],
            None,
        )
        .expect("a root with chats can be detached from the group");
    assert_eq!(detached.roots.len(), 1);
    assert_eq!(detached.roots[0].path, group.primary_path);
    assert_eq!(detached.detached_paths.len(), 1);

    let groups = db.list_project_groups().unwrap();
    assert_eq!(groups.len(), 2);
    let standalone = groups
        .iter()
        .find(|candidate| candidate.roots[0].path == canonical_second)
        .expect("the detached project's chats remain reachable");
    assert!(standalone.legacy);
    assert_eq!(
        db.project_session_ids(&canonical_second).unwrap(),
        [session.id]
    );
}

#[test]
fn project_group_update_switches_the_primary_root() {
    let dir = tempfile::tempdir().unwrap();
    let primary = dir.path().join("primary");
    let member = dir.path().join("member");
    let other = dir.path().join("other");
    std::fs::create_dir_all(&primary).unwrap();
    std::fs::create_dir_all(&member).unwrap();
    std::fs::create_dir_all(&other).unwrap();
    let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();
    let group = db
        .create_project_group(
            "Switchable",
            &[
                primary.to_string_lossy().into(),
                member.to_string_lossy().into(),
                other.to_string_lossy().into(),
            ],
        )
        .unwrap();
    let canonical_primary = crate::db::canonical_project_path(&primary.to_string_lossy()).unwrap();
    let canonical_member = crate::db::canonical_project_path(&member.to_string_lossy()).unwrap();
    let canonical_other = crate::db::canonical_project_path(&other.to_string_lossy()).unwrap();
    let all_folders = || {
        vec![
            primary.to_string_lossy().into_owned(),
            member.to_string_lossy().into_owned(),
            other.to_string_lossy().into_owned(),
        ]
    };

    // Naming another selected folder promotes it and keeps it first.
    let switched = db
        .update_project_group(
            &group.id,
            "Switchable",
            &all_folders(),
            Some(&canonical_member),
        )
        .unwrap();
    assert_eq!(switched.primary_path, canonical_member);
    assert_eq!(
        switched
            .roots
            .iter()
            .map(|root| root.path.as_str())
            .collect::<Vec<_>>(),
        [
            canonical_member.as_str(),
            canonical_primary.as_str(),
            canonical_other.as_str()
        ]
    );
    assert_eq!(
        switched
            .roots
            .iter()
            .map(|root| root.position)
            .collect::<Vec<_>>(),
        [0, 1, 2]
    );
    // The former primary becomes an ordinary member root.
    assert!(switched
        .roots
        .iter()
        .skip(1)
        .any(|root| root.path == canonical_primary));
    // The switch survives reloading the stored record.
    let reloaded = db
        .list_project_groups()
        .unwrap()
        .into_iter()
        .find(|candidate| candidate.id == group.id)
        .unwrap();
    assert_eq!(reloaded.primary_path, canonical_member);

    // A primary outside the selected folders is refused.
    assert!(db
        .update_project_group(
            &group.id,
            "Switchable",
            std::slice::from_ref(&canonical_primary),
            Some(&canonical_member),
        )
        .unwrap_err()
        .to_string()
        .contains("must be one of the group folders"));
    // Omitting the primary still refuses dropping the stored one.
    assert!(db
        .update_project_group(
            &group.id,
            "Switchable",
            std::slice::from_ref(&canonical_primary),
            None
        )
        .unwrap_err()
        .to_string()
        .contains("primary folder"));
    // The refused calls leave the stored switch in place.
    let unchanged = db
        .list_project_groups()
        .unwrap()
        .into_iter()
        .find(|candidate| candidate.id == group.id)
        .unwrap();
    assert_eq!(unchanged.primary_path, canonical_member);
}

#[test]
fn single_root_replacement_preserves_legacy_project_and_its_owned_data() {
    let dir = tempfile::tempdir().unwrap();
    let old = dir.path().join("old");
    let new = dir.path().join("new");
    std::fs::create_dir(&old).unwrap();
    let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();
    let source = db.ensure_project(&old.to_string_lossy(), false).unwrap();
    db.conn()
        .execute(
            "INSERT INTO sessions(id,project_id,created_at,updated_at) VALUES('session',?1,1,1)",
            [source],
        )
        .unwrap();
    db.conn()
        .execute(
            "INSERT INTO scheduled_tasks(id,title,prompt,project_id,config_json,created_at,updated_at)
             VALUES('task','Task','Prompt',?1,json_object('workspacePath',?2),1,1)",
            params![
                source,
                format!(
                    "{}/",
                    crate::db::canonical_project_path(&old.to_string_lossy()).unwrap()
                )
            ],
        )
        .unwrap();
    db.set_project_memory(&old.to_string_lossy(), "Keep this context")
        .unwrap();
    let group = db
        .list_project_groups()
        .unwrap()
        .into_iter()
        .find(|group| group.legacy)
        .unwrap();

    std::fs::rename(&old, &new).unwrap();
    let shadow = db.ensure_project(&new.to_string_lossy(), false).unwrap();
    db.kv_set(
        "app",
        "currentProjectId",
        &serde_json::json!(shadow.to_string()),
    )
    .unwrap();
    let updated = db
        .update_project_group(
            &group.id,
            "Relocated",
            &[new.to_string_lossy().into_owned()],
            Some(&new.to_string_lossy()),
        )
        .unwrap();

    let canonical_new = crate::db::canonical_project_path(&new.to_string_lossy()).unwrap();
    assert_eq!(updated.primary_path, canonical_new);
    assert_eq!(
        db.project_path(source).unwrap().as_deref(),
        Some(canonical_new.as_str())
    );
    assert!(db.get_project(shadow).unwrap().is_none());
    assert_eq!(db.list_projects().unwrap().len(), 1);
    let owner: i64 = db
        .conn()
        .query_row(
            "SELECT project_id FROM sessions WHERE id='session'",
            [],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(owner, source);
    let task_owner: i64 = db
        .conn()
        .query_row(
            "SELECT project_id FROM scheduled_tasks WHERE id='task'",
            [],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(task_owner, source);
    let task_workspace: String = db
        .conn()
        .query_row(
            "SELECT json_extract(config_json,'$.workspacePath') FROM scheduled_tasks WHERE id='task'",
            [],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(task_workspace, canonical_new);
    assert_eq!(
        db.get_project_memory(&new.to_string_lossy())
            .unwrap()
            .content,
        "Keep this context"
    );
    assert!(db
        .get_project_memory(&old.to_string_lossy())
        .unwrap()
        .content
        .is_empty());
    assert_eq!(
        db.kv_get("app", "currentProjectId").unwrap(),
        Some(serde_json::json!(source))
    );
}

#[test]
fn single_root_replacement_refuses_a_non_empty_target_project() {
    let dir = tempfile::tempdir().unwrap();
    let old = dir.path().join("old");
    let new = dir.path().join("new");
    std::fs::create_dir(&old).unwrap();
    std::fs::create_dir(&new).unwrap();
    let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();
    let group = db
        .create_project_group("Source", &[old.to_string_lossy().into_owned()])
        .unwrap();
    let source = db.ensure_project(&old.to_string_lossy(), false).unwrap();
    let target = db.ensure_project(&new.to_string_lossy(), false).unwrap();
    db.conn()
        .execute(
            "INSERT INTO sessions(id,project_id,created_at,updated_at) VALUES('source-session',?1,1,1)",
            [source],
        )
        .unwrap();
    db.conn()
        .execute(
            "INSERT INTO scheduled_tasks(id,title,prompt,config_json,created_at,updated_at)
             VALUES('target-task','Target','Prompt',json_object('workspacePath',?1),1,1)",
            [format!(
                "{}/",
                crate::db::canonical_project_path(&new.to_string_lossy()).unwrap()
            )],
        )
        .unwrap();
    std::fs::remove_dir(&old).unwrap();

    let error = db
        .update_project_group(
            &group.id,
            "Source",
            &[new.to_string_lossy().into_owned()],
            Some(&new.to_string_lossy()),
        )
        .unwrap_err();
    assert!(error.to_string().contains("non-empty project"));
    assert_eq!(
        db.project_path(source).unwrap(),
        Some(group.primary_path.clone())
    );
    assert_eq!(
        db.project_path(target).unwrap(),
        Some(crate::db::canonical_project_path(&new.to_string_lossy()).unwrap())
    );
    assert_eq!(db.list_projects().unwrap().len(), 2);
    assert_eq!(
        db.list_project_groups()
            .unwrap()
            .into_iter()
            .find(|candidate| candidate.id == group.id)
            .unwrap()
            .primary_path,
        group.primary_path
    );
}

#[test]
fn single_root_replacement_refuses_orphaned_target_memory() {
    let dir = tempfile::tempdir().unwrap();
    let old = dir.path().join("old");
    let new = dir.path().join("new");
    std::fs::create_dir(&old).unwrap();
    std::fs::create_dir(&new).unwrap();
    let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();
    let group = db
        .create_project_group("Source", &[old.to_string_lossy().into_owned()])
        .unwrap();
    let source = db.ensure_project(&old.to_string_lossy(), false).unwrap();
    let canonical_new = crate::db::canonical_project_path(&new.to_string_lossy()).unwrap();
    db.kv_set(
        "projectMemory",
        &canonical_new,
        &serde_json::json!({"content":"Independent memory"}),
    )
    .unwrap();
    std::fs::remove_dir(&old).unwrap();

    assert!(db
        .update_project_group(
            &group.id,
            "Source",
            &[new.to_string_lossy().into_owned()],
            Some(&new.to_string_lossy()),
        )
        .unwrap_err()
        .to_string()
        .contains("non-empty project"));
    assert_eq!(db.project_path(source).unwrap(), Some(group.primary_path));
    assert_eq!(
        db.get_project_memory(&new.to_string_lossy())
            .unwrap()
            .content,
        "Independent memory"
    );
}

#[test]
fn single_root_replacement_rolls_back_an_empty_target_delete_on_failure() {
    let dir = tempfile::tempdir().unwrap();
    let old = dir.path().join("old");
    let new = dir.path().join("new");
    std::fs::create_dir(&old).unwrap();
    let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();
    let group = db
        .create_project_group("Source", &[old.to_string_lossy().into_owned()])
        .unwrap();
    let source = db.ensure_project(&old.to_string_lossy(), false).unwrap();
    std::fs::rename(&old, &new).unwrap();
    let target = db.ensure_project(&new.to_string_lossy(), false).unwrap();
    db.conn()
        .execute_batch(&format!(
            "CREATE TRIGGER reject_relocation BEFORE UPDATE OF path ON projects
             WHEN OLD.id={source} BEGIN SELECT RAISE(ABORT,'blocked'); END;"
        ))
        .unwrap();

    assert!(db
        .update_project_group(
            &group.id,
            "Source",
            &[new.to_string_lossy().into_owned()],
            Some(&new.to_string_lossy()),
        )
        .is_err());
    assert!(db.get_project(target).unwrap().is_some());
    assert_eq!(db.project_path(source).unwrap(), Some(group.primary_path));
}

fn create_project_chat(db: &Database, path: &std::path::Path) -> String {
    crate::sessions::create_session(
        db,
        Some("Existing chat".into()),
        Some("agent".into()),
        None,
        None,
        Some(path.to_string_lossy().into_owned()),
    )
    .unwrap()
    .id
}

fn session_project_path(db: &Database, id: &str) -> Option<String> {
    crate::sessions::session_summary(db, id)
        .unwrap()
        .unwrap()
        .project_path
}

#[test]
fn single_root_replacement_keeps_sessions_when_the_old_folder_still_exists() {
    // Swapping an existing folder for an unrelated one is not a relocation:
    // the old project keeps its chats and stays reachable on its own.
    let dir = tempfile::tempdir().unwrap();
    let old = dir.path().join("old");
    let other = dir.path().join("other");
    std::fs::create_dir(&old).unwrap();
    std::fs::create_dir(&other).unwrap();
    let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();
    let group = db
        .create_project_group("Swap", &[old.to_string_lossy().into_owned()])
        .unwrap();
    let source = db.ensure_project(&old.to_string_lossy(), false).unwrap();
    let session = create_project_chat(&db, &old);
    db.set_project_memory(&old.to_string_lossy(), "Old context")
        .unwrap();
    let canonical_old = group.primary_path.clone();
    let canonical_other = crate::db::canonical_project_path(&other.to_string_lossy()).unwrap();

    let updated = db
        .update_project_group(
            &group.id,
            "Swap",
            &[other.to_string_lossy().into_owned()],
            Some(&other.to_string_lossy()),
        )
        .unwrap();

    assert_eq!(updated.primary_path, canonical_other);
    assert_eq!(
        db.project_path(source).unwrap().as_deref(),
        Some(canonical_old.as_str())
    );
    assert_eq!(
        session_project_path(&db, &session).as_deref(),
        Some(canonical_old.as_str())
    );
    assert_eq!(db.project_session_ids(&canonical_old).unwrap(), [session]);
    assert!(db.project_session_ids(&canonical_other).unwrap().is_empty());
    assert_eq!(
        db.get_project_memory(&old.to_string_lossy())
            .unwrap()
            .content,
        "Old context"
    );
    assert_eq!(db.list_projects().unwrap().len(), 2);
    assert!(db
        .list_project_groups()
        .unwrap()
        .iter()
        .any(|candidate| candidate.legacy && candidate.primary_path == canonical_old));
}

#[test]
fn legacy_single_root_replacement_keeps_sessions_when_the_old_folder_still_exists() {
    let dir = tempfile::tempdir().unwrap();
    let old = dir.path().join("old");
    let other = dir.path().join("other");
    std::fs::create_dir(&old).unwrap();
    std::fs::create_dir(&other).unwrap();
    let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();
    let source = db.ensure_project(&old.to_string_lossy(), false).unwrap();
    let session = create_project_chat(&db, &old);
    let group = db
        .list_project_groups()
        .unwrap()
        .into_iter()
        .find(|group| group.legacy)
        .unwrap();
    let canonical_old = group.primary_path.clone();

    let updated = db
        .update_project_group(
            &group.id,
            "Swap",
            &[other.to_string_lossy().into_owned()],
            Some(&other.to_string_lossy()),
        )
        .unwrap();

    // Pre-relocation behavior: the legacy record is returned unchanged.
    assert_eq!(updated.primary_path, canonical_old);
    assert_eq!(
        db.project_path(source).unwrap().as_deref(),
        Some(canonical_old.as_str())
    );
    assert_eq!(
        session_project_path(&db, &session).as_deref(),
        Some(canonical_old.as_str())
    );
    assert_eq!(db.list_projects().unwrap().len(), 2);
}

#[test]
fn two_step_stale_root_repair_relocates_the_stale_project() {
    // #1869 + #2469: the user first saves the replacement next to the stale
    // root, then saves again with only the replacement.
    let dir = tempfile::tempdir().unwrap();
    let old = dir.path().join("old");
    let new = dir.path().join("new");
    std::fs::create_dir(&old).unwrap();
    let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();
    let group = db
        .create_project_group("Moved", &[old.to_string_lossy().into_owned()])
        .unwrap();
    let canonical_old = group.primary_path.clone();
    let source = db.ensure_project(&old.to_string_lossy(), false).unwrap();
    let session = create_project_chat(&db, &old);
    db.conn()
        .execute(
            "INSERT INTO scheduled_tasks(id,title,prompt,project_id,config_json,created_at,updated_at)
             VALUES('task','Task','Prompt',?1,json_object('workspacePath',?2),1,1)",
            params![source, canonical_old],
        )
        .unwrap();
    db.set_project_memory(&old.to_string_lossy(), "Keep this context")
        .unwrap();

    std::fs::rename(&old, &new).unwrap();
    let canonical_new = crate::db::canonical_project_path(&new.to_string_lossy()).unwrap();
    let first = db
        .update_project_group(
            &group.id,
            "Moved",
            &[canonical_old.clone(), new.to_string_lossy().into_owned()],
            Some(&canonical_new),
        )
        .unwrap();
    assert_eq!(first.roots.len(), 2);
    let shadow = db.ensure_project(&canonical_new, false).unwrap();
    assert_ne!(shadow, source);

    let healed = db
        .update_project_group(
            &group.id,
            "Moved",
            &[new.to_string_lossy().into_owned()],
            Some(&canonical_new),
        )
        .unwrap();

    assert_eq!(healed.id, group.id);
    assert_eq!(healed.primary_path, canonical_new);
    assert_eq!(healed.roots.len(), 1);
    assert!(!healed.detached_paths.contains(&canonical_old));
    assert_eq!(
        db.project_path(source).unwrap().as_deref(),
        Some(canonical_new.as_str())
    );
    assert!(db.get_project(shadow).unwrap().is_none());
    assert_eq!(db.list_projects().unwrap().len(), 1);
    assert_eq!(
        session_project_path(&db, &session).as_deref(),
        Some(canonical_new.as_str())
    );
    let task_workspace: String = db
        .conn()
        .query_row(
            "SELECT json_extract(config_json,'$.workspacePath') FROM scheduled_tasks WHERE id='task'",
            [],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(task_workspace, canonical_new);
    assert_eq!(
        db.get_project_memory(&canonical_new).unwrap().content,
        "Keep this context"
    );
    let groups = db.list_project_groups().unwrap();
    assert_eq!(groups.len(), 1);
    assert_eq!(groups[0].id, group.id);
}

#[test]
fn two_step_stale_root_repair_keeps_detach_when_the_replacement_has_chats() {
    // A replacement that already owns chats is never merged implicitly; the
    // stale root is detached exactly as before relocation existed.
    let dir = tempfile::tempdir().unwrap();
    let old = dir.path().join("old");
    let new = dir.path().join("new");
    std::fs::create_dir(&old).unwrap();
    std::fs::create_dir(&new).unwrap();
    let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();
    let group = db
        .create_project_group(
            "Pair",
            &[
                new.to_string_lossy().into_owned(),
                old.to_string_lossy().into_owned(),
            ],
        )
        .unwrap();
    let canonical_new = group.primary_path.clone();
    let canonical_old = crate::db::canonical_project_path(&old.to_string_lossy()).unwrap();
    let source = db.ensure_project(&old.to_string_lossy(), false).unwrap();
    let old_session = create_project_chat(&db, &old);
    let new_session = create_project_chat(&db, &new);
    std::fs::remove_dir(&old).unwrap();

    let updated = db
        .update_project_group(
            &group.id,
            "Pair",
            &[new.to_string_lossy().into_owned()],
            Some(&canonical_new),
        )
        .unwrap();
    assert_eq!(updated.roots.len(), 1);
    assert_eq!(
        db.project_path(source).unwrap().as_deref(),
        Some(canonical_old.as_str())
    );
    assert_eq!(
        session_project_path(&db, &old_session).as_deref(),
        Some(canonical_old.as_str())
    );
    assert_eq!(
        session_project_path(&db, &new_session).as_deref(),
        Some(canonical_new.as_str())
    );
    assert_eq!(db.list_projects().unwrap().len(), 2);
}

#[test]
fn removing_an_existing_root_with_chats_still_detaches_it() {
    let dir = tempfile::tempdir().unwrap();
    let kept = dir.path().join("kept");
    let removed = dir.path().join("removed");
    std::fs::create_dir(&kept).unwrap();
    std::fs::create_dir(&removed).unwrap();
    let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();
    let group = db
        .create_project_group(
            "Pair",
            &[
                kept.to_string_lossy().into_owned(),
                removed.to_string_lossy().into_owned(),
            ],
        )
        .unwrap();
    let canonical_kept = group.primary_path.clone();
    let canonical_removed = crate::db::canonical_project_path(&removed.to_string_lossy()).unwrap();
    let source = db
        .ensure_project(&removed.to_string_lossy(), false)
        .unwrap();
    let session = create_project_chat(&db, &removed);

    let updated = db
        .update_project_group(
            &group.id,
            "Pair",
            &[kept.to_string_lossy().into_owned()],
            None,
        )
        .unwrap();
    assert_eq!(updated.roots.len(), 1);
    assert_eq!(updated.primary_path, canonical_kept);
    assert!(!updated.detached_paths.contains(&canonical_removed));
    assert_eq!(
        db.project_path(source).unwrap().as_deref(),
        Some(canonical_removed.as_str())
    );
    assert_eq!(
        session_project_path(&db, &session).as_deref(),
        Some(canonical_removed.as_str())
    );
    assert!(db
        .list_project_groups()
        .unwrap()
        .iter()
        .any(|candidate| candidate.legacy && candidate.primary_path == canonical_removed));
}

#[test]
fn project_group_update_allows_a_root_renamed_away_externally() {
    // #1869: when a group folder is renamed (or unmounted) outside the app,
    // editing the group must still be able to keep the stale root while its
    // replacement is added, and must be able to drop the stale root afterwards.
    let dir = tempfile::tempdir().unwrap();
    let stale = dir.path().join("stale");
    let replacement = dir.path().join("replacement");
    std::fs::create_dir_all(&stale).unwrap();
    std::fs::create_dir_all(&replacement).unwrap();
    let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();
    let group = db
        .create_project_group("Renamed away", &[stale.to_string_lossy().into()])
        .unwrap();
    let canonical_stale = crate::db::canonical_project_path(&stale.to_string_lossy()).unwrap();
    let canonical_replacement =
        crate::db::canonical_project_path(&replacement.to_string_lossy()).unwrap();

    // The folder is renamed externally after the group stored it.
    std::fs::remove_dir_all(&stale).unwrap();

    // Keeping the stale root while adding and promoting its replacement must
    // not be blocked by the on-disk directory check. The submission uses the
    // stored spelling, exactly as the edit dialog echoes the root back.
    let updated = db
        .update_project_group(
            &group.id,
            "Renamed away",
            &[
                replacement.to_string_lossy().into(),
                canonical_stale.clone(),
            ],
            Some(&canonical_replacement),
        )
        .expect("a root the group already owns may be missing on disk");
    assert_eq!(updated.primary_path, canonical_replacement);
    assert_eq!(updated.roots.len(), 2);
    assert_eq!(updated.roots[0].path, canonical_replacement);
    assert_eq!(updated.roots[1].path, canonical_stale);

    // A later edit can drop the stale root entirely, healing the group.
    let healed = db
        .update_project_group(
            &group.id,
            "Renamed away",
            &[replacement.to_string_lossy().into()],
            Some(&canonical_replacement),
        )
        .expect("the stale root can be dropped from the group");
    assert_eq!(healed.roots.len(), 1);
    assert_eq!(healed.roots[0].path, canonical_replacement);
    assert!(healed.detached_paths.contains(&canonical_stale));

    // A folder that is new to the group must still exist on disk.
    let missing = dir.path().join("missing");
    assert!(db
        .update_project_group(
            &group.id,
            "Renamed away",
            &[
                replacement.to_string_lossy().into(),
                missing.to_string_lossy().into(),
            ],
            Some(&canonical_replacement),
        )
        .unwrap_err()
        .to_string()
        .contains("not a directory"));
}

#[test]
fn remove_project_from_group_detaches_even_with_chats_and_may_move_primary() {
    let dir = tempfile::tempdir().unwrap();
    let primary = dir.path().join("primary");
    let first = dir.path().join("first");
    let second = dir.path().join("second");
    std::fs::create_dir_all(&primary).unwrap();
    std::fs::create_dir_all(&first).unwrap();
    std::fs::create_dir_all(&second).unwrap();
    let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();
    let group = db
        .create_project_group(
            "Deadlock",
            &[
                primary.to_string_lossy().into(),
                first.to_string_lossy().into(),
                second.to_string_lossy().into(),
            ],
        )
        .unwrap();
    // The project has chats: `update_project_group` refuses to detach it, so
    // `projects.remove` must not depend on that path (#1358).
    let session = crate::sessions::create_session(
        &db,
        Some("Blocked chat".into()),
        Some("agent".into()),
        None,
        None,
        Some(primary.to_string_lossy().into_owned()),
    )
    .unwrap();
    let project_session_ids = db.project_session_ids(&group.primary_path).unwrap();
    assert_eq!(
        project_session_ids.as_slice(),
        std::slice::from_ref(&session.id)
    );

    // Removing the primary moves the role to the first remaining root and
    // keeps the other root in the group.
    let after_primary = db
        .remove_project_from_group(&group.id, &group.primary_path)
        .unwrap()
        .expect("group survives removing its primary");
    let canonical_first = crate::db::canonical_project_path(&first.to_string_lossy()).unwrap();
    let canonical_second = crate::db::canonical_project_path(&second.to_string_lossy()).unwrap();
    assert_eq!(after_primary.primary_path, canonical_first);
    assert_eq!(after_primary.roots.len(), 2);
    assert_eq!(after_primary.roots[0].path, canonical_first);

    // Removing a non-primary root keeps the primary in place.
    let after_second = db
        .remove_project_from_group(&group.id, &canonical_second)
        .unwrap()
        .unwrap();
    assert_eq!(after_second.primary_path, canonical_first);
    assert_eq!(after_second.roots.len(), 1);

    // Removing the last root deletes the group record.
    let gone = db
        .remove_project_from_group(&group.id, &canonical_first)
        .unwrap();
    assert!(gone.is_none());
    assert!(!db
        .list_project_groups()
        .unwrap()
        .iter()
        .any(|candidate| candidate.id == group.id));
    // The chats of removed roots stay reachable for the caller's bulk delete.
    assert_eq!(
        db.project_session_ids(&group.primary_path).unwrap(),
        [session.id]
    );
}

#[test]
fn editing_a_legacy_project_with_an_extra_folder_upgrades_it_to_a_group() {
    let dir = tempfile::tempdir().unwrap();
    let primary = dir.path().join("primary");
    let extra = dir.path().join("extra");
    std::fs::create_dir_all(&primary).unwrap();
    std::fs::create_dir_all(&extra).unwrap();
    let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();
    db.ensure_project(&primary.to_string_lossy(), false)
        .unwrap();
    db.set_project_memory(&primary.to_string_lossy(), "Remember this.")
        .unwrap();
    let legacy = db.list_project_groups().unwrap().pop().unwrap();
    db.set_project_memory(&extra.to_string_lossy(), "Remember the extra root too.")
        .unwrap();
    assert!(legacy.legacy);

    let upgraded = db
        .update_project_group(
            &legacy.id,
            "Upgraded",
            &[
                primary.to_string_lossy().into(),
                extra.to_string_lossy().into(),
            ],
            None,
        )
        .unwrap();
    assert!(!upgraded.legacy);
    let memory = db.get_project_group_memory(&upgraded.id).unwrap();
    assert!(memory.content.contains("Remember this."));
    assert!(memory.content.contains("Remember the extra root too."));
    assert_eq!(db.list_project_groups().unwrap().len(), 1);
}

#[test]
fn old_path_projects_are_legacy_single_root_groups() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().join("legacy");
    std::fs::create_dir_all(&root).unwrap();
    let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();
    db.ensure_project(&root.to_string_lossy(), false).unwrap();

    let groups = db.list_project_groups().unwrap();
    assert_eq!(groups.len(), 1);
    assert!(groups[0].legacy);
    assert_eq!(groups[0].roots.len(), 1);
    assert!(db
        .project_group_context_for_path(&root.to_string_lossy())
        .unwrap()
        .is_none());
}

#[test]
fn ensure_project_upserts_by_path() {
    let dir = tempfile::tempdir().unwrap();
    let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();
    let a = db.ensure_project("/tmp/demo", true).unwrap();
    let b = db.ensure_project("/tmp/demo/", false).unwrap();
    assert_eq!(a, b);
    assert_eq!(db.project_path(a).unwrap().as_deref(), Some("/tmp/demo"));
    let projects = db.list_projects().unwrap();
    assert_eq!(projects.len(), 1);
    assert_eq!(projects[0].path, "/tmp/demo");
    assert_eq!(projects[0].name, "demo");

    let windows = db.ensure_project("C:\\work\\project\\", false).unwrap();
    assert_eq!(
        db.project_path(windows).unwrap().as_deref(),
        Some("C:/work/project")
    );
}

#[test]
fn list_projects_propagates_row_decode_errors() {
    let dir = tempfile::tempdir().unwrap();
    let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();
    db.conn()
        .execute(
            "INSERT INTO projects
                    (path, name, pinned, created_at, last_opened_at)
                 VALUES ('/tmp/broken', 'broken', 'not-a-number', 1, 1)",
            [],
        )
        .unwrap();

    assert!(db.list_projects().is_err());
}

#[cfg(unix)]
#[test]
fn ensure_project_dedupes_symlinked_spellings() {
    let dir = tempfile::tempdir().unwrap();
    let real = dir.path().join("real-project");
    std::fs::create_dir_all(&real).unwrap();
    let link = dir.path().join("link-project");
    std::os::unix::fs::symlink(&real, &link).unwrap();
    let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();
    let a = db.ensure_project(&real.to_string_lossy(), true).unwrap();
    let b = db.ensure_project(&link.to_string_lossy(), true).unwrap();
    assert_eq!(a, b, "symlinked path spellings must share one project row");
    assert_eq!(db.list_projects().unwrap().len(), 1);
}

#[test]
fn normalize_project_path_strips_extended_length_prefix() {
    // Forward-slash variant stored by older DB versions on Windows
    assert_eq!(
        normalize_project_path("//?/C:/Users/mi/project"),
        Some("C:/Users/mi/project".to_string()),
    );
    assert_eq!(
        normalize_project_path("//?/D:/work/app"),
        Some("D:/work/app".to_string()),
    );
    // Backslash variant coming directly from canonicalize on Windows
    assert_eq!(
        normalize_project_path(r"\\?\C:\Users\mi\project"),
        Some("C:/Users/mi/project".to_string()),
    );
    // Non-drive UNC paths should NOT be stripped
    assert_eq!(
        normalize_project_path("//?/UNC/server/share"),
        Some("//?/UNC/server/share".to_string()),
    );
    // Normal paths remain unchanged
    assert_eq!(
        normalize_project_path("C:/Users/mi/project"),
        Some("C:/Users/mi/project".to_string()),
    );
    assert_eq!(
        normalize_project_path("/home/user/project"),
        Some("/home/user/project".to_string()),
    );
}

/// The v16 → v17 step runs after the v15 → v16 step in the same launch, so a
/// file one version behind must land on the current version with both changes
/// applied rather than stopping at the version the first step stamps.
#[test]
fn a_v16_file_gains_the_provider_owner_column() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("pi.sqlite");
    let provider_id;
    {
        let db = Database::open(&path).unwrap();
        provider_id = db
            .conn()
            .query_row(
                "INSERT INTO providers (id, name, created_at, updated_at)
                 VALUES ('p-user', 'Mine', 1, 1) RETURNING id",
                [],
                |row| row.get::<_, String>(0),
            )
            .unwrap();
        // Back to a file that predates the ownership column. SQLite will not
        // drop a column an index still references, so the index goes first.
        db.conn()
            .execute_batch(
                "DROP INDEX idx_providers_owner;
                 ALTER TABLE providers DROP COLUMN owner_plugin_id;
                 PRAGMA user_version=16;",
            )
            .unwrap();
    }
    let db = Database::open(&path).unwrap();
    assert_eq!(
        db.conn()
            .query_row("PRAGMA user_version", [], |row| row.get::<_, i64>(0))
            .unwrap(),
        SCHEMA_VERSION
    );
    assert!(migration_backup_path(&path, 16).exists());
    // The existing row survives and stays user-owned.
    let owner: Option<String> = db
        .conn()
        .query_row(
            "SELECT owner_plugin_id FROM providers WHERE id = ?1",
            params![provider_id],
            |row| row.get(0),
        )
        .unwrap();
    assert!(owner.is_none());
}

#[test]
fn migrates_v21_to_v22_replaces_session_index() {
    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("pi.sqlite");
    {
        // Open a fresh database which creates the latest schema
        let db = Database::open(&db_path).unwrap();
        db.conn()
            .execute_batch(
                "
            DROP INDEX IF EXISTS idx_sessions_updated_id;
            CREATE INDEX idx_sessions_updated ON sessions(updated_at DESC);
            PRAGMA user_version = 21;
            ",
            )
            .unwrap();
    }

    let db = Database::open(&db_path).unwrap();

    let version: i64 = db
        .conn()
        .query_row("PRAGMA user_version", [], |r| r.get(0))
        .unwrap();
    assert_eq!(version, crate::db::SCHEMA_VERSION);

    let old_index_exists: bool = db.conn().query_row(
        "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='index' AND name='idx_sessions_updated')",
        [],
        |r| r.get(0)
    ).unwrap();
    assert!(!old_index_exists, "idx_sessions_updated should be dropped");

    let new_index_exists: bool = db.conn().query_row(
        "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='index' AND name='idx_sessions_updated_id')",
        [],
        |r| r.get(0)
    ).unwrap();
    assert!(
        new_index_exists,
        "idx_sessions_updated_id should be created"
    );
}

#[test]
fn v24_model_discovery_upgrade_preserves_rows_and_reopens() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("pi.sqlite");
    {
        let db = Database::open(&path).unwrap();
        db.conn().execute_batch("ALTER TABLE models DROP COLUMN discovery_state;
            INSERT INTO providers(id, name, type, protocol, auth_kind, config_json, created_at, updated_at)
            VALUES ('fixture', 'Fixture', 'openai_compatible', 'openai_compatible', 'none', '{}', 1, 1);
            INSERT INTO models(provider_id, model_id, display_name, source, updated_at)
            VALUES ('fixture', 'known', 'Known', 'discovered', 1), ('fixture', 'manual', 'Manual', 'user', 1);
            PRAGMA user_version = 24;").unwrap();
    }
    let db = Database::open(&path).unwrap();
    assert_eq!(schema_version(db.conn()), SCHEMA_VERSION);
    assert!(migration_backup_path(&path, 24).exists());
    let models = crate::providers::list_models(&db, Some("fixture")).unwrap();
    assert_eq!(models.len(), 2);
    assert_eq!(models[0].discovery_state.as_deref(), Some("published"));
    assert!(models[1].discovery_state.is_none());
    drop(db);
    let db = Database::open(&path).unwrap();
    assert_eq!(
        crate::providers::list_models(&db, Some("fixture")).unwrap(),
        models
    );
}