Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(mods): retire legacy Goal turn snapshot triggers
new-Beginner733b753883e5
diff --git a/crates/host-core/src/db.rs b/crates/host-core/src/db.rsindex 08255ca97..74e394237 100644--- a/crates/host-core/src/db.rs+++ b/crates/host-core/src/db.rs@@ -7,7 +7,7 @@ pub(crate) use serde_json::Value;pub(crate) use std::path::{Path, PathBuf};/// Current SQLite schema version.-pub const SCHEMA_VERSION: i64 = 32;+pub const SCHEMA_VERSION: i64 = 33;/// Absolute approval deadline for a newly submitted Plan or Goal proposal.pub const PLAN_APPROVAL_TIMEOUT_MS: i64 = 30 * 60 * 1000;@@ -16,6 +16,7 @@ pub const PLAN_APPROVAL_TIMEOUT_MS: i64 = 30 * 60 * 1000;pub const NOTIFICATION_KEEP: i64 = 200;mod completion_report_migration;+mod legacy_goal_migration;mod migrations;mod mode_run_elapsed_migration;mod mode_runs_migration;@@ -26,6 +27,7 @@ mod project_groups;mod project_path_migration;mod repositories;mod schema;+mod schema_rebuild;mod session_collaboration_migration;mod session_fast_mode_migration;mod session_mode_migration;diff --git a/crates/host-core/src/db/completion_report_migration_tests.rs b/crates/host-core/src/db/completion_report_migration_tests.rsindex f59e387d0..1c79e4800 100644--- a/crates/host-core/src/db/completion_report_migration_tests.rs+++ b/crates/host-core/src/db/completion_report_migration_tests.rs@@ -74,7 +74,7 @@ fn completion_report_migration_populated_30_preserves_all_data_and_pre_migrationdrop(before);let db = Database::open(&path).unwrap();assert_eq!(version(db.conn()), SCHEMA_VERSION);- assert_eq!(SCHEMA_VERSION, 32);+ assert_eq!(SCHEMA_VERSION, 33);assert!(has_report(db.conn()));assert_eq!(rows(db.conn(), LEGACY_RUN), old_run);assert_eq!(rows(db.conn(), "SELECT * FROM mode_gate_results"), gates);diff --git a/crates/host-core/src/db/legacy_goal_migration.rs b/crates/host-core/src/db/legacy_goal_migration.rsnew file mode 100644index 000000000..7429734f4--- /dev/null+++ b/crates/host-core/src/db/legacy_goal_migration.rs@@ -0,0 +1,25 @@+use super::{anyhow, create_migration_backup, Connection, Context, Path, Result};++/// Retire the withdrawn independent Goal writer without deleting its history.+/// That candidate also used version 32, so version alone cannot prove that+/// either the sessions mode CHECK or its turn snapshot trigger was repaired.+pub(super) fn migrate(conn: &Connection, path: &Path) -> Result<()> {+ let backup = create_migration_backup(conn, path, 32)?;+ super::schema_rebuild::with_table_rebuild(conn, || {+ let tx = conn.unchecked_transaction()?;+ tx.execute_batch("DROP TRIGGER IF EXISTS turn_execution_snapshot;")?;+ super::session_mode_migration::widen_session_modes(&tx)?;+ if tx.prepare("PRAGMA foreign_key_check")?.exists([])? {+ return Err(anyhow!(+ "foreign key check failed during legacy Goal migration"+ ));+ }+ tx.pragma_update(None, "user_version", 33i64)?;+ tx.commit().with_context(|| {+ format!(+ "commit schema v32 to v33 legacy Goal migration; backup {} remains",+ backup.display()+ )+ })+ })+}diff --git a/crates/host-core/src/db/mode_runs_migration.rs b/crates/host-core/src/db/mode_runs_migration.rsindex 29da0ff03..06fd375fe 100644--- a/crates/host-core/src/db/mode_runs_migration.rs+++ b/crates/host-core/src/db/mode_runs_migration.rs@@ -157,7 +157,7 @@ mod tests {let db = Database::open(&path).unwrap();assert_eq!(version(db.conn()), SCHEMA_VERSION);- assert_eq!(SCHEMA_VERSION, 32);+ assert_eq!(SCHEMA_VERSION, 33);assert!(has_column(db.conn(), "sessions", "mode_snapshot_hash"));for table in ["mode_snapshots", "mode_runs", "mode_gate_results"] {assert!(has_table(db.conn(), table), "{table}");diff --git a/crates/host-core/src/db/repositories.rs b/crates/host-core/src/db/repositories.rsindex 6093b7d39..48515cf44 100644--- a/crates/host-core/src/db/repositories.rs+++ b/crates/host-core/src/db/repositories.rs@@ -224,6 +224,7 @@ impl Database {29 => {}30 => {}31 => {}+ 32 => {}legacy @ 1..=6 => {let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);");drop(conn);@@ -307,6 +308,10 @@ impl Database {if version == 31 {super::session_mode_migration::migrate(&conn, path)?;}+ let version: i64 = conn.query_row("PRAGMA user_version", [], |r| r.get(0))?;+ if version == 32 {+ super::legacy_goal_migration::migrate(&conn, path)?;+ }let db = Self { conn, data_dir };db.boot_maintenance()?;crate::session_collaboration::recover(&db)?;diff --git a/crates/host-core/src/db/schema_rebuild.rs b/crates/host-core/src/db/schema_rebuild.rsnew file mode 100644index 000000000..e6eb75832--- /dev/null+++ b/crates/host-core/src/db/schema_rebuild.rs@@ -0,0 +1,23 @@+use super::{Connection, Context, Result};++/// Keep dependent views, triggers and child FK targets stable during table+/// replacement, then restore both connection settings on every exit path.+pub(super) fn with_table_rebuild(+ conn: &Connection,+ action: impl FnOnce() -> Result<()>,+) -> Result<()> {+ let foreign_keys: bool = conn.pragma_query_value(None, "foreign_keys", |row| row.get(0))?;+ let legacy_alter_table: bool =+ conn.pragma_query_value(None, "legacy_alter_table", |row| row.get(0))?;+ conn.pragma_update(None, "foreign_keys", false)?;+ let result = (|| {+ conn.pragma_update(None, "legacy_alter_table", true)?;+ action()+ })();+ // Attempt both restores even when migration or the other restore fails.+ let restore_alter = conn.pragma_update(None, "legacy_alter_table", legacy_alter_table);+ let restore_keys = conn.pragma_update(None, "foreign_keys", foreign_keys);+ restore_alter.context("restore legacy alter table after schema rebuild")?;+ restore_keys.context("restore foreign keys after schema rebuild")?;+ result+}diff --git a/crates/host-core/src/db/session_mode_migration.rs b/crates/host-core/src/db/session_mode_migration.rsindex 24952b793..0b21a34ca 100644--- a/crates/host-core/src/db/session_mode_migration.rs+++ b/crates/host-core/src/db/session_mode_migration.rs@@ -5,7 +5,7 @@ use rusqlite::Transaction;/// Existing databases can retain the builtin-only mode CHECK even though the/// current schema and Host accept validated custom mode ids. Remove only that/// legacy constraint, preserving the rest of the actual sessions definition.-fn widen_session_modes(tx: &Transaction<'_>) -> Result<()> {+pub(super) fn widen_session_modes(tx: &Transaction<'_>) -> Result<()> {let sql: String = tx.query_row("SELECT sql FROM sqlite_master WHERE type='table' AND name='sessions'",[],@@ -45,14 +45,7 @@ fn widen_session_modes(tx: &Transaction<'_>) -> Result<()> {pub(super) fn migrate(conn: &Connection, path: &Path) -> Result<()> {let backup = create_migration_backup(conn, path, 31)?;- let foreign_keys: bool = conn.pragma_query_value(None, "foreign_keys", |row| row.get(0))?;- let legacy_alter_table: bool =- conn.pragma_query_value(None, "legacy_alter_table", |row| row.get(0))?;- conn.pragma_update(None, "foreign_keys", false)?;- let result = (|| {- // Keep dependent views/triggers and child FK targets unchanged while- // sessions is briefly absent inside the transactional replacement.- conn.pragma_update(None, "legacy_alter_table", true)?;+ super::schema_rebuild::with_table_rebuild(conn, || {let tx = conn.unchecked_transaction()?;widen_session_modes(&tx)?;tx.pragma_update(None, "user_version", 32i64)?;@@ -62,13 +55,7 @@ pub(super) fn migrate(conn: &Connection, path: &Path) -> Result<()> {backup.display())})- })();- // Attempt both restores even when migration or the other restore fails.- let restore_alter = conn.pragma_update(None, "legacy_alter_table", legacy_alter_table);- let restore_keys = conn.pragma_update(None, "foreign_keys", foreign_keys);- restore_alter.context("restore legacy alter table after session mode migration")?;- restore_keys.context("restore foreign keys after session mode migration")?;- result+ })}#[cfg(test)]diff --git a/crates/host-core/src/mode_runs/elapsed_tests.rs b/crates/host-core/src/mode_runs/elapsed_tests.rsindex 1aecd14b9..e7694afd3 100644--- a/crates/host-core/src/mode_runs/elapsed_tests.rs+++ b/crates/host-core/src/mode_runs/elapsed_tests.rs@@ -307,7 +307,7 @@ fn elapsed_schema_29_upgrade_preserves_populated_runs_queue_and_backup() {.conn().query_row("PRAGMA user_version", [], |r| r.get(0)).unwrap();- assert_eq!(version, 32);+ assert_eq!(version, 33);assert_eq!(version, SCHEMA_VERSION);for state in LEGACY_STATES {let run = repository::owned(db.conn(), state, state).unwrap();diff --git a/crates/host-core/src/rpc/session_mode_migration_tests.rs b/crates/host-core/src/rpc/session_mode_migration_tests.rsindex e9b8a16b1..eda1122bc 100644--- a/crates/host-core/src/rpc/session_mode_migration_tests.rs+++ b/crates/host-core/src/rpc/session_mode_migration_tests.rs@@ -186,3 +186,276 @@ async fn custom_mode_selection_upgrades_older_mode_schemas() {assert_eq!(migrated, crate::db::SCHEMA_VERSION);}}++const LEGACY_GOAL_EXECUTION_SCHEMA: &str = r#"+CREATE TABLE session_goals(id TEXT PRIMARY KEY, payload BLOB NOT NULL);+CREATE TABLE goal_turns (+ turn_id TEXT PRIMARY KEY,+ goal_id TEXT NOT NULL REFERENCES session_goals(id) ON DELETE CASCADE,+ settled INTEGER NOT NULL DEFAULT 0 CHECK(settled IN (0,1)),+ interrupted INTEGER NOT NULL DEFAULT 0 CHECK(interrupted IN (0,1)),+ tokens INTEGER CHECK(tokens >= 0)+);+CREATE TABLE turn_execution (+ turn_id TEXT PRIMARY KEY REFERENCES turns(id) ON DELETE CASCADE,+ mode TEXT NOT NULL CHECK(mode IN ('agent','plan','goal')),+ goal_claim_id TEXT UNIQUE REFERENCES goal_turns(turn_id),+ provenance TEXT CHECK(provenance IN ('user-goal','goal-continuation')),+ CHECK((goal_claim_id IS NULL AND provenance IS NULL) OR+ (goal_claim_id IS NOT NULL AND provenance IS NOT NULL AND mode='goal'))+);+CREATE INDEX legacy_execution_mode ON turn_execution(mode);+CREATE TRIGGER turn_execution_snapshot AFTER INSERT ON turns+BEGIN+ INSERT INTO turn_execution(turn_id,mode)+ SELECT NEW.id,mode FROM sessions WHERE id=NEW.session_id;+END;+CREATE TABLE retained_turn_audit(turn_id TEXT NOT NULL);+CREATE TRIGGER retained_turn_audit AFTER INSERT ON turns+BEGIN+ INSERT INTO retained_turn_audit VALUES(NEW.id);+END;+INSERT INTO sessions(id,title,mode,created_at,updated_at)+VALUES('existing','Saved task','agent',1,1);+INSERT INTO session_goals VALUES('saved-goal',X'00FE');+INSERT INTO goal_turns VALUES('saved-claim','saved-goal',1,0,17);+INSERT INTO turns(id,session_id,status,started_at,ended_at)+VALUES('saved-turn','existing','completed',1,2);+UPDATE turn_execution SET mode='goal',goal_claim_id='saved-claim',+ provenance='goal-continuation' WHERE turn_id='saved-turn';+"#;++fn legacy_goal_database(path: &Path, version: i64, check: &str) {+ legacy_database(path, version, check);+ Connection::open(path)+ .unwrap()+ .execute_batch(LEGACY_GOAL_EXECUTION_SCHEMA)+ .unwrap();+}++fn legacy_goal_snapshot(conn: &Connection) -> (String, String, String, Vec<u8>, i64) {+ conn.query_row(+ "SELECT e.mode,e.goal_claim_id,e.provenance,g.payload,c.tokens+ FROM turn_execution e JOIN goal_turns c ON c.turn_id=e.goal_claim_id+ JOIN session_goals g ON g.id=c.goal_id WHERE e.turn_id='saved-turn'",+ [],+ |row| {+ Ok((+ row.get(0)?,+ row.get(1)?,+ row.get(2)?,+ row.get(3)?,+ row.get(4)?,+ ))+ },+ )+ .unwrap()+}++fn has_legacy_goal_trigger(conn: &Connection) -> bool {+ conn.query_row(+ "SELECT EXISTS(SELECT 1 FROM sqlite_master+ WHERE type='trigger' AND name='turn_execution_snapshot')",+ [],+ |row| row.get(0),+ )+ .unwrap()+}++#[tokio::test]+async fn legacy_goal_schema_allows_custom_mode_turns_without_losing_history() {+ for (version, check) in [(31, LEGACY_MODE_CHECK), (32, ""), (32, LEGACY_MODE_CHECK)] {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("pi.sqlite");+ legacy_goal_database(&path, version, check);+ let before = legacy_goal_snapshot(&Connection::open(&path).unwrap());+ let mut app = AppState::open(dir.path()).unwrap();+ app.handshook = true;+ let state = Arc::new(Mutex::new(app));+ let (tx, _rx) = mpsc::unbounded_channel();+ let selected = handle_request(+ state.clone(),+ "session.configure",+ json!({"id":"existing","mode":"goal-3","modeSnapshot":definition("goal-3")}),+ tx.clone(),+ )+ .await+ .expect("legacy schema 32 must allow custom mode selection too");+ assert_eq!(selected["session"]["mode"], "goal-3");+ let turn = handle_request(+ state.clone(),+ "session.beginTurn",+ json!({"sessionId":"existing"}),+ tx.clone(),+ )+ .await+ .expect("retired Goal triggers must not reject a custom-mode turn");+ let ended = handle_request(+ state.clone(),+ "session.endTurn",+ json!({"turnId":turn["turnId"],"status":"completed","createNotification":false}),+ tx,+ )+ .await+ .unwrap();+ assert_eq!(ended["ok"], true);+ {+ let app = state.lock().await;+ assert_eq!(legacy_goal_snapshot(app.db.conn()), before);+ assert!(!has_legacy_goal_trigger(app.db.conn()));+ let audit: i64 = app+ .db+ .conn()+ .query_row("SELECT count(*) FROM retained_turn_audit", [], |row| {+ row.get(0)+ })+ .unwrap();+ assert_eq!(audit, 2, "unrelated triggers must still run");+ let rows: i64 = app+ .db+ .conn()+ .query_row("SELECT count(*) FROM turn_execution", [], |row| row.get(0))+ .unwrap();+ assert_eq!(+ rows, 1,+ "the legacy ledger is retained but no longer populated"+ );+ }+ drop(state);+ let backup_path = dir.path().join("pi.sqlite.v32.bak");+ let backup = Connection::open(&backup_path).unwrap();+ assert!(has_legacy_goal_trigger(&backup));+ assert_eq!(legacy_goal_snapshot(&backup), before);+ assert_eq!(+ backup+ .pragma_query_value(None, "user_version", |row| row.get::<_, i64>(0))+ .unwrap(),+ 32+ );+ drop(backup);+ let backup_bytes = std::fs::read(&backup_path).unwrap();+ let reopened = Database::open(&path).unwrap();+ assert_eq!(+ reopened+ .conn()+ .pragma_query_value(None, "user_version", |row| row.get::<_, i64>(0))+ .unwrap(),+ 33+ );+ assert_eq!(legacy_goal_snapshot(reopened.conn()), before);+ assert!(!has_legacy_goal_trigger(reopened.conn()));+ assert_eq!(std::fs::read(&backup_path).unwrap(), backup_bytes);+ assert!(!reopened+ .conn()+ .prepare("PRAGMA foreign_key_check")+ .unwrap()+ .exists([])+ .unwrap());+ }+}++#[test]+fn legacy_goal_migration_rolls_back_trigger_retirement_on_rebuild_failure() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("pi.sqlite");+ legacy_goal_database(&path, 32, LEGACY_MODE_CHECK);+ let conn = Connection::open(&path).unwrap();+ let before = legacy_goal_snapshot(&conn);+ conn.execute_batch("CREATE TABLE sessions_v32(unrelated TEXT);")+ .unwrap();+ drop(conn);+ assert!(Database::open(&path).is_err());+ let conn = Connection::open(&path).unwrap();+ assert_eq!(+ conn.pragma_query_value(None, "user_version", |row| row.get::<_, i64>(0))+ .unwrap(),+ 32+ );+ assert!(has_legacy_goal_trigger(&conn));+ assert_eq!(legacy_goal_snapshot(&conn), before);+ assert!(conn+ .execute("UPDATE sessions SET mode='goal-3'", [])+ .is_err());+ assert!(dir.path().join("pi.sqlite.v32.bak").is_file());+}++#[test]+fn legacy_goal_migration_refuses_changes_without_a_valid_backup() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("pi.sqlite");+ legacy_goal_database(&path, 32, "");+ std::fs::create_dir(dir.path().join("pi.sqlite.v32.bak")).unwrap();+ assert!(Database::open(&path).is_err());+ let conn = Connection::open(&path).unwrap();+ assert_eq!(+ conn.pragma_query_value(None, "user_version", |row| row.get::<_, i64>(0))+ .unwrap(),+ 32+ );+ assert!(has_legacy_goal_trigger(&conn));+ assert_eq!(legacy_goal_snapshot(&conn).3, vec![0, 254]);+}++#[test]+fn legacy_goal_migration_preserves_an_already_unconstrained_schema() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("pi.sqlite");+ let db = Database::open(&path).unwrap();+ let before: String = db+ .conn()+ .query_row(+ "SELECT sql FROM sqlite_master WHERE name='sessions'",+ [],+ |row| row.get(0),+ )+ .unwrap();+ db.conn()+ .pragma_update(None, "user_version", 32i64)+ .unwrap();+ drop(db);+ let db = Database::open(&path).unwrap();+ let after: String = db+ .conn()+ .query_row(+ "SELECT sql FROM sqlite_master WHERE name='sessions'",+ [],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(before, after);+ assert_eq!(+ db.conn()+ .pragma_query_value(None, "user_version", |row| row.get::<_, i64>(0))+ .unwrap(),+ 33+ );+}++#[test]+fn legacy_goal_migration_rolls_back_on_foreign_key_failure() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("pi.sqlite");+ legacy_goal_database(&path, 32, "");+ let conn = Connection::open(&path).unwrap();+ let before = legacy_goal_snapshot(&conn);+ conn.pragma_update(None, "foreign_keys", false).unwrap();+ conn.execute(+ "INSERT INTO goal_turns(turn_id,goal_id) VALUES('orphan','missing')",+ [],+ )+ .unwrap();+ drop(conn);+ let error = Database::open(&path)+ .err()+ .expect("broken references must prevent migration commit");+ assert!(error.to_string().contains("foreign key check failed"));+ let conn = Connection::open(&path).unwrap();+ assert!(has_legacy_goal_trigger(&conn));+ assert_eq!(legacy_goal_snapshot(&conn), before);+ assert_eq!(+ conn.pragma_query_value(None, "user_version", |row| row.get::<_, i64>(0))+ .unwrap(),+ 32+ );+ assert!(dir.path().join("pi.sqlite.v32.bak").is_file());+}diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.mdindex 70df0358e..d30704340 100644--- a/docs/spec/03-runtime/04-data-storage.md+++ b/docs/spec/03-runtime/04-data-storage.md@@ -1,4 +1,4 @@-# 04. Data Storage (Schema v32)+# 04. Data Storage (Schema v33)### Project path aliases (#2148)@@ -2191,3 +2191,24 @@ does not repeat the migration. Earlier supported mode schemas upgrade throughtheir existing migrations first. Host mode-id, snapshot, and permission validationis unchanged. Older binaries reject schema 32; rollback uses the retained`pi.sqlite.v31.bak` rather than deleting user data.++### Retired independent Goal storage (schema 33)++Before the v32-to-v33 transaction, the Host verifies a `pi.sqlite.v32.bak`+backup. The transaction retires only the obsolete+`turn_execution_snapshot` trigger from the withdrawn independent Goal+implementation. Its `turn_execution`, `goal_turns`, and `session_goals` tables,+records, indexes, and other triggers remain intact; no new turns are written to+that archived execution ledger. A custom mode can then start and finish a turn+without being copied into its builtin-only mode CHECK.++That historical candidate also used schema 32. The new migration therefore+checks the actual sessions definition again and reuses the schema-32 repair+when its builtin-only CHECK remains. Already-unconstrained sessions are not+rebuilt. Foreign-key validation precedes commit, failures roll back both the+trigger retirement and any table replacement, and connection PRAGMAs are+restored on all exit paths. Earlier supported versions follow their existing+upgrade chain first. Reopening schema 33 does not repeat the repair or replace+the backup. Mode snapshots, permissions, and staged-run contracts are unchanged.+Older Host binaries reject schema 33; retain the compatible backup rather than+deleting application data or manually lowering the version marker.diff --git a/docs/spec/06-delivery/e2e/plans-goals-automation.md b/docs/spec/06-delivery/e2e/plans-goals-automation.mdindex 2079b1f5e..d3d43edca 100644--- a/docs/spec/06-delivery/e2e/plans-goals-automation.md+++ b/docs/spec/06-delivery/e2e/plans-goals-automation.md@@ -733,6 +733,28 @@ Coverage: `rpc/session_mode_migration_tests.rs` and`db/session_mode_migration_tests.rs`. This is isolated real SQLite/Host RPC coverage,not a claim of installed-client or live-provider acceptance.+## E2E-custom-mode-legacy-goal-upgrade: Retire the old turn snapshot writer++- **Preconditions**: Isolated schema-31 and schema-32 fixtures retain the+ independent Goal `turn_execution_snapshot` trigger and populated execution+ history. Include schema 32 both with and without the old sessions-mode CHECK.+- **Command**: Set `PI_SCRATCH_DIR` and `PI_DESKTOP_HOST_BIN`, then run+ `node scripts/e2e-legacy-goal-migration.mjs` after JS and Host builds. The+ Host binary may also be selected from the extracted installed-layout payload.+- **Steps**: Upgrade, select staged `goal-3` in a saved session, begin and end+ a turn, create another custom-mode session, inspect the backup, and restart.+- **Expected**: Schema reaches 33; custom turns complete without the legacy+ CHECK error; old ledger rows remain unchanged; only the obsolete trigger is+ retired; foreign keys remain valid; the verified schema-32 backup retains the+ original trigger and records and is not replaced on restart. RPC regression+ tests also cover backup refusal, transactional rollback, unchanged sessions+ schema when no rebuild is needed, and unrelated trigger behavior.+- **Specs linked**: [Data storage](../../03-runtime/04-data-storage.md).+- **Acceptance criterion**: C, G, H.+- **Milestone**: Post-MVP compatibility repair.+- **Status**: Automated at the isolated real-Host/RPC boundary; no live provider+ or running user Desktop is used.+## E2E-GOAL-completion-channel: Completion and blockers stop autonomous rounds- **Environment**: Isolated Host data and `PI_DESKTOP_AGENTS_DIR`, productiondiff --git a/package.json b/package.jsonindex 326c32986..097399b36 100644--- a/package.json+++ b/package.json@@ -120,7 +120,8 @@"test:e2e:shortcut-settings": "node scripts/test-shortcut-settings.mjs","test:e2e:dialog-overflow": "node scripts/test-dialog-overflow.mjs","test:e2e:overlay-selection": "node scripts/test-overlay-selection.mjs",- "test:e2e:live-voice-interaction": "node scripts/test-live-voice-interaction.mjs"+ "test:e2e:live-voice-interaction": "node scripts/test-live-voice-interaction.mjs",+ "test:e2e:mode-migration": "node scripts/e2e-legacy-goal-migration.mjs"},"devDependencies": {"@biomejs/biome": "^2.5.13",diff --git a/scripts/e2e-legacy-goal-migration.mjs b/scripts/e2e-legacy-goal-migration.mjsnew file mode 100644index 000000000..a33f9c43b--- /dev/null+++ b/scripts/e2e-legacy-goal-migration.mjs@@ -0,0 +1,112 @@+import assert from "node:assert/strict";+import fs from "node:fs";+import path from "node:path";+import { createHash } from "node:crypto";+import { DatabaseSync } from "node:sqlite";+import { loadModeDefinitions } from "../packages/agent-runtime/dist/mode-definitions.js";+import { Host, resolveHostBinary } from "./e2e/host.mjs";++const scratch = process.env.PI_SCRATCH_DIR;+assert.ok(scratch, "Set PI_SCRATCH_DIR to an isolated test-artifact directory");+const source = `---+name: goal-3+label: Goal 3+permission: agent+budget:+ maxTurns: 20+stages:+ work:+ permission: agent+ loop: true+ prompt: Verify the objective with evidence before completing the stage.+---+Work only within the current authorized goal.+`;+const loaded = loadModeDefinitions({ userDocuments: [{ dirName: "goal-3", filePath: "goal-3/mode.md", source, templates: {} }] });+assert.deepEqual(loaded.diagnostics, []);+const modeSnapshot = loaded.definitions.find((mode) => mode.id === "goal-3");+assert.ok(modeSnapshot?.stages[0]?.loop);+const digest = (file) => createHash("sha256").update(fs.readFileSync(file)).digest("hex");++for (const [version, constrained] of [[31, true], [32, false], [32, true]]) {+ const scenario = fs.mkdtempSync(path.join(scratch, "legacy-goal-upgrade-"));+ const data = path.join(scenario, "data");+ const workspace = path.join(scenario, "workspace");+ const agents = path.join(scenario, "agents");+ for (const dir of [data, workspace, agents]) fs.mkdirSync(dir);+ const host = new Host(resolveHostBinary(), data, { env: { PI_DESKTOP_AGENTS_DIR: agents }, quiet: true });+ const file = path.join(data, "pi.sqlite");+ let db;+ try {+ await host.start();+ await host.call("workspace.set", { path: workspace });+ const { session } = await host.call("session.create", { mode: "agent", title: "Saved fixture" });+ const { turnId: savedTurn } = await host.call("session.beginTurn", { sessionId: session.id });+ await host.call("session.endTurn", { turnId: savedTurn, status: "completed", createNotification: false });+ await host.stop();+ db = new DatabaseSync(file);+ assert.equal(db.prepare("PRAGMA user_version").get().user_version, 33);+ db.exec("PRAGMA foreign_keys=OFF; PRAGMA legacy_alter_table=ON; BEGIN;");+ if (constrained) {+ const sql = db.prepare("SELECT sql FROM sqlite_master WHERE type='table' AND name='sessions'").get().sql;+ const column = "mode TEXT NOT NULL DEFAULT 'agent'";+ assert.equal(sql.split(column).length, 2);+ const objects = db.prepare("SELECT sql FROM sqlite_master WHERE tbl_name='sessions' AND type IN ('index','trigger') AND sql IS NOT NULL").all();+ const legacy = sql.replace(column, `${column} CHECK(mode IN ('agent','plan','goal'))`);+ db.exec("CREATE TABLE sessions_legacy " + legacy.slice(legacy.indexOf("(")));+ db.exec("INSERT INTO sessions_legacy SELECT * FROM sessions; DROP TABLE sessions; ALTER TABLE sessions_legacy RENAME TO sessions;");+ for (const object of objects) db.exec(object.sql);+ }+ db.exec(`+ CREATE TABLE goal_turns(turn_id TEXT PRIMARY KEY);+ CREATE TABLE turn_execution(+ turn_id TEXT PRIMARY KEY REFERENCES turns(id) ON DELETE CASCADE,+ mode TEXT NOT NULL CHECK(mode IN ('agent','plan','goal')),+ goal_claim_id TEXT UNIQUE REFERENCES goal_turns(turn_id),+ provenance TEXT CHECK(provenance IN ('user-goal','goal-continuation')),+ CHECK((goal_claim_id IS NULL AND provenance IS NULL) OR+ (goal_claim_id IS NOT NULL AND provenance IS NOT NULL AND mode='goal'))+ );+ CREATE TRIGGER turn_execution_snapshot AFTER INSERT ON turns+ BEGIN+ INSERT INTO turn_execution(turn_id,mode)+ SELECT NEW.id,mode FROM sessions WHERE id=NEW.session_id;+ END;+ `);+ db.prepare("INSERT INTO turn_execution(turn_id,mode) VALUES(?,'agent')").run(savedTurn);+ db.exec(`PRAGMA user_version=${version}; COMMIT;`);+ const retained = db.prepare("SELECT * FROM turn_execution").all();+ db.close(); db = undefined;++ await host.start();+ const selected = await host.call("session.configure", { id: session.id, mode: "goal-3", modeSnapshot });+ assert.equal(selected.session.mode, "goal-3");+ const { turnId } = await host.call("session.beginTurn", { sessionId: session.id });+ const ended = await host.call("session.endTurn", { turnId, status: "completed", createNotification: false });+ assert.equal(ended.ok, true);+ const created = await host.call("session.create", { mode: "goal-3", modeSnapshot });+ assert.equal(created.session.mode, "goal-3");+ await host.stop();+ db = new DatabaseSync(file, { readOnly: true });+ assert.equal(db.prepare("PRAGMA user_version").get().user_version, 33);+ assert.deepEqual(db.prepare("SELECT * FROM turn_execution").all(), retained);+ assert.equal(db.prepare("SELECT count(*) AS n FROM sqlite_master WHERE type='trigger' AND name='turn_execution_snapshot'").get().n, 0);+ assert.deepEqual(db.prepare("PRAGMA foreign_key_check").all(), []);+ db.close(); db = undefined;+ const backup = file + ".v32.bak";+ db = new DatabaseSync(backup, { readOnly: true });+ assert.equal(db.prepare("PRAGMA user_version").get().user_version, 32);+ assert.deepEqual(db.prepare("SELECT * FROM turn_execution").all(), retained);+ assert.equal(db.prepare("SELECT count(*) AS n FROM sqlite_master WHERE name='turn_execution_snapshot'").get().n, 1);+ db.close(); db = undefined;+ const backupHash = digest(backup);+ await host.start();+ assert.equal((await host.call("session.get", { id: session.id, messageLimit: 1 })).session.mode, "goal-3");+ await host.stop();+ assert.equal(digest(backup), backupHash);+ console.log(`PASS schema ${version}, sessions CHECK ${constrained}: upgrade, staged custom mode turn, historical ledger, backup and restart. Artifacts: ${scenario}`);+ } finally {+ db?.close();+ await host.stop();+ }+}