Skip to main content

aidaemon_work/
schema.rs

1//! The goals, mandates, tasks, work and notification tables.
2//!
3//! The statements run in the order they always have. A database gives no way
4//! to tell which of them it has seen, so they stay idempotent and keep
5//! running on every start. Called in two steps because the host's own tables
6//! sit between them. `goals.source_episode_id` refers to long-term memory's
7//! `episodes` table, so a host without that memory creates a table of that
8//! name first; `aidaemon_events::schema::migrate_events` runs first as well.
9
10use chrono::{Datelike, TimeZone, Timelike};
11use sqlx::Row;
12use sqlx::SqlitePool;
13
14/// The version record that says `_goals_legacy_deprecated` has been imported.
15pub const LEGACY_GOALS_IMPORTED_VERSION: i64 = 2;
16
17pub async fn table_exists_in_pool(pool: &SqlitePool, name: &str) -> anyhow::Result<bool> {
18    Ok(sqlx::query_scalar::<_, i64>(
19        "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?",
20    )
21    .bind(name)
22    .fetch_optional(pool)
23    .await?
24    .is_some())
25}
26
27/// The version record that says the one-time backfills below have run with
28/// this release's code: mandate session links, task dependency rows and the
29/// legacy goal runs. Recorded by the host after the steps ran; before it they
30/// run on every start, as they always did.
31pub const WORK_BACKFILLS_DONE_VERSION: i64 = 3;
32
33async fn state_version_recorded(pool: &SqlitePool, version: i64) -> anyhow::Result<bool> {
34    if !table_exists_in_pool(pool, "state_schema_versions").await? {
35        return Ok(false);
36    }
37    Ok(
38        sqlx::query_scalar::<_, i64>("SELECT 1 FROM state_schema_versions WHERE version = ?")
39            .bind(version)
40            .fetch_optional(pool)
41            .await?
42            .is_some(),
43    )
44}
45
46async fn legacy_goals_already_imported(pool: &SqlitePool) -> anyhow::Result<bool> {
47    state_version_recorded(pool, LEGACY_GOALS_IMPORTED_VERSION).await
48}
49
50async fn work_backfills_done(pool: &SqlitePool) -> anyhow::Result<bool> {
51    state_version_recorded(pool, WORK_BACKFILLS_DONE_VERSION).await
52}
53
54/// The goal, mandate, task and notification tables, up to the host's own.
55pub async fn migrate_work_tables(
56    pool: &SqlitePool,
57    is_one_shot_schedule: fn(&str) -> bool,
58) -> anyhow::Result<()> {
59    // --- Goals/Tasks/Schedules (cleanup/unification) ---
60    //
61    // Historical schemas:
62    // - `goals` (INTEGER PRIMARY KEY): personal memory goals (legacy)
63    // - `scheduled_tasks`: legacy scheduler rows
64    // - prior orchestration schema: `goals_v3`, `tasks_v3`, `task_activity_v3`
65    //
66    // Target schema:
67    // - `goals` (TEXT PRIMARY KEY) with `domain` gating ("orchestration" vs "personal")
68    // - `tasks`, `task_activity`
69    // - `goal_schedules` (multiple schedules per goal with per-schedule state)
70    //
71    // Safety goals:
72    // - Transactional table renames (all succeed or none)
73    // - Legacy tables preserved as *_deprecated for recovery (not dropped)
74    // - Idempotent (safe to run multiple times)
75
76    let has_goals_v3 = sqlx::query_scalar::<_, i64>(
77        "SELECT 1 FROM sqlite_master WHERE type='table' AND name='goals_v3' LIMIT 1",
78    )
79    .fetch_optional(pool)
80    .await?
81    .is_some();
82    let has_tasks_v3 = sqlx::query_scalar::<_, i64>(
83        "SELECT 1 FROM sqlite_master WHERE type='table' AND name='tasks_v3' LIMIT 1",
84    )
85    .fetch_optional(pool)
86    .await?
87    .is_some();
88    let has_task_activity_v3 = sqlx::query_scalar::<_, i64>(
89        "SELECT 1 FROM sqlite_master WHERE type='table' AND name='task_activity_v3' LIMIT 1",
90    )
91    .fetch_optional(pool)
92    .await?
93    .is_some();
94    let has_scheduled_tasks = sqlx::query_scalar::<_, i64>(
95        "SELECT 1 FROM sqlite_master WHERE type='table' AND name='scheduled_tasks' LIMIT 1",
96    )
97    .fetch_optional(pool)
98    .await?
99    .is_some();
100
101    let has_goals = sqlx::query_scalar::<_, i64>(
102        "SELECT 1 FROM sqlite_master WHERE type='table' AND name='goals' LIMIT 1",
103    )
104    .fetch_optional(pool)
105    .await?
106    .is_some();
107
108    let (goals_has_goal_type, goals_has_legacy_int_id) = if has_goals {
109        let cols = sqlx::query("PRAGMA table_info(goals)")
110            .fetch_all(pool)
111            .await?;
112        let mut has_goal_type = false;
113        let mut has_legacy_int_id = false;
114        for name in cols
115            .iter()
116            .filter_map(|r| r.try_get::<String, _>("name").ok())
117        {
118            if name == "goal_type" {
119                has_goal_type = true;
120            } else if name == "legacy_int_id" {
121                has_legacy_int_id = true;
122            }
123        }
124        (has_goal_type, has_legacy_int_id)
125    } else {
126        (false, false)
127    };
128    let has_legacy_goals = has_goals && !goals_has_goal_type;
129
130    let has_legacy_goals_deprecated = sqlx::query_scalar::<_, i64>(
131        "SELECT 1 FROM sqlite_master WHERE type='table' AND name='_goals_legacy_deprecated' LIMIT 1",
132    )
133    .fetch_optional(pool)
134    .await?
135    .is_some();
136
137    // Keep the deprecated table for recovery, but only re-run heavy goal schema
138    // unification when it still contains rows that are not represented in unified goals.
139    let legacy_goals_deprecated_needs_migration = if has_legacy_goals_deprecated {
140        if !has_goals || !goals_has_goal_type || !goals_has_legacy_int_id {
141            true
142        } else if legacy_goals_already_imported(pool).await? {
143            // Retention may have removed imported goals since. They stay gone.
144            false
145        } else {
146            sqlx::query_scalar::<_, i64>(
147                "SELECT 1
148                 FROM _goals_legacy_deprecated lg
149                 WHERE NOT EXISTS (
150                     SELECT 1
151                     FROM goals g
152                     WHERE g.domain = 'personal'
153                       AND g.legacy_int_id = lg.id
154                 )
155                 LIMIT 1",
156            )
157            .fetch_optional(pool)
158            .await?
159            .is_some()
160        }
161    } else {
162        false
163    };
164
165    let should_unify_goal_schema = has_goals_v3
166        || has_tasks_v3
167        || has_task_activity_v3
168        || has_scheduled_tasks
169        || has_legacy_goals
170        || legacy_goals_deprecated_needs_migration;
171
172    if should_unify_goal_schema {
173        tracing::info!(
174            "Migrating database: unifying goals/tasks schema (legacy + prior schema -> clean names)"
175        );
176
177        // Best-effort datetime parser for legacy rows.
178        fn parse_legacy_datetime_to_local(raw: &str) -> Option<chrono::DateTime<chrono::Local>> {
179            chrono::DateTime::parse_from_rfc3339(raw)
180                .ok()
181                .map(|dt| dt.with_timezone(&chrono::Local))
182                .or_else(|| {
183                    chrono::NaiveDateTime::parse_from_str(raw, "%Y-%m-%d %H:%M:%S")
184                        .ok()
185                        .and_then(|naive| match chrono::Local.from_local_datetime(&naive) {
186                            chrono::LocalResult::Single(dt) => Some(dt),
187                            chrono::LocalResult::Ambiguous(early, _) => Some(early),
188                            chrono::LocalResult::None => None,
189                        })
190                })
191        }
192
193        let mut tx = pool.begin_with("BEGIN IMMEDIATE").await?;
194
195        // Helper: column existence check (works even if the table doesn't exist).
196        async fn column_exists(
197            tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
198            table: &str,
199            column: &str,
200        ) -> anyhow::Result<bool> {
201            let rows = sqlx::query(sqlx::AssertSqlSafe(format!("PRAGMA table_info({})", table)))
202                .fetch_all(&mut **tx)
203                .await?;
204            Ok(rows
205                .iter()
206                .filter_map(|r| r.try_get::<String, _>("name").ok())
207                .any(|n| n == column))
208        }
209
210        async fn table_exists(
211            tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
212            name: &str,
213        ) -> anyhow::Result<bool> {
214            Ok(sqlx::query_scalar::<_, i64>(
215                "SELECT 1 FROM sqlite_master WHERE type='table' AND name=? LIMIT 1",
216            )
217            .bind(name)
218            .fetch_optional(&mut **tx)
219            .await?
220            .is_some())
221        }
222
223        // 1) If a legacy `goals` table exists (INTEGER PK), rename it out of the way.
224        // Drop the legacy index first to avoid name collisions when we create new indexes.
225        let goals_is_legacy = table_exists(&mut tx, "goals").await?
226            && !column_exists(&mut tx, "goals", "goal_type").await?;
227        if goals_is_legacy && !table_exists(&mut tx, "_goals_legacy_deprecated").await? {
228            let _ = sqlx::query("DROP INDEX IF EXISTS idx_goals_status")
229                .execute(&mut *tx)
230                .await;
231            sqlx::query("ALTER TABLE goals RENAME TO _goals_legacy_deprecated")
232                .execute(&mut *tx)
233                .await?;
234        }
235
236        // 2) Rename prior orchestration tables to clean names.
237        if table_exists(&mut tx, "goals_v3").await? && !table_exists(&mut tx, "goals").await? {
238            sqlx::query("ALTER TABLE goals_v3 RENAME TO goals")
239                .execute(&mut *tx)
240                .await?;
241        }
242        if table_exists(&mut tx, "tasks_v3").await? && !table_exists(&mut tx, "tasks").await? {
243            sqlx::query("ALTER TABLE tasks_v3 RENAME TO tasks")
244                .execute(&mut *tx)
245                .await?;
246        }
247        if table_exists(&mut tx, "task_activity_v3").await?
248            && !table_exists(&mut tx, "task_activity").await?
249        {
250            sqlx::query("ALTER TABLE task_activity_v3 RENAME TO task_activity")
251                .execute(&mut *tx)
252                .await?;
253        }
254
255        // 3) Drop old index names (SQLite keeps index names on table rename).
256        let _ = sqlx::query("DROP INDEX IF EXISTS idx_goals_v3_status")
257            .execute(&mut *tx)
258            .await;
259        let _ = sqlx::query("DROP INDEX IF EXISTS idx_goals_v3_session")
260            .execute(&mut *tx)
261            .await;
262        let _ = sqlx::query("DROP INDEX IF EXISTS idx_tasks_v3_goal")
263            .execute(&mut *tx)
264            .await;
265        let _ = sqlx::query("DROP INDEX IF EXISTS idx_tasks_v3_status")
266            .execute(&mut *tx)
267            .await;
268        let _ = sqlx::query("DROP INDEX IF EXISTS idx_task_activity_v3_task")
269            .execute(&mut *tx)
270            .await;
271        let _ = sqlx::query("DROP INDEX IF EXISTS idx_task_activity_v3_created_at")
272            .execute(&mut *tx)
273            .await;
274
275        // 4) Create clean tables if missing (fresh installs or legacy DBs).
276        sqlx::query(
277            "CREATE TABLE IF NOT EXISTS goals (
278                id TEXT PRIMARY KEY,
279                description TEXT NOT NULL,
280                domain TEXT NOT NULL DEFAULT 'orchestration',
281                goal_type TEXT NOT NULL DEFAULT 'finite',
282                status TEXT NOT NULL DEFAULT 'active',
283                priority TEXT NOT NULL DEFAULT 'medium',
284                conditions TEXT,
285                context TEXT,
286                resources TEXT,
287                budget_per_check INTEGER,
288                budget_daily INTEGER,
289                tokens_used_today INTEGER NOT NULL DEFAULT 0,
290                tokens_used_day TEXT NOT NULL DEFAULT '1970-01-01',
291                last_useful_action TEXT,
292                created_at TEXT NOT NULL DEFAULT (datetime('now')),
293                updated_at TEXT NOT NULL DEFAULT (datetime('now')),
294                completed_at TEXT,
295                parent_goal_id TEXT,
296                session_id TEXT NOT NULL,
297                notified_at TEXT,
298                notification_attempts INTEGER NOT NULL DEFAULT 0,
299                dispatch_failures INTEGER NOT NULL DEFAULT 0,
300                progress_notes TEXT,
301                source_episode_id INTEGER REFERENCES episodes(id),
302                legacy_int_id INTEGER
303            )",
304        )
305        .execute(&mut *tx)
306        .await?;
307
308        sqlx::query(
309            "CREATE TABLE IF NOT EXISTS tasks (
310                id TEXT PRIMARY KEY,
311                goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
312                description TEXT NOT NULL,
313                status TEXT NOT NULL DEFAULT 'pending',
314                priority TEXT NOT NULL DEFAULT 'medium',
315                task_order INTEGER NOT NULL DEFAULT 0,
316                parallel_group TEXT,
317                depends_on TEXT,
318                agent_id TEXT,
319                context TEXT,
320                result TEXT,
321                error TEXT,
322                blocker TEXT,
323                idempotent INTEGER NOT NULL DEFAULT 0,
324                retry_count INTEGER NOT NULL DEFAULT 0,
325                max_retries INTEGER NOT NULL DEFAULT 3,
326                created_at TEXT NOT NULL DEFAULT (datetime('now')),
327                started_at TEXT,
328                completed_at TEXT
329            )",
330        )
331        .execute(&mut *tx)
332        .await?;
333
334        sqlx::query(
335            "CREATE TABLE IF NOT EXISTS task_activity (
336                id INTEGER PRIMARY KEY AUTOINCREMENT,
337                task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
338                activity_type TEXT NOT NULL,
339                tool_name TEXT,
340                tool_args TEXT,
341                result TEXT,
342                success INTEGER,
343                tokens_used INTEGER,
344                created_at TEXT NOT NULL DEFAULT (datetime('now'))
345            )",
346        )
347        .execute(&mut *tx)
348        .await?;
349
350        sqlx::query(
351            "CREATE TABLE IF NOT EXISTS goal_schedules (
352                id TEXT PRIMARY KEY,
353                goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
354                cron_expr TEXT NOT NULL,
355                tz TEXT NOT NULL DEFAULT 'local',
356                original_schedule TEXT,
357                fire_policy TEXT NOT NULL DEFAULT 'coalesce',
358                is_one_shot INTEGER NOT NULL DEFAULT 0,
359                is_paused INTEGER NOT NULL DEFAULT 0,
360                last_run_at TEXT,
361                next_run_at TEXT NOT NULL,
362                created_at TEXT NOT NULL DEFAULT (datetime('now')),
363                updated_at TEXT NOT NULL DEFAULT (datetime('now'))
364            )",
365        )
366        .execute(&mut *tx)
367        .await?;
368
369        // 5) Ensure new columns exist on renamed goals table.
370        aidaemon_tools::sqlite_schema::add_column_if_missing_on(
371            &mut tx,
372            "ALTER TABLE goals ADD COLUMN domain TEXT NOT NULL DEFAULT 'orchestration'",
373        )
374        .await?;
375        aidaemon_tools::sqlite_schema::add_column_if_missing_on(
376            &mut tx,
377            "ALTER TABLE goals ADD COLUMN tokens_used_day TEXT NOT NULL DEFAULT '1970-01-01'",
378        )
379        .await?;
380        aidaemon_tools::sqlite_schema::add_column_if_missing_on(
381            &mut tx,
382            "ALTER TABLE goals ADD COLUMN notification_attempts INTEGER NOT NULL DEFAULT 0",
383        )
384        .await?;
385        aidaemon_tools::sqlite_schema::add_column_if_missing_on(
386            &mut tx,
387            "ALTER TABLE goals ADD COLUMN dispatch_failures INTEGER NOT NULL DEFAULT 0",
388        )
389        .await?;
390        aidaemon_tools::sqlite_schema::add_column_if_missing_on(
391            &mut tx,
392            "ALTER TABLE goals ADD COLUMN progress_notes TEXT",
393        )
394        .await?;
395        aidaemon_tools::sqlite_schema::add_column_if_missing_on(
396            &mut tx,
397            "ALTER TABLE goals ADD COLUMN source_episode_id INTEGER",
398        )
399        .await?;
400        aidaemon_tools::sqlite_schema::add_column_if_missing_on(
401            &mut tx,
402            "ALTER TABLE goals ADD COLUMN legacy_int_id INTEGER",
403        )
404        .await?;
405
406        // 6) Create clean indexes (drop potential collisions first).
407        let _ = sqlx::query("DROP INDEX IF EXISTS idx_goals_status")
408            .execute(&mut *tx)
409            .await;
410        let _ = sqlx::query("DROP INDEX IF EXISTS idx_goals_session")
411            .execute(&mut *tx)
412            .await;
413
414        sqlx::query("CREATE INDEX IF NOT EXISTS idx_goals_status ON goals(status)")
415            .execute(&mut *tx)
416            .await?;
417        sqlx::query("CREATE INDEX IF NOT EXISTS idx_goals_session ON goals(session_id)")
418            .execute(&mut *tx)
419            .await?;
420        sqlx::query("CREATE INDEX IF NOT EXISTS idx_goals_domain_status ON goals(domain, status)")
421            .execute(&mut *tx)
422            .await?;
423        sqlx::query("CREATE INDEX IF NOT EXISTS idx_tasks_goal ON tasks(goal_id)")
424            .execute(&mut *tx)
425            .await?;
426        sqlx::query("CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks(status)")
427            .execute(&mut *tx)
428            .await?;
429        sqlx::query("CREATE INDEX IF NOT EXISTS idx_task_activity_task ON task_activity(task_id)")
430            .execute(&mut *tx)
431            .await?;
432        sqlx::query(
433            "CREATE INDEX IF NOT EXISTS idx_task_activity_created_at ON task_activity(created_at)",
434        )
435        .execute(&mut *tx)
436        .await?;
437        sqlx::query(
438            "CREATE INDEX IF NOT EXISTS idx_goal_schedules_goal ON goal_schedules(goal_id)",
439        )
440        .execute(&mut *tx)
441        .await?;
442        sqlx::query(
443            "CREATE INDEX IF NOT EXISTS idx_goal_schedules_next_run
444             ON goal_schedules(next_run_at) WHERE is_paused = 0",
445        )
446        .execute(&mut *tx)
447        .await?;
448
449        // 7) Migrate legacy personal goals into unified `goals` (domain='personal').
450        if table_exists(&mut tx, "_goals_legacy_deprecated").await? {
451            sqlx::query(
452                "INSERT OR IGNORE INTO goals (
453                    id, description, domain, goal_type, status, priority,
454                    conditions, context, resources,
455                    budget_per_check, budget_daily,
456                    tokens_used_today, tokens_used_day,
457                    last_useful_action,
458                    created_at, updated_at, completed_at,
459                    parent_goal_id, session_id, notified_at,
460                    notification_attempts, dispatch_failures,
461                    progress_notes, source_episode_id, legacy_int_id
462                )
463                SELECT
464                    'personal-legacy-' || id,
465                    description,
466                    'personal',
467                    'finite',
468                    COALESCE(status, 'active'),
469                    COALESCE(priority, 'medium'),
470                    NULL, NULL, NULL,
471                    NULL, NULL,
472                    0,
473                    '1970-01-01',
474                    NULL,
475                    created_at,
476                    updated_at,
477                    completed_at,
478                    NULL,
479                    '_global',
480                    NULL,
481                    0,
482                    0,
483                    progress_notes,
484                    source_episode_id,
485                    id
486                FROM _goals_legacy_deprecated",
487            )
488            .execute(&mut *tx)
489            .await?;
490        }
491
492        // 8) Migrate schedules stored as `goals.schedule` into `goal_schedules`.
493        if column_exists(&mut tx, "goals", "schedule").await? {
494            let rows = sqlx::query(
495                "SELECT id, goal_type, status, schedule, created_at, last_useful_action
496                 FROM goals
497                 WHERE schedule IS NOT NULL AND TRIM(schedule) != ''",
498            )
499            .fetch_all(&mut *tx)
500            .await?;
501
502            for r in &rows {
503                let goal_id: String = r.get("id");
504                let goal_type: String = r.get("goal_type");
505                let status: String = r.get("status");
506                let cron_expr: Option<String> = r.get("schedule");
507                let created_at: String = r.get("created_at");
508                let last_useful_action: Option<String> = r.get("last_useful_action");
509
510                let Some(cron_expr) = cron_expr
511                    .map(|s| s.trim().to_string())
512                    .filter(|s| !s.is_empty())
513                else {
514                    continue;
515                };
516
517                // Deterministic schedule ID keeps migration idempotent.
518                let schedule_id = format!("sched-migrated-{}", goal_id);
519
520                let cron: croner::Cron = match cron_expr.parse() {
521                    Ok(c) => c,
522                    Err(_) => continue,
523                };
524
525                // Anchor next-run computation to last_useful_action or created_at,
526                // matching prior behavior (so one-shots overdue on restart fire ASAP).
527                let anchor_local = last_useful_action
528                    .as_deref()
529                    .and_then(parse_legacy_datetime_to_local)
530                    .or_else(|| parse_legacy_datetime_to_local(&created_at))
531                    .unwrap_or_else(chrono::Local::now);
532
533                let next_local = match cron.find_next_occurrence(&anchor_local, false) {
534                    Ok(dt) => dt,
535                    Err(_) => continue,
536                };
537
538                let is_one_shot = goal_type == "finite" && is_one_shot_schedule(&cron_expr);
539                let fire_policy = "coalesce";
540                let tz = "local";
541                let now = chrono::Utc::now().to_rfc3339();
542                let next_run_at = next_local.with_timezone(&chrono::Utc).to_rfc3339();
543
544                let schedule_paused = status == "paused";
545
546                let _ = sqlx::query(
547                    "INSERT OR IGNORE INTO goal_schedules
548                        (id, goal_id, cron_expr, tz, original_schedule, fire_policy, is_one_shot, is_paused, last_run_at, next_run_at, created_at, updated_at)
549                     VALUES (?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?)",
550                )
551                .bind(&schedule_id)
552                .bind(&goal_id)
553                .bind(&cron_expr)
554                .bind(tz)
555                .bind(fire_policy)
556                .bind(if is_one_shot { 1 } else { 0 })
557                .bind(if schedule_paused { 1 } else { 0 })
558                .bind(&last_useful_action)
559                .bind(&next_run_at)
560                .bind(&now)
561                .bind(&now)
562                .execute(&mut *tx)
563                .await;
564            }
565        }
566
567        // 9) Migrate legacy scheduled_tasks rows into goals + goal_schedules, then drop the table.
568        if table_exists(&mut tx, "scheduled_tasks").await? {
569            let rows = sqlx::query(
570                "SELECT id, name, cron_expr, original_schedule, prompt, source, is_oneshot, is_paused,
571                        last_run_at, next_run_at
572                 FROM scheduled_tasks
573                 ORDER BY created_at ASC",
574            )
575            .fetch_all(&mut *tx)
576            .await?;
577
578            let now_rfc3339 = chrono::Utc::now().to_rfc3339();
579            let now_local = chrono::Local::now();
580
581            for r in &rows {
582                let legacy_id: String = r.get("id");
583                let legacy_name: String = r.get("name");
584                let legacy_cron: String = r.get("cron_expr");
585                let legacy_original_schedule: String = r.get("original_schedule");
586                let legacy_prompt: String = r.get("prompt");
587                let legacy_source: String = r.get("source");
588                let legacy_is_oneshot: bool = r.get::<i64, _>("is_oneshot") != 0;
589                let legacy_is_paused: bool = r.get::<i64, _>("is_paused") != 0;
590                let legacy_last_run: Option<String> = r.get("last_run_at");
591                let legacy_next_run: String = r.get("next_run_at");
592
593                let migrated_goal_id = format!("legacy-sched-{}", legacy_id);
594                let description = if !legacy_prompt.trim().is_empty() {
595                    legacy_prompt.trim().to_string()
596                } else {
597                    legacy_name.clone()
598                };
599
600                // If this goal already exists (e.g., migrated earlier by runtime code), skip creating it.
601                let goal_exists =
602                    sqlx::query_scalar::<_, i64>("SELECT 1 FROM goals WHERE id = ? LIMIT 1")
603                        .bind(&migrated_goal_id)
604                        .fetch_optional(&mut *tx)
605                        .await?
606                        .is_some();
607
608                if !goal_exists {
609                    let (goal_type, priority, budget_per_check, budget_daily) = if legacy_is_oneshot
610                    {
611                        ("finite", "medium", Some(100_000i64), Some(500_000i64))
612                    } else {
613                        ("continuous", "low", Some(100_000i64), Some(500_000i64))
614                    };
615
616                    let status = if legacy_is_paused { "paused" } else { "active" };
617
618                    let ctx = serde_json::json!({
619                        "migrated_from": "scheduled_tasks",
620                        "legacy_task_id": legacy_id,
621                        "legacy_name": legacy_name,
622                        "legacy_source": legacy_source,
623                        "legacy_original_schedule": legacy_original_schedule,
624                        "legacy_next_run_at": legacy_next_run,
625                    })
626                    .to_string();
627
628                    let _ = sqlx::query(
629                        "INSERT OR IGNORE INTO goals
630                            (id, description, domain, goal_type, status, priority, conditions, context, resources,
631                             budget_per_check, budget_daily, tokens_used_today, tokens_used_day, last_useful_action,
632                             created_at, updated_at, completed_at, parent_goal_id, session_id, notified_at,
633                             notification_attempts, dispatch_failures, progress_notes, source_episode_id, legacy_int_id)
634                         VALUES (?, ?, 'orchestration', ?, ?, ?, NULL, ?, NULL, ?, ?, 0, ?, ?, ?, ?, NULL, NULL, 'system', NULL, 0, 0, NULL, NULL, NULL)",
635                    )
636                    .bind(&migrated_goal_id)
637                    .bind(&description)
638                    .bind(goal_type)
639                    .bind(status)
640                    .bind(priority)
641                    .bind(&ctx)
642                    .bind(budget_per_check)
643                    .bind(budget_daily)
644                    .bind(chrono::Utc::now().date_naive().to_string())
645                    .bind(legacy_last_run.as_deref().unwrap_or(""))
646                    .bind(&now_rfc3339)
647                    .bind(&now_rfc3339)
648                    .execute(&mut *tx)
649                    .await;
650                }
651
652                // Schedule: preserve legacy next_run_at when possible.
653                let cron_expr = if legacy_is_oneshot {
654                    let target_local = parse_legacy_datetime_to_local(&legacy_next_run)
655                        .unwrap_or_else(|| now_local + chrono::Duration::minutes(1));
656                    let effective_target = if target_local <= now_local {
657                        now_local + chrono::Duration::minutes(1)
658                    } else {
659                        target_local
660                    };
661                    format!(
662                        "{} {} {} {} *",
663                        effective_target.minute(),
664                        effective_target.hour(),
665                        effective_target.day(),
666                        effective_target.month()
667                    )
668                } else {
669                    legacy_cron.clone()
670                };
671
672                let next_run_at = parse_legacy_datetime_to_local(&legacy_next_run)
673                    .map(|dt| dt.with_timezone(&chrono::Utc).to_rfc3339())
674                    .unwrap_or_else(|| chrono::Utc::now().to_rfc3339());
675
676                let schedule_id = format!("sched-legacy-{}", legacy_id);
677                let _ = sqlx::query(
678                    "INSERT OR IGNORE INTO goal_schedules
679                        (id, goal_id, cron_expr, tz, original_schedule, fire_policy, is_one_shot, is_paused, last_run_at, next_run_at, created_at, updated_at)
680                     VALUES (?, ?, ?, 'local', ?, 'coalesce', ?, ?, ?, ?, ?, ?)",
681                )
682                .bind(&schedule_id)
683                .bind(&migrated_goal_id)
684                .bind(&cron_expr)
685                .bind(&legacy_original_schedule)
686                .bind(if legacy_is_oneshot { 1 } else { 0 })
687                .bind(if legacy_is_paused { 1 } else { 0 })
688                .bind(&legacy_last_run)
689                .bind(&next_run_at)
690                .bind(&now_rfc3339)
691                .bind(&now_rfc3339)
692                .execute(&mut *tx)
693                .await;
694            }
695
696            let _ = sqlx::query("DROP TABLE IF EXISTS scheduled_tasks")
697                .execute(&mut *tx)
698                .await;
699        }
700
701        tx.commit().await?;
702    }
703
704    // Ensure clean schema exists for fresh installs or already-migrated DBs.
705    sqlx::query(
706        "CREATE TABLE IF NOT EXISTS goals (
707            id TEXT PRIMARY KEY,
708            description TEXT NOT NULL,
709            domain TEXT NOT NULL DEFAULT 'orchestration',
710            goal_type TEXT NOT NULL DEFAULT 'finite',
711            status TEXT NOT NULL DEFAULT 'active',
712            priority TEXT NOT NULL DEFAULT 'medium',
713            conditions TEXT,
714            context TEXT,
715            resources TEXT,
716            budget_per_check INTEGER,
717            budget_daily INTEGER,
718            tokens_used_today INTEGER NOT NULL DEFAULT 0,
719            tokens_used_day TEXT NOT NULL DEFAULT '1970-01-01',
720            last_useful_action TEXT,
721            created_at TEXT NOT NULL DEFAULT (datetime('now')),
722            updated_at TEXT NOT NULL DEFAULT (datetime('now')),
723            completed_at TEXT,
724            parent_goal_id TEXT,
725            session_id TEXT NOT NULL,
726            notified_at TEXT,
727            notification_attempts INTEGER NOT NULL DEFAULT 0,
728            dispatch_failures INTEGER NOT NULL DEFAULT 0,
729            progress_notes TEXT,
730            source_episode_id INTEGER REFERENCES episodes(id),
731            legacy_int_id INTEGER
732        )",
733    )
734    .execute(pool)
735    .await?;
736
737    sqlx::query(
738        "CREATE TABLE IF NOT EXISTS tasks (
739            id TEXT PRIMARY KEY,
740            goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
741            description TEXT NOT NULL,
742            status TEXT NOT NULL DEFAULT 'pending',
743            priority TEXT NOT NULL DEFAULT 'medium',
744            task_order INTEGER NOT NULL DEFAULT 0,
745            parallel_group TEXT,
746            depends_on TEXT,
747            agent_id TEXT,
748            context TEXT,
749            result TEXT,
750            error TEXT,
751            blocker TEXT,
752            idempotent INTEGER NOT NULL DEFAULT 0,
753            retry_count INTEGER NOT NULL DEFAULT 0,
754            max_retries INTEGER NOT NULL DEFAULT 3,
755            created_at TEXT NOT NULL DEFAULT (datetime('now')),
756            started_at TEXT,
757            completed_at TEXT
758        )",
759    )
760    .execute(pool)
761    .await?;
762
763    sqlx::query(
764        "CREATE TABLE IF NOT EXISTS task_activity (
765            id INTEGER PRIMARY KEY AUTOINCREMENT,
766            task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
767            activity_type TEXT NOT NULL,
768            tool_name TEXT,
769            tool_args TEXT,
770            result TEXT,
771            success INTEGER,
772            tokens_used INTEGER,
773            created_at TEXT NOT NULL DEFAULT (datetime('now'))
774        )",
775    )
776    .execute(pool)
777    .await?;
778
779    sqlx::query(
780        "CREATE TABLE IF NOT EXISTS goal_schedules (
781            id TEXT PRIMARY KEY,
782            goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
783            cron_expr TEXT NOT NULL,
784            tz TEXT NOT NULL DEFAULT 'local',
785            original_schedule TEXT,
786            fire_policy TEXT NOT NULL DEFAULT 'coalesce',
787            is_one_shot INTEGER NOT NULL DEFAULT 0,
788            is_paused INTEGER NOT NULL DEFAULT 0,
789            last_run_at TEXT,
790            next_run_at TEXT NOT NULL,
791            created_at TEXT NOT NULL DEFAULT (datetime('now')),
792            updated_at TEXT NOT NULL DEFAULT (datetime('now'))
793        )",
794    )
795    .execute(pool)
796    .await?;
797
798    sqlx::query(
799        "CREATE TABLE IF NOT EXISTS scheduled_run_state (
800            goal_id TEXT PRIMARY KEY REFERENCES goals(id) ON DELETE CASCADE,
801            root_task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
802            effective_budget_per_check INTEGER NOT NULL,
803            tokens_used INTEGER NOT NULL DEFAULT 0,
804            budget_extensions_count INTEGER NOT NULL DEFAULT 0,
805            health_json TEXT NOT NULL DEFAULT '{}',
806            created_at TEXT NOT NULL DEFAULT (datetime('now')),
807            updated_at TEXT NOT NULL DEFAULT (datetime('now'))
808        )",
809    )
810    .execute(pool)
811    .await?;
812
813    aidaemon_tools::sqlite_schema::add_column_if_missing(
814        pool,
815        "ALTER TABLE scheduled_run_state ADD COLUMN health_json TEXT NOT NULL DEFAULT '{}'",
816    )
817    .await?;
818    sqlx::query(
819        "CREATE TABLE IF NOT EXISTS scheduled_recovery_state (
820            goal_id TEXT PRIMARY KEY REFERENCES goals(id) ON DELETE CASCADE,
821            consecutive_failures INTEGER NOT NULL DEFAULT 0,
822            failure_budget INTEGER NOT NULL DEFAULT 3 CHECK (failure_budget BETWEEN 1 AND 10),
823            disposition TEXT NOT NULL DEFAULT 'healthy'
824                CHECK (disposition IN ('healthy', 'recovering', 'escalated')),
825            latest_failure_kind TEXT,
826            last_failed_run_id TEXT REFERENCES goal_runs(id) ON DELETE SET NULL,
827            last_recovery_run_id TEXT REFERENCES goal_runs(id) ON DELETE SET NULL,
828            updated_at TEXT NOT NULL
829        )",
830    )
831    .execute(pool)
832    .await?;
833    // Additive columns for automatic post-escalation recovery attempts.
834    aidaemon_tools::sqlite_schema::add_column_if_missing(
835        pool,
836        "ALTER TABLE scheduled_recovery_state
837            ADD COLUMN recovery_attempts INTEGER NOT NULL DEFAULT 0",
838    )
839    .await?;
840    aidaemon_tools::sqlite_schema::add_column_if_missing(
841        pool,
842        "ALTER TABLE scheduled_recovery_state ADD COLUMN last_recovery_attempt_at TEXT",
843    )
844    .await?;
845    sqlx::query(
846        "CREATE TABLE IF NOT EXISTS goal_run_recovery_links (
847            failed_run_id TEXT NOT NULL REFERENCES goal_runs(id) ON DELETE CASCADE,
848            recovery_run_id TEXT NOT NULL REFERENCES goal_runs(id) ON DELETE CASCADE,
849            outcome_status TEXT NOT NULL
850                CHECK (outcome_status IN ('recovering', 'verified', 'failed')),
851            proof_receipt_ids_json TEXT NOT NULL DEFAULT '[]',
852            created_at TEXT NOT NULL,
853            updated_at TEXT NOT NULL,
854            PRIMARY KEY (failed_run_id, recovery_run_id)
855        )",
856    )
857    .execute(pool)
858    .await?;
859    sqlx::query(
860        "CREATE TABLE IF NOT EXISTS scheduled_recovery_paused_schedules (
861            schedule_id TEXT PRIMARY KEY REFERENCES goal_schedules(id) ON DELETE CASCADE,
862            goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
863            paused_at TEXT NOT NULL
864        )",
865    )
866    .execute(pool)
867    .await?;
868
869    // Columns on goals added via ALTER for older migrated databases.
870    aidaemon_tools::sqlite_schema::add_column_if_missing(
871        pool,
872        "ALTER TABLE goals ADD COLUMN domain TEXT NOT NULL DEFAULT 'orchestration'",
873    )
874    .await?;
875    aidaemon_tools::sqlite_schema::add_column_if_missing(
876        pool,
877        "ALTER TABLE goals ADD COLUMN tokens_used_day TEXT NOT NULL DEFAULT '1970-01-01'",
878    )
879    .await?;
880    aidaemon_tools::sqlite_schema::add_column_if_missing(
881        pool,
882        "ALTER TABLE goals ADD COLUMN notification_attempts INTEGER NOT NULL DEFAULT 0",
883    )
884    .await?;
885    aidaemon_tools::sqlite_schema::add_column_if_missing(
886        pool,
887        "ALTER TABLE goals ADD COLUMN dispatch_failures INTEGER NOT NULL DEFAULT 0",
888    )
889    .await?;
890    aidaemon_tools::sqlite_schema::add_column_if_missing(
891        pool,
892        "ALTER TABLE goals ADD COLUMN progress_notes TEXT",
893    )
894    .await?;
895    aidaemon_tools::sqlite_schema::add_column_if_missing(
896        pool,
897        "ALTER TABLE goals ADD COLUMN source_episode_id INTEGER",
898    )
899    .await?;
900    aidaemon_tools::sqlite_schema::add_column_if_missing(
901        pool,
902        "ALTER TABLE goals ADD COLUMN legacy_int_id INTEGER",
903    )
904    .await?;
905
906    // Durable collaborative-work model. The default project keeps existing
907    // installations behaviorally unchanged while making project scope explicit.
908    sqlx::query(
909        "CREATE TABLE IF NOT EXISTS work_projects (
910            id TEXT PRIMARY KEY,
911            name TEXT NOT NULL COLLATE NOCASE UNIQUE,
912            description TEXT,
913            created_at TEXT NOT NULL DEFAULT (datetime('now')),
914            updated_at TEXT NOT NULL DEFAULT (datetime('now'))
915        )",
916    )
917    .execute(pool)
918    .await?;
919    // A project's folder (any folder: a repository, a site, designs);
920    // conversations in the project work there.
921    aidaemon_tools::sqlite_schema::add_column_if_missing(
922        pool,
923        "ALTER TABLE work_projects ADD COLUMN path TEXT",
924    )
925    .await?;
926    sqlx::query(
927        "INSERT OR IGNORE INTO work_projects (id, name, description)
928         VALUES ('default', 'Default', 'Default Aidaemon work project')",
929    )
930    .execute(pool)
931    .await?;
932
933    sqlx::query(
934        "CREATE TABLE IF NOT EXISTS session_work_projects (
935            session_id TEXT PRIMARY KEY,
936            project_id TEXT NOT NULL REFERENCES work_projects(id) ON DELETE CASCADE,
937            updated_at TEXT NOT NULL DEFAULT (datetime('now'))
938        )",
939    )
940    .execute(pool)
941    .await?;
942    // The project a chat bot's direct-message chats go to (`channel`: the
943    // bot's session channel, `telegram:coding_bot`).
944    sqlx::query(
945        "CREATE TABLE IF NOT EXISTS channel_work_projects (
946            channel TEXT PRIMARY KEY,
947            project_id TEXT NOT NULL REFERENCES work_projects(id) ON DELETE CASCADE,
948            updated_at TEXT NOT NULL DEFAULT (datetime('now'))
949        )",
950    )
951    .execute(pool)
952    .await?;
953
954    aidaemon_tools::sqlite_schema::add_column_if_missing(
955        pool,
956        "ALTER TABLE goals ADD COLUMN project_id TEXT NOT NULL DEFAULT 'default'",
957    )
958    .await?;
959    sqlx::query(
960        "UPDATE goals SET project_id = 'default' WHERE project_id IS NULL OR project_id = ''",
961    )
962    .execute(pool)
963    .await?;
964
965    sqlx::query(
966        "CREATE TABLE IF NOT EXISTS goal_runs (
967            id TEXT PRIMARY KEY,
968            project_id TEXT NOT NULL REFERENCES work_projects(id) ON DELETE CASCADE,
969            goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
970            trigger_type TEXT NOT NULL,
971            schedule_id TEXT REFERENCES goal_schedules(id) ON DELETE SET NULL,
972            root_task_id TEXT,
973            status TEXT NOT NULL DEFAULT 'running',
974            outcome_summary TEXT,
975            started_at TEXT NOT NULL DEFAULT (datetime('now')),
976            completed_at TEXT,
977            created_at TEXT NOT NULL DEFAULT (datetime('now')),
978            updated_at TEXT NOT NULL DEFAULT (datetime('now'))
979        )",
980    )
981    .execute(pool)
982    .await?;
983
984    // Owner-authorized autonomy. A mandate is intentionally separate from a
985    // personal goal (desire) and from an intention (one agent commitment).
986    // Every decision cycle is bound to exactly one durable goal run.
987    sqlx::query(
988        "CREATE TABLE IF NOT EXISTS mandates (
989            id TEXT PRIMARY KEY,
990            goal_id TEXT NOT NULL UNIQUE REFERENCES goals(id) ON DELETE CASCADE,
991            source_goal_id TEXT REFERENCES goals(id) ON DELETE SET NULL,
992            name TEXT,
993            objective TEXT NOT NULL,
994            status TEXT NOT NULL DEFAULT 'active'
995                CHECK (status IN ('active', 'paused', 'awaiting_input', 'completed', 'cancelled')),
996            autonomy_mode TEXT NOT NULL DEFAULT 'bounded'
997                CHECK (autonomy_mode IN ('bounded', 'autopilot')),
998            authority_json TEXT NOT NULL,
999            strategy_json TEXT,
1000            objective_control_json TEXT,
1001            suspension_json TEXT,
1002            constraints_json TEXT NOT NULL DEFAULT '[]',
1003            success_criteria_json TEXT NOT NULL DEFAULT '[]',
1004            stop_conditions_json TEXT NOT NULL DEFAULT '[]',
1005            min_review_secs INTEGER NOT NULL CHECK (min_review_secs > 0),
1006            max_review_secs INTEGER NOT NULL CHECK (max_review_secs >= min_review_secs),
1007            default_review_secs INTEGER NOT NULL
1008                CHECK (default_review_secs BETWEEN min_review_secs AND max_review_secs),
1009            review_effort TEXT NOT NULL DEFAULT 'balanced'
1010                CHECK (review_effort IN ('efficient', 'balanced', 'thorough', 'legacy_custom')),
1011            next_review_at TEXT NOT NULL,
1012            review_lease_token TEXT,
1013            review_lease_expires_at TEXT,
1014            expires_at TEXT,
1015            confirmed_at TEXT,
1016            version INTEGER NOT NULL DEFAULT 1 CHECK (version > 0),
1017            owner_principal_id TEXT NOT NULL,
1018            created_by_session TEXT NOT NULL,
1019            created_at TEXT NOT NULL DEFAULT (datetime('now')),
1020            updated_at TEXT NOT NULL DEFAULT (datetime('now'))
1021        )",
1022    )
1023    .execute(pool)
1024    .await?;
1025    aidaemon_tools::sqlite_schema::add_column_if_missing(
1026        pool,
1027        "ALTER TABLE mandates ADD COLUMN owner_principal_id TEXT",
1028    )
1029    .await?;
1030    aidaemon_tools::sqlite_schema::add_column_if_missing(
1031        pool,
1032        "ALTER TABLE mandates ADD COLUMN objective_control_json TEXT",
1033    )
1034    .await?;
1035    // The owner-given name (nullable: mandates created before it have none).
1036    aidaemon_tools::sqlite_schema::add_column_if_missing(
1037        pool,
1038        "ALTER TABLE mandates ADD COLUMN name TEXT",
1039    )
1040    .await?;
1041    sqlx::query(
1042        "UPDATE mandates SET owner_principal_id = 'principal:' || id
1043         WHERE owner_principal_id IS NULL OR trim(owner_principal_id) = ''",
1044    )
1045    .execute(pool)
1046    .await?;
1047    sqlx::query(
1048        "CREATE TABLE IF NOT EXISTS mandate_principal_sessions (
1049            principal_id TEXT NOT NULL,
1050            session_id TEXT NOT NULL,
1051            linked_at TEXT NOT NULL,
1052            linked_by_session TEXT NOT NULL,
1053            PRIMARY KEY (principal_id, session_id)
1054        )",
1055    )
1056    .execute(pool)
1057    .await?;
1058    // Links for mandates made before links existed, once
1059    // ([`WORK_BACKFILLS_DONE_VERSION`]): a link taken back must stay gone.
1060    if !work_backfills_done(pool).await? {
1061        sqlx::query(
1062            "INSERT OR IGNORE INTO mandate_principal_sessions
1063                (principal_id, session_id, linked_at, linked_by_session)
1064             SELECT owner_principal_id, created_by_session, created_at, created_by_session
1065             FROM mandates",
1066        )
1067        .execute(pool)
1068        .await?;
1069        // Older mandates were assigned one random principal per mandate. Migrate
1070        // only channel identities whose platform semantics prove they are the
1071        // same private owner across bot routes; never infer group or arbitrary
1072        // session-name equivalence.
1073        let mandate_owner_rows = sqlx::query("SELECT id, created_by_session FROM mandates")
1074            .fetch_all(pool)
1075            .await?;
1076        for row in mandate_owner_rows {
1077            let mandate_id: String = row.get("id");
1078            let created_by_session: String = row.get("created_by_session");
1079            let Some(principal_id) =
1080                aidaemon_events::session::stable_private_owner_principal_id(&created_by_session)
1081            else {
1082                continue;
1083            };
1084            sqlx::query("UPDATE mandates SET owner_principal_id = ? WHERE id = ?")
1085                .bind(&principal_id)
1086                .bind(&mandate_id)
1087                .execute(pool)
1088                .await?;
1089            sqlx::query(
1090                "INSERT OR IGNORE INTO mandate_principal_sessions
1091                    (principal_id, session_id, linked_at, linked_by_session)
1092                 VALUES (?, ?, datetime('now'), ?)",
1093            )
1094            .bind(&principal_id)
1095            .bind(&created_by_session)
1096            .bind(&created_by_session)
1097            .execute(pool)
1098            .await?;
1099        }
1100    }
1101    sqlx::query(
1102        "CREATE INDEX IF NOT EXISTS idx_mandate_principal_sessions_session
1103         ON mandate_principal_sessions(session_id, principal_id)",
1104    )
1105    .execute(pool)
1106    .await?;
1107    sqlx::query(
1108        "CREATE TABLE IF NOT EXISTS mandate_objective_measurements (
1109            id TEXT PRIMARY KEY,
1110            mandate_id TEXT NOT NULL REFERENCES mandates(id) ON DELETE CASCADE,
1111            mandate_version INTEGER NOT NULL CHECK (mandate_version > 0),
1112            goal_run_id TEXT NOT NULL REFERENCES goal_runs(id) ON DELETE CASCADE,
1113            value_micros INTEGER NOT NULL,
1114            confidence_bps INTEGER NOT NULL CHECK (confidence_bps BETWEEN 0 AND 10000),
1115            evidence_receipt_ids_json TEXT NOT NULL,
1116            attributed_intention_ids_json TEXT NOT NULL DEFAULT '[]',
1117            observed_at TEXT NOT NULL,
1118            created_at TEXT NOT NULL,
1119            UNIQUE (mandate_id, goal_run_id, observed_at)
1120        )",
1121    )
1122    .execute(pool)
1123    .await?;
1124    sqlx::query(
1125        "CREATE INDEX IF NOT EXISTS idx_mandate_measurements_recent
1126         ON mandate_objective_measurements(mandate_id, observed_at DESC)",
1127    )
1128    .execute(pool)
1129    .await?;
1130    sqlx::query(
1131        "CREATE TABLE IF NOT EXISTS mandate_ownership_transfers (
1132            id TEXT PRIMARY KEY,
1133            mandate_id TEXT NOT NULL REFERENCES mandates(id) ON DELETE CASCADE,
1134            principal_id TEXT NOT NULL,
1135            from_session_id TEXT NOT NULL,
1136            to_session_id TEXT NOT NULL,
1137            from_version INTEGER NOT NULL,
1138            to_version INTEGER NOT NULL,
1139            transferred_at TEXT NOT NULL
1140        )",
1141    )
1142    .execute(pool)
1143    .await?;
1144    aidaemon_tools::sqlite_schema::add_column_if_missing(
1145        pool,
1146        "ALTER TABLE mandates ADD COLUMN autonomy_mode TEXT NOT NULL DEFAULT 'bounded'
1147         CHECK (autonomy_mode IN ('bounded', 'autopilot'))",
1148    )
1149    .await?;
1150    aidaemon_tools::sqlite_schema::add_column_if_missing(
1151        pool,
1152        "ALTER TABLE mandates ADD COLUMN review_effort TEXT NOT NULL DEFAULT 'balanced'
1153         CHECK (review_effort IN ('efficient', 'balanced', 'thorough', 'legacy_custom'))",
1154    )
1155    .await?;
1156
1157    // One immutable aggregate budget per autonomous decision cycle. The
1158    // short-lived call lease serializes lead/executor model calls so they
1159    // cannot each observe the same remaining balance and overspend in
1160    // parallel. Usage survives daemon restarts and is never auto-extended.
1161    sqlx::query(
1162        "CREATE TABLE IF NOT EXISTS mandate_run_token_budgets (
1163            goal_run_id TEXT PRIMARY KEY REFERENCES goal_runs(id) ON DELETE CASCADE,
1164            budget_per_cycle INTEGER NOT NULL CHECK (budget_per_cycle > 0),
1165            tokens_used INTEGER NOT NULL DEFAULT 0 CHECK (tokens_used >= 0),
1166            call_lease_token TEXT,
1167            call_lease_expires_at TEXT,
1168            call_dispatched INTEGER NOT NULL DEFAULT 0 CHECK (call_dispatched IN (0, 1)),
1169            call_tokens_used_before INTEGER,
1170            created_at TEXT NOT NULL DEFAULT (datetime('now')),
1171            updated_at TEXT NOT NULL DEFAULT (datetime('now')),
1172            CHECK (
1173                (call_lease_token IS NULL AND call_lease_expires_at IS NULL
1174                    AND call_dispatched = 0 AND call_tokens_used_before IS NULL)
1175                OR (call_lease_token IS NOT NULL AND call_lease_expires_at IS NOT NULL
1176                    AND ((call_dispatched = 0 AND call_tokens_used_before IS NULL)
1177                         OR (call_dispatched = 1 AND call_tokens_used_before IS NOT NULL)))
1178            )
1179        )",
1180    )
1181    .execute(pool)
1182    .await?;
1183    aidaemon_tools::sqlite_schema::add_column_if_missing(
1184        pool,
1185        "ALTER TABLE mandate_run_token_budgets
1186         ADD COLUMN call_dispatched INTEGER NOT NULL DEFAULT 0 CHECK (call_dispatched IN (0, 1))",
1187    )
1188    .await?;
1189    aidaemon_tools::sqlite_schema::add_column_if_missing(
1190        pool,
1191        "ALTER TABLE mandate_run_token_budgets ADD COLUMN call_tokens_used_before INTEGER",
1192    )
1193    .await?;
1194
1195    sqlx::query(
1196        "CREATE TABLE IF NOT EXISTS mandate_decision_cycles (
1197            id TEXT PRIMARY KEY,
1198            mandate_id TEXT NOT NULL REFERENCES mandates(id) ON DELETE CASCADE,
1199            goal_run_id TEXT NOT NULL UNIQUE REFERENCES goal_runs(id) ON DELETE CASCADE,
1200            mandate_version INTEGER NOT NULL,
1201            outcome TEXT NOT NULL CHECK (outcome IN ('act', 'wait', 'ask', 'stop')),
1202            origin TEXT NOT NULL DEFAULT 'deliberator'
1203                CHECK (origin IN ('deliberator', 'runtime_fallback')),
1204            activity_level TEXT NOT NULL DEFAULT 'quiet'
1205                CHECK (activity_level IN ('quiet', 'active', 'urgent')),
1206            rationale TEXT NOT NULL,
1207            belief_snapshot TEXT,
1208            evidence_receipt_ids_json TEXT NOT NULL DEFAULT '[]'
1209                CHECK (json_valid(evidence_receipt_ids_json)),
1210            question TEXT,
1211            termination_kind TEXT
1212                CHECK (termination_kind IS NULL OR termination_kind IN (
1213                    'success_criteria_satisfied', 'stop_condition_met', 'safety_termination'
1214                )),
1215            termination_match TEXT,
1216            reconsider_at TEXT,
1217            action_attempts INTEGER NOT NULL DEFAULT 0 CHECK (action_attempts >= 0),
1218            created_at TEXT NOT NULL DEFAULT (datetime('now')),
1219            updated_at TEXT NOT NULL DEFAULT (datetime('now'))
1220        )",
1221    )
1222    .execute(pool)
1223    .await?;
1224
1225    aidaemon_tools::sqlite_schema::add_column_if_missing(
1226        pool,
1227        "ALTER TABLE mandate_decision_cycles ADD COLUMN owner_alert TEXT",
1228    )
1229    .await?;
1230
1231    // Pre-release development databases may already contain the first mandate
1232    // draft. Keep startup migration idempotent while backfilling the durable
1233    // wake/lease and policy-version columns added before the first release.
1234    aidaemon_tools::sqlite_schema::add_column_if_missing(
1235        pool,
1236        "ALTER TABLE mandates ADD COLUMN next_review_at TEXT",
1237    )
1238    .await?;
1239    aidaemon_tools::sqlite_schema::add_column_if_missing(
1240        pool,
1241        "ALTER TABLE mandates ADD COLUMN review_lease_token TEXT",
1242    )
1243    .await?;
1244    aidaemon_tools::sqlite_schema::add_column_if_missing(
1245        pool,
1246        "ALTER TABLE mandates ADD COLUMN review_lease_expires_at TEXT",
1247    )
1248    .await?;
1249    aidaemon_tools::sqlite_schema::add_column_if_missing(
1250        pool,
1251        "ALTER TABLE mandates ADD COLUMN confirmed_at TEXT",
1252    )
1253    .await?;
1254    aidaemon_tools::sqlite_schema::add_column_if_missing(
1255        pool,
1256        "ALTER TABLE mandates ADD COLUMN strategy_json TEXT",
1257    )
1258    .await?;
1259    aidaemon_tools::sqlite_schema::add_column_if_missing(
1260        pool,
1261        "ALTER TABLE mandates ADD COLUMN suspension_json TEXT",
1262    )
1263    .await?;
1264    aidaemon_tools::sqlite_schema::add_column_if_missing(
1265        pool,
1266        "ALTER TABLE mandate_decision_cycles
1267         ADD COLUMN evidence_receipt_ids_json TEXT NOT NULL DEFAULT '[]'",
1268    )
1269    .await?;
1270    aidaemon_tools::sqlite_schema::add_column_if_missing(
1271        pool,
1272        "ALTER TABLE mandate_decision_cycles
1273         ADD COLUMN activity_level TEXT NOT NULL DEFAULT 'quiet'
1274         CHECK (activity_level IN ('quiet', 'active', 'urgent'))",
1275    )
1276    .await?;
1277    // Who wrote a decision was once read from its rationale text; existing
1278    // runtime-written rows are recognised by the two texts the runtime used.
1279    let origin_added = aidaemon_tools::sqlite_schema::add_column_if_missing(
1280        pool,
1281        "ALTER TABLE mandate_decision_cycles
1282         ADD COLUMN origin TEXT NOT NULL DEFAULT 'deliberator'
1283         CHECK (origin IN ('deliberator', 'runtime_fallback'))",
1284    )
1285    .await?;
1286    if origin_added {
1287        sqlx::query(
1288            "UPDATE mandate_decision_cycles SET origin = 'runtime_fallback'
1289             WHERE rationale IN (?, ?)",
1290        )
1291        .bind(crate::mandates::SAFE_FALLBACK_WAIT_RATIONALE)
1292        .bind(
1293            "This review reached its internal runaway-protection ceiling before another model \
1294             turn could be admitted. No new action was authorized; the controller will retry \
1295             automatically at the earliest bounded review time.",
1296        )
1297        .execute(pool)
1298        .await?;
1299    }
1300    aidaemon_tools::sqlite_schema::add_column_if_missing(
1301        pool,
1302        "ALTER TABLE mandate_decision_cycles ADD COLUMN termination_kind TEXT",
1303    )
1304    .await?;
1305    aidaemon_tools::sqlite_schema::add_column_if_missing(
1306        pool,
1307        "ALTER TABLE mandate_decision_cycles ADD COLUMN termination_match TEXT",
1308    )
1309    .await?;
1310    sqlx::query(
1311        "UPDATE mandates
1312         SET next_review_at = COALESCE(next_review_at, updated_at, created_at, datetime('now'))",
1313    )
1314    .execute(pool)
1315    .await?;
1316    // Backfill only states that could have been reached after confirmation in
1317    // the pre-release schema. A paused mandate whose controller is still
1318    // pending confirmation deliberately remains unconfirmed, as do cancelled
1319    // records where provenance can no longer be inferred safely.
1320    sqlx::query(
1321        "UPDATE mandates
1322         SET confirmed_at = COALESCE(confirmed_at, created_at, updated_at, datetime('now'))
1323         WHERE confirmed_at IS NULL
1324           AND (
1325               status IN ('active', 'awaiting_input', 'completed')
1326               OR (
1327                   status = 'paused'
1328                   AND EXISTS (
1329                       SELECT 1 FROM goals g
1330                       WHERE g.id = mandates.goal_id AND g.status = 'paused'
1331                   )
1332               )
1333           )",
1334    )
1335    .execute(pool)
1336    .await?;
1337    sqlx::query(
1338        "UPDATE mandates
1339         SET suspension_json = json_object(
1340             'kind', CASE WHEN status = 'paused' THEN 'owner_paused' ELSE 'review_failed' END,
1341             'reason_code', 'legacy_state_backfill',
1342             'created_at', COALESCE(updated_at, created_at, datetime('now'))
1343         )
1344         WHERE suspension_json IS NULL
1345           AND confirmed_at IS NOT NULL
1346           AND status IN ('paused', 'awaiting_input')",
1347    )
1348    .execute(pool)
1349    .await?;
1350    let added_mandate_version = aidaemon_tools::sqlite_schema::add_column_if_missing(
1351        pool,
1352        "ALTER TABLE mandate_decision_cycles
1353         ADD COLUMN mandate_version INTEGER NOT NULL DEFAULT 1",
1354    )
1355    .await?;
1356    if added_mandate_version {
1357        sqlx::query(
1358            "UPDATE mandate_decision_cycles
1359             SET mandate_version = COALESCE(
1360                 (SELECT m.version FROM mandates m
1361                  WHERE m.id = mandate_decision_cycles.mandate_id),
1362                 mandate_version
1363             )",
1364        )
1365        .execute(pool)
1366        .await?;
1367    }
1368
1369    sqlx::query(
1370        "CREATE TABLE IF NOT EXISTS intentions (
1371            id TEXT PRIMARY KEY,
1372            mandate_id TEXT NOT NULL REFERENCES mandates(id) ON DELETE CASCADE,
1373            decision_cycle_id TEXT NOT NULL UNIQUE REFERENCES mandate_decision_cycles(id) ON DELETE CASCADE,
1374            goal_run_id TEXT NOT NULL REFERENCES goal_runs(id) ON DELETE CASCADE,
1375            description TEXT NOT NULL,
1376            rationale TEXT NOT NULL,
1377            value_criterion TEXT,
1378            expected_benefit TEXT,
1379            risk TEXT,
1380            invalidation_criteria TEXT,
1381            format_key TEXT,
1382            status TEXT NOT NULL DEFAULT 'committed',
1383            created_at TEXT NOT NULL DEFAULT (datetime('now')),
1384            updated_at TEXT NOT NULL DEFAULT (datetime('now')),
1385            completed_at TEXT
1386        )",
1387    )
1388    .execute(pool)
1389    .await?;
1390    // Existing installations may have the pre-value-contract intentions
1391    // table. Historical rows remain nullable and readable; every new
1392    // value-contract ACT is validated before insertion.
1393    aidaemon_tools::sqlite_schema::add_column_if_missing(
1394        pool,
1395        "ALTER TABLE intentions ADD COLUMN value_criterion TEXT",
1396    )
1397    .await?;
1398    // The canonical format an ACT declared (`[a-z0-9_-]{1,64}`), so outcomes
1399    // can be grouped by format. Older rows stay NULL ("untagged").
1400    aidaemon_tools::sqlite_schema::add_column_if_missing(
1401        pool,
1402        "ALTER TABLE intentions ADD COLUMN format_key TEXT",
1403    )
1404    .await?;
1405
1406    sqlx::query(
1407        "CREATE TABLE IF NOT EXISTS mandate_learning_notes (
1408            id TEXT PRIMARY KEY,
1409            mandate_id TEXT NOT NULL REFERENCES mandates(id) ON DELETE CASCADE,
1410            mandate_version INTEGER NOT NULL CHECK (mandate_version > 0),
1411            learned_in_decision_cycle_id TEXT NOT NULL
1412                REFERENCES mandate_decision_cycles(id) ON DELETE CASCADE,
1413            summary TEXT NOT NULL,
1414            evidence_receipt_ids_json TEXT NOT NULL CHECK (json_valid(evidence_receipt_ids_json)),
1415            created_at TEXT NOT NULL,
1416            UNIQUE(mandate_id, learned_in_decision_cycle_id, summary)
1417        )",
1418    )
1419    .execute(pool)
1420    .await?;
1421    sqlx::query(
1422        "CREATE INDEX IF NOT EXISTS idx_mandate_learning_notes_recent
1423         ON mandate_learning_notes(mandate_id, created_at DESC)",
1424    )
1425    .execute(pool)
1426    .await?;
1427
1428    // Append-only adaptive operating-strategy revisions. They are deliberately
1429    // separate from the owner-confirmed mandate policy and therefore cannot
1430    // grant authority. The latest revision for one key is its current node.
1431    sqlx::query(
1432        "CREATE TABLE IF NOT EXISTS mandate_strategy_revisions (
1433            id TEXT PRIMARY KEY,
1434            mandate_id TEXT NOT NULL REFERENCES mandates(id) ON DELETE CASCADE,
1435            mandate_version INTEGER NOT NULL CHECK (mandate_version > 0),
1436            decision_cycle_id TEXT NOT NULL
1437                REFERENCES mandate_decision_cycles(id) ON DELETE CASCADE,
1438            strategy_key TEXT NOT NULL,
1439            kind TEXT NOT NULL CHECK (kind IN ('reinforce', 'explore', 'avoid', 'retire')),
1440            guidance TEXT NOT NULL,
1441            confidence_bps INTEGER NOT NULL CHECK (confidence_bps BETWEEN 0 AND 10000),
1442            evidence_receipt_ids_json TEXT NOT NULL CHECK (json_valid(evidence_receipt_ids_json)),
1443            created_at TEXT NOT NULL,
1444            UNIQUE(decision_cycle_id, strategy_key)
1445        )",
1446    )
1447    .execute(pool)
1448    .await?;
1449    sqlx::query(
1450        "CREATE INDEX IF NOT EXISTS idx_mandate_strategy_revisions_latest
1451         ON mandate_strategy_revisions(mandate_id, strategy_key, created_at DESC, id DESC)",
1452    )
1453    .execute(pool)
1454    .await?;
1455
1456    // Content-free, deduplicated wake receipts for structured external signals.
1457    // Raw webhook bodies never enter this table or the mandate prompt.
1458    sqlx::query(
1459        "CREATE TABLE IF NOT EXISTS mandate_wake_signals (
1460            mandate_id TEXT NOT NULL REFERENCES mandates(id) ON DELETE CASCADE,
1461            mandate_version INTEGER NOT NULL CHECK (mandate_version > 0),
1462            signal_digest TEXT NOT NULL,
1463            kind TEXT NOT NULL CHECK (kind IN (
1464                'mention', 'reply', 'reaction', 'metric_change',
1465                'delivery_failure', 'external_change'
1466            )),
1467            source TEXT NOT NULL,
1468            target_url TEXT NOT NULL,
1469            account_id TEXT,
1470            occurred_at TEXT NOT NULL,
1471            received_at TEXT NOT NULL,
1472            PRIMARY KEY(mandate_id, signal_digest)
1473        )",
1474    )
1475    .execute(pool)
1476    .await?;
1477    sqlx::query(
1478        "CREATE INDEX IF NOT EXISTS idx_mandate_wake_signals_recent
1479         ON mandate_wake_signals(mandate_id, received_at DESC)",
1480    )
1481    .execute(pool)
1482    .await?;
1483
1484    sqlx::query(
1485        "CREATE TABLE IF NOT EXISTS mandate_reconciliations (
1486            id TEXT PRIMARY KEY,
1487            mandate_id TEXT NOT NULL REFERENCES mandates(id) ON DELETE CASCADE,
1488            suspended_version INTEGER NOT NULL CHECK (suspended_version > 0),
1489            suspension_kind TEXT NOT NULL,
1490            resolution TEXT NOT NULL CHECK (resolution IN (
1491                'confirmed_effect_occurred', 'confirmed_no_effect', 'abandon_attempt'
1492            )),
1493            owner_guidance TEXT NOT NULL,
1494            resolved_by_session TEXT NOT NULL,
1495            resolved_at TEXT NOT NULL
1496        )",
1497    )
1498    .execute(pool)
1499    .await?;
1500
1501    // Cross-cycle mutation safety ledger. This table intentionally contains
1502    // only typed identifiers and compact execution facts; raw tool arguments,
1503    // bodies, outputs, errors, and credentials belong nowhere in this ledger.
1504    sqlx::query(
1505        "CREATE TABLE IF NOT EXISTS mandate_mutation_attempts (
1506            id TEXT PRIMARY KEY,
1507            mandate_id TEXT NOT NULL REFERENCES mandates(id) ON DELETE CASCADE,
1508            mandate_version INTEGER NOT NULL CHECK (mandate_version > 0),
1509            decision_cycle_id TEXT NOT NULL REFERENCES mandate_decision_cycles(id) ON DELETE CASCADE,
1510            goal_run_id TEXT NOT NULL REFERENCES goal_runs(id) ON DELETE CASCADE,
1511            intention_id TEXT NOT NULL REFERENCES intentions(id) ON DELETE CASCADE,
1512            root_task_id TEXT NOT NULL,
1513            root_task_attempt_id TEXT NOT NULL,
1514            task_id TEXT NOT NULL,
1515            task_attempt_id TEXT NOT NULL,
1516            reserved_action_attempt INTEGER NOT NULL CHECK (reserved_action_attempt > 0),
1517            action_digest TEXT NOT NULL UNIQUE CHECK (length(action_digest) = 64),
1518            tool_call_id TEXT NOT NULL UNIQUE,
1519            tool_name TEXT NOT NULL,
1520            mutation_effects_json TEXT NOT NULL CHECK (json_valid(mutation_effects_json)),
1521            targets_json TEXT NOT NULL CHECK (json_valid(targets_json)),
1522            account_identifiers_json TEXT NOT NULL CHECK (json_valid(account_identifiers_json)),
1523            status TEXT NOT NULL DEFAULT 'reserved'
1524                CHECK (status IN ('reserved', 'never_dispatched', 'succeeded', 'failed', 'ambiguous')),
1525            outcome_evidence TEXT
1526                CHECK (outcome_evidence IS NULL OR outcome_evidence IN ('tool_reported', 'structured_metadata')),
1527            http_status INTEGER CHECK (http_status IS NULL OR http_status BETWEEN 100 AND 599),
1528            exit_code INTEGER,
1529            external_resource_id TEXT,
1530            reserved_at TEXT NOT NULL,
1531            dispatch_claimed_at TEXT,
1532            completed_at TEXT,
1533            UNIQUE (decision_cycle_id, reserved_action_attempt)
1534        )",
1535    )
1536    .execute(pool)
1537    .await?;
1538    // Development and upgrade databases may already have the v1 ledger from
1539    // an earlier build. Duplicate-column is the expected no-op on fresh/newer
1540    // schemas; a successful ALTER upgrades the old table in place.
1541    let _added_dispatch_claim = aidaemon_tools::sqlite_schema::add_column_if_missing(
1542        pool,
1543        "ALTER TABLE mandate_mutation_attempts
1544         ADD COLUMN dispatch_claimed_at TEXT",
1545    )
1546    .await?;
1547
1548    // SQLite cannot widen an inline CHECK constraint in place. Rebuild the
1549    // pre-release ledger once so invalidated reservations that never crossed
1550    // the final dispatcher boundary can be closed without misclassifying them
1551    // as an ambiguous external effect.
1552    let mutation_attempts_schema = sqlx::query(
1553        "SELECT sql FROM sqlite_master
1554         WHERE type = 'table' AND name = 'mandate_mutation_attempts'",
1555    )
1556    .fetch_optional(pool)
1557    .await?
1558    .and_then(|row| row.try_get::<Option<String>, _>("sql").ok().flatten())
1559    .unwrap_or_default();
1560    if !mutation_attempts_schema.contains("never_dispatched") {
1561        let mut tx = pool.begin_with("BEGIN IMMEDIATE").await?;
1562        sqlx::query("DROP TABLE IF EXISTS mandate_mutation_attempts_v2")
1563            .execute(&mut *tx)
1564            .await?;
1565        sqlx::query(
1566            "CREATE TABLE mandate_mutation_attempts_v2 (
1567                id TEXT PRIMARY KEY,
1568                mandate_id TEXT NOT NULL REFERENCES mandates(id) ON DELETE CASCADE,
1569                mandate_version INTEGER NOT NULL CHECK (mandate_version > 0),
1570                decision_cycle_id TEXT NOT NULL REFERENCES mandate_decision_cycles(id) ON DELETE CASCADE,
1571                goal_run_id TEXT NOT NULL REFERENCES goal_runs(id) ON DELETE CASCADE,
1572                intention_id TEXT NOT NULL REFERENCES intentions(id) ON DELETE CASCADE,
1573                root_task_id TEXT NOT NULL,
1574                root_task_attempt_id TEXT NOT NULL,
1575                task_id TEXT NOT NULL,
1576                task_attempt_id TEXT NOT NULL,
1577                reserved_action_attempt INTEGER NOT NULL CHECK (reserved_action_attempt > 0),
1578                action_digest TEXT NOT NULL UNIQUE CHECK (length(action_digest) = 64),
1579                tool_call_id TEXT NOT NULL UNIQUE,
1580                tool_name TEXT NOT NULL,
1581                mutation_effects_json TEXT NOT NULL CHECK (json_valid(mutation_effects_json)),
1582                targets_json TEXT NOT NULL CHECK (json_valid(targets_json)),
1583                account_identifiers_json TEXT NOT NULL CHECK (json_valid(account_identifiers_json)),
1584                status TEXT NOT NULL DEFAULT 'reserved'
1585                    CHECK (status IN ('reserved', 'never_dispatched', 'succeeded', 'failed', 'ambiguous')),
1586                outcome_evidence TEXT
1587                    CHECK (outcome_evidence IS NULL OR outcome_evidence IN ('tool_reported', 'structured_metadata')),
1588                http_status INTEGER CHECK (http_status IS NULL OR http_status BETWEEN 100 AND 599),
1589                exit_code INTEGER,
1590                reserved_at TEXT NOT NULL,
1591                dispatch_claimed_at TEXT,
1592                completed_at TEXT,
1593                UNIQUE (decision_cycle_id, reserved_action_attempt)
1594            )",
1595        )
1596        .execute(&mut *tx)
1597        .await?;
1598        sqlx::query(
1599            "INSERT INTO mandate_mutation_attempts_v2
1600                (id, mandate_id, mandate_version, decision_cycle_id, goal_run_id,
1601                 intention_id, root_task_id, root_task_attempt_id, task_id,
1602                 task_attempt_id, reserved_action_attempt, action_digest,
1603                 tool_call_id, tool_name, mutation_effects_json, targets_json,
1604                 account_identifiers_json, status, outcome_evidence, http_status,
1605                 exit_code, reserved_at, dispatch_claimed_at, completed_at)
1606             SELECT id, mandate_id, mandate_version, decision_cycle_id, goal_run_id,
1607                    intention_id, root_task_id, root_task_attempt_id, task_id,
1608                    task_attempt_id, reserved_action_attempt, action_digest,
1609                    tool_call_id, tool_name, mutation_effects_json, targets_json,
1610                    account_identifiers_json, status, outcome_evidence, http_status,
1611                    exit_code, reserved_at, dispatch_claimed_at, completed_at
1612             FROM mandate_mutation_attempts",
1613        )
1614        .execute(&mut *tx)
1615        .await?;
1616        sqlx::query("DROP TABLE mandate_mutation_attempts")
1617            .execute(&mut *tx)
1618            .await?;
1619        sqlx::query("ALTER TABLE mandate_mutation_attempts_v2 RENAME TO mandate_mutation_attempts")
1620            .execute(&mut *tx)
1621            .await?;
1622        tx.commit().await?;
1623    }
1624    // The canonical id of the resource a strictly successful mutation
1625    // created, projected from its receipt by the event store. Added after
1626    // the rebuild above so an upgraded ledger gets it too.
1627    aidaemon_tools::sqlite_schema::add_column_if_missing(
1628        pool,
1629        "ALTER TABLE mandate_mutation_attempts ADD COLUMN external_resource_id TEXT",
1630    )
1631    .await?;
1632
1633    // Runtime-validated per-action outcomes: a later review reads a
1634    // published resource's public counts and records them against the
1635    // succeeded mutation that created it. Only ids and counts, never text.
1636    sqlx::query(
1637        "CREATE TABLE IF NOT EXISTS mandate_action_outcomes (
1638            id TEXT PRIMARY KEY,
1639            mandate_id TEXT NOT NULL REFERENCES mandates(id) ON DELETE CASCADE,
1640            mandate_version INTEGER NOT NULL CHECK (mandate_version > 0),
1641            decision_cycle_id TEXT NOT NULL REFERENCES mandate_decision_cycles(id) ON DELETE CASCADE,
1642            external_resource_id TEXT NOT NULL,
1643            format_key TEXT,
1644            engagements_micros INTEGER NOT NULL CHECK (engagements_micros >= 0),
1645            impressions INTEGER CHECK (impressions IS NULL OR impressions >= 0),
1646            evidence_receipt_ids_json TEXT NOT NULL CHECK (json_valid(evidence_receipt_ids_json)),
1647            observed_at TEXT NOT NULL,
1648            created_at TEXT NOT NULL,
1649            UNIQUE(mandate_id, external_resource_id, decision_cycle_id)
1650        )",
1651    )
1652    .execute(pool)
1653    .await?;
1654    sqlx::query(
1655        "CREATE INDEX IF NOT EXISTS idx_mandate_action_outcomes_recent
1656         ON mandate_action_outcomes(mandate_id, observed_at DESC)",
1657    )
1658    .execute(pool)
1659    .await?;
1660
1661    sqlx::query(
1662        "CREATE INDEX IF NOT EXISTS idx_mandates_due
1663         ON mandates(status, next_review_at, review_lease_expires_at)",
1664    )
1665    .execute(pool)
1666    .await?;
1667    sqlx::query(
1668        "CREATE INDEX IF NOT EXISTS idx_mandate_cycles_mandate
1669         ON mandate_decision_cycles(mandate_id, created_at DESC)",
1670    )
1671    .execute(pool)
1672    .await?;
1673    sqlx::query(
1674        "CREATE INDEX IF NOT EXISTS idx_intentions_mandate
1675         ON intentions(mandate_id, created_at DESC)",
1676    )
1677    .execute(pool)
1678    .await?;
1679    sqlx::query(
1680        "CREATE INDEX IF NOT EXISTS idx_mandate_mutations_quota
1681         ON mandate_mutation_attempts(mandate_id, reserved_at)",
1682    )
1683    .execute(pool)
1684    .await?;
1685    sqlx::query(
1686        "CREATE INDEX IF NOT EXISTS idx_mandate_mutations_run_status
1687         ON mandate_mutation_attempts(goal_run_id, status)",
1688    )
1689    .execute(pool)
1690    .await?;
1691
1692    aidaemon_tools::sqlite_schema::add_column_if_missing(
1693        pool,
1694        "ALTER TABLE tasks ADD COLUMN goal_run_id TEXT",
1695    )
1696    .await?;
1697    aidaemon_tools::sqlite_schema::add_column_if_missing(
1698        pool,
1699        "ALTER TABLE tasks ADD COLUMN current_attempt_id TEXT",
1700    )
1701    .await?;
1702    aidaemon_tools::sqlite_schema::add_column_if_missing(
1703        pool,
1704        "ALTER TABLE tasks ADD COLUMN worker_profile_id TEXT",
1705    )
1706    .await?;
1707    aidaemon_tools::sqlite_schema::add_column_if_missing(
1708        pool,
1709        "ALTER TABLE tasks ADD COLUMN workspace_policy TEXT NOT NULL DEFAULT 'shared'",
1710    )
1711    .await?;
1712    aidaemon_tools::sqlite_schema::add_column_if_missing(
1713        pool,
1714        "ALTER TABLE tasks ADD COLUMN workspace_policy_explicit INTEGER NOT NULL DEFAULT 0",
1715    )
1716    .await?;
1717    aidaemon_tools::sqlite_schema::add_column_if_missing(
1718        pool,
1719        "ALTER TABLE tasks ADD COLUMN task_kind TEXT NOT NULL DEFAULT 'work'",
1720    )
1721    .await?;
1722    aidaemon_tools::sqlite_schema::add_column_if_missing(
1723        pool,
1724        "ALTER TABLE tasks ADD COLUMN visibility TEXT NOT NULL DEFAULT 'internal'",
1725    )
1726    .await?;
1727    aidaemon_tools::sqlite_schema::add_column_if_missing(
1728        pool,
1729        "ALTER TABLE tasks ADD COLUMN version INTEGER NOT NULL DEFAULT 0",
1730    )
1731    .await?;
1732    aidaemon_tools::sqlite_schema::add_column_if_missing(
1733        pool,
1734        "ALTER TABLE tasks ADD COLUMN updated_at TEXT",
1735    )
1736    .await?;
1737    sqlx::query(
1738        "UPDATE tasks
1739         SET updated_at = COALESCE(updated_at, completed_at, started_at, created_at)",
1740    )
1741    .execute(pool)
1742    .await?;
1743
1744    sqlx::query(
1745        "CREATE TABLE IF NOT EXISTS worker_profiles (
1746            id TEXT PRIMARY KEY,
1747            project_id TEXT REFERENCES work_projects(id) ON DELETE CASCADE,
1748            name TEXT NOT NULL,
1749            specialist TEXT NOT NULL,
1750            model TEXT,
1751            tools_json TEXT,
1752            max_iterations INTEGER,
1753            tool_budget INTEGER,
1754            timeout_secs INTEGER,
1755            max_concurrency INTEGER NOT NULL DEFAULT 1 CHECK (max_concurrency > 0),
1756            workspace_policy TEXT NOT NULL DEFAULT 'shared',
1757            memory_scope TEXT NOT NULL DEFAULT 'project',
1758            version INTEGER NOT NULL DEFAULT 1,
1759            enabled INTEGER NOT NULL DEFAULT 1,
1760            created_at TEXT NOT NULL DEFAULT (datetime('now')),
1761            updated_at TEXT NOT NULL DEFAULT (datetime('now')),
1762            UNIQUE(project_id, name)
1763        )",
1764    )
1765    .execute(pool)
1766    .await?;
1767
1768    for (id, name, max_concurrency, workspace_policy) in [
1769        ("profile-task-lead", "task_lead", 2_i64, "shared"),
1770        ("profile-executor", "executor", 4_i64, "shared"),
1771        ("profile-research", "research", 4_i64, "shared"),
1772        (
1773            "profile-artifact-writer",
1774            "artifact_writer",
1775            2_i64,
1776            "shared",
1777        ),
1778        ("profile-code", "code", 2_i64, "shared"),
1779        (
1780            "profile-browser-verifier",
1781            "browser_verifier",
1782            2_i64,
1783            "shared",
1784        ),
1785        ("profile-review", "review", 2_i64, "shared"),
1786        ("profile-comms-draft", "comms_draft", 2_i64, "shared"),
1787        ("profile-generic", "generic", 2_i64, "shared"),
1788    ] {
1789        sqlx::query(
1790            "INSERT OR IGNORE INTO worker_profiles
1791                (id, project_id, name, specialist, max_concurrency, workspace_policy)
1792             VALUES (?, NULL, ?, ?, ?, ?)",
1793        )
1794        .bind(id)
1795        .bind(name)
1796        .bind(name)
1797        .bind(max_concurrency)
1798        .bind(workspace_policy)
1799        .execute(pool)
1800        .await?;
1801    }
1802
1803    sqlx::query(
1804        "CREATE TABLE IF NOT EXISTS task_attempts (
1805            id TEXT PRIMARY KEY,
1806            task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
1807            goal_run_id TEXT NOT NULL REFERENCES goal_runs(id) ON DELETE CASCADE,
1808            worker_profile_id TEXT REFERENCES worker_profiles(id) ON DELETE SET NULL,
1809            worker_instance_id TEXT NOT NULL,
1810            lease_token TEXT NOT NULL UNIQUE,
1811            status TEXT NOT NULL,
1812            lease_expires_at TEXT NOT NULL,
1813            last_heartbeat_at TEXT NOT NULL,
1814            workspace_id TEXT,
1815            started_at TEXT NOT NULL,
1816            completed_at TEXT
1817        )",
1818    )
1819    .execute(pool)
1820    .await?;
1821
1822    sqlx::query(
1823        "CREATE TABLE IF NOT EXISTS task_journal (
1824            id TEXT PRIMARY KEY,
1825            project_id TEXT NOT NULL REFERENCES work_projects(id) ON DELETE CASCADE,
1826            goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
1827            goal_run_id TEXT NOT NULL REFERENCES goal_runs(id) ON DELETE CASCADE,
1828            task_id TEXT REFERENCES tasks(id) ON DELETE CASCADE,
1829            attempt_id TEXT REFERENCES task_attempts(id) ON DELETE SET NULL,
1830            entry_type TEXT NOT NULL,
1831            actor_type TEXT NOT NULL,
1832            actor_id TEXT NOT NULL,
1833            source_channel TEXT,
1834            body TEXT NOT NULL,
1835            payload TEXT,
1836            created_at TEXT NOT NULL DEFAULT (datetime('now'))
1837        )",
1838    )
1839    .execute(pool)
1840    .await?;
1841
1842    sqlx::query(
1843        "CREATE TABLE IF NOT EXISTS task_handoffs (
1844            id TEXT PRIMARY KEY,
1845            task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
1846            attempt_id TEXT NOT NULL REFERENCES task_attempts(id) ON DELETE CASCADE,
1847            summary TEXT NOT NULL,
1848            artifacts_json TEXT NOT NULL DEFAULT '[]',
1849            verification_json TEXT NOT NULL DEFAULT '[]',
1850            remaining_risk TEXT,
1851            next_step TEXT,
1852            created_at TEXT NOT NULL DEFAULT (datetime('now'))
1853        )",
1854    )
1855    .execute(pool)
1856    .await?;
1857
1858    sqlx::query(
1859        "CREATE TABLE IF NOT EXISTS task_workspaces (
1860            id TEXT PRIMARY KEY,
1861            task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
1862            attempt_id TEXT NOT NULL REFERENCES task_attempts(id) ON DELETE CASCADE,
1863            backend_id TEXT NOT NULL,
1864            policy TEXT NOT NULL,
1865            root_path TEXT NOT NULL,
1866            branch_name TEXT,
1867            base_ref TEXT,
1868            head_ref TEXT,
1869            status TEXT NOT NULL,
1870            created_at TEXT NOT NULL DEFAULT (datetime('now')),
1871            released_at TEXT
1872        )",
1873    )
1874    .execute(pool)
1875    .await?;
1876
1877    sqlx::query(
1878        "CREATE TABLE IF NOT EXISTS work_channel_links (
1879            goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
1880            channel_session_id TEXT NOT NULL,
1881            thread_ref TEXT,
1882            created_at TEXT NOT NULL DEFAULT (datetime('now')),
1883            updated_at TEXT NOT NULL DEFAULT (datetime('now')),
1884            PRIMARY KEY (goal_id, channel_session_id)
1885        )",
1886    )
1887    .execute(pool)
1888    .await?;
1889
1890    // Episode analysis historically inserted inferred goal mentions without a
1891    // domain, so the orchestration default made them executable work. Reclassify
1892    // only rows that still have no task or schedule evidence; preserve them as
1893    // inert personal observations for audit and possible later confirmation.
1894    sqlx::query(
1895        "UPDATE goals
1896         SET domain = 'personal',
1897             status = CASE
1898                 WHEN status IN ('active', 'pending', 'pending_confirmation')
1899                 THEN 'observed'
1900                 ELSE status
1901             END,
1902             updated_at = datetime('now')
1903         WHERE domain = 'orchestration'
1904           AND source_episode_id IS NOT NULL
1905           AND NOT EXISTS (SELECT 1 FROM tasks t WHERE t.goal_id = goals.id)
1906           AND NOT EXISTS (SELECT 1 FROM goal_schedules s WHERE s.goal_id = goals.id)",
1907    )
1908    .execute(pool)
1909    .await?;
1910
1911    sqlx::query(
1912        "DELETE FROM work_channel_links
1913         WHERE goal_id IN (
1914             SELECT id FROM goals
1915             WHERE domain = 'personal' AND source_episode_id IS NOT NULL
1916         )",
1917    )
1918    .execute(pool)
1919    .await?;
1920
1921    sqlx::query(
1922        "UPDATE goal_runs
1923         SET status = 'cancelled',
1924             outcome_summary = COALESCE(
1925                 outcome_summary,
1926                 'Reclassified as a non-executable personal observation'
1927             ),
1928             completed_at = COALESCE(completed_at, datetime('now')),
1929             updated_at = datetime('now')
1930         WHERE status IN ('pending', 'running', 'blocked')
1931           AND goal_id IN (
1932               SELECT g.id FROM goals g
1933               WHERE g.domain = 'personal'
1934                 AND g.source_episode_id IS NOT NULL
1935                 AND NOT EXISTS (SELECT 1 FROM tasks t WHERE t.goal_id = g.id)
1936           )",
1937    )
1938    .execute(pool)
1939    .await?;
1940
1941    // Once ([`WORK_BACKFILLS_DONE_VERSION`]): run on every start it gave each
1942    // goal made since a task-less "legacy" run (4,304 of 4,365 in one owner's
1943    // database on 2026-11-21).
1944    if !work_backfills_done(pool).await? {
1945        // Existing goal/task data gets one explicit legacy run. New scheduled
1946        // firings create a fresh run before any task is inserted.
1947        sqlx::query(
1948            "INSERT OR IGNORE INTO goal_runs
1949                (id, project_id, goal_id, trigger_type, status, outcome_summary,
1950                 started_at, completed_at, created_at, updated_at)
1951             SELECT
1952                'run-legacy-' || g.id,
1953                COALESCE(NULLIF(g.project_id, ''), 'default'),
1954                g.id,
1955                'legacy',
1956                CASE
1957                    WHEN g.status IN ('completed', 'failed', 'cancelled') THEN g.status
1958                    WHEN EXISTS (
1959                        SELECT 1 FROM tasks t
1960                        WHERE t.goal_id = g.id AND t.status = 'blocked'
1961                    ) THEN 'blocked'
1962                    ELSE 'running'
1963                END,
1964                NULL,
1965                g.created_at,
1966                CASE WHEN g.status IN ('completed', 'failed', 'cancelled')
1967                     THEN COALESCE(g.completed_at, g.updated_at) ELSE NULL END,
1968                g.created_at,
1969                g.updated_at
1970             FROM goals g
1971             WHERE g.domain = 'orchestration'",
1972        )
1973        .execute(pool)
1974        .await?;
1975    }
1976    sqlx::query(
1977        "UPDATE tasks
1978         SET goal_run_id = COALESCE(
1979             goal_run_id,
1980             (SELECT gr.id FROM goal_runs gr
1981              WHERE gr.goal_id = tasks.goal_id
1982              ORDER BY julianday(gr.started_at) DESC, gr.id DESC LIMIT 1)
1983         )
1984         WHERE goal_run_id IS NULL OR goal_run_id = ''",
1985    )
1986    .execute(pool)
1987    .await?;
1988
1989    aidaemon_tools::sqlite_schema::add_column_if_missing(
1990        pool,
1991        "ALTER TABLE scheduled_run_state ADD COLUMN goal_run_id TEXT",
1992    )
1993    .await?;
1994    sqlx::query(
1995        "UPDATE scheduled_run_state
1996         SET goal_run_id = COALESCE(
1997             goal_run_id,
1998             (SELECT t.goal_run_id FROM tasks t
1999              WHERE t.id = scheduled_run_state.root_task_id)
2000         )",
2001    )
2002    .execute(pool)
2003    .await?;
2004
2005    // The first run-isolation migration grouped all pre-existing recurring
2006    // history into one legacy run. Once no live task or scheduled-run state
2007    // references that run, close it so current board views do not present old
2008    // outcomes as an active recurring cycle. Tasks and journals remain intact.
2009    sqlx::query(
2010        "UPDATE goal_runs
2011         SET status = CASE
2012                 WHEN EXISTS (
2013                     SELECT 1 FROM tasks t
2014                     WHERE t.goal_run_id = goal_runs.id
2015                       AND t.status IN ('failed', 'blocked', 'interrupted')
2016                 ) THEN 'failed'
2017                 ELSE 'completed'
2018             END,
2019             outcome_summary = COALESCE(
2020                 outcome_summary,
2021                 'Archived legacy history after recurring-run isolation'
2022             ),
2023             completed_at = COALESCE(completed_at, datetime('now')),
2024             updated_at = datetime('now')
2025         WHERE trigger_type = 'legacy'
2026           AND status IN ('pending', 'running', 'blocked')
2027           AND EXISTS (
2028               SELECT 1 FROM goals g
2029               WHERE g.id = goal_runs.goal_id
2030                 AND g.goal_type = 'continuous'
2031           )
2032           AND NOT EXISTS (
2033               SELECT 1 FROM tasks t
2034               WHERE t.goal_run_id = goal_runs.id
2035                 AND t.status IN ('pending', 'claimed', 'running')
2036           )
2037           AND NOT EXISTS (
2038               SELECT 1 FROM scheduled_run_state s
2039               WHERE s.goal_run_id = goal_runs.id
2040           )",
2041    )
2042    .execute(pool)
2043    .await?;
2044
2045    aidaemon_tools::sqlite_schema::add_column_if_missing(
2046        pool,
2047        "ALTER TABLE notification_queue ADD COLUMN task_id TEXT",
2048    )
2049    .await?;
2050    aidaemon_tools::sqlite_schema::add_column_if_missing(
2051        pool,
2052        "ALTER TABLE notification_queue ADD COLUMN action_token TEXT",
2053    )
2054    .await?;
2055    aidaemon_tools::sqlite_schema::add_column_if_missing(
2056        pool,
2057        "ALTER TABLE notification_queue ADD COLUMN untrusted INTEGER NOT NULL DEFAULT 0",
2058    )
2059    .await?;
2060
2061    let _ = sqlx::query(
2062        "CREATE INDEX IF NOT EXISTS idx_goals_project_status
2063         ON goals(project_id, status)",
2064    )
2065    .execute(pool)
2066    .await;
2067    let _ = sqlx::query(
2068        "CREATE INDEX IF NOT EXISTS idx_goal_runs_goal_started
2069         ON goal_runs(goal_id, started_at DESC)",
2070    )
2071    .execute(pool)
2072    .await;
2073    let _ = sqlx::query("DROP INDEX IF EXISTS idx_goal_runs_one_open")
2074        .execute(pool)
2075        .await;
2076    let _ = sqlx::query(
2077        "CREATE INDEX IF NOT EXISTS idx_goal_runs_open
2078         ON goal_runs(goal_id, status)
2079         WHERE status IN ('pending', 'running', 'blocked')",
2080    )
2081    .execute(pool)
2082    .await;
2083    let _ = sqlx::query(
2084        "CREATE INDEX IF NOT EXISTS idx_tasks_goal_run_status
2085         ON tasks(goal_run_id, status)",
2086    )
2087    .execute(pool)
2088    .await;
2089    let _ = sqlx::query(
2090        "CREATE UNIQUE INDEX IF NOT EXISTS idx_task_attempts_one_active
2091         ON task_attempts(task_id)
2092         WHERE status IN ('claimed', 'running')",
2093    )
2094    .execute(pool)
2095    .await;
2096    let _ = sqlx::query(
2097        "CREATE INDEX IF NOT EXISTS idx_task_attempts_lease
2098         ON task_attempts(status, lease_expires_at)",
2099    )
2100    .execute(pool)
2101    .await;
2102    let _ = sqlx::query(
2103        "CREATE INDEX IF NOT EXISTS idx_task_journal_task_created
2104         ON task_journal(task_id, created_at)",
2105    )
2106    .execute(pool)
2107    .await;
2108    let _ = sqlx::query(
2109        "CREATE INDEX IF NOT EXISTS idx_task_handoffs_task_created
2110         ON task_handoffs(task_id, created_at)",
2111    )
2112    .execute(pool)
2113    .await;
2114    let _ = sqlx::query(
2115        "CREATE INDEX IF NOT EXISTS idx_task_workspaces_task
2116         ON task_workspaces(task_id, created_at)",
2117    )
2118    .execute(pool)
2119    .await;
2120
2121    // Indexes (idempotent).
2122    let _ = sqlx::query("CREATE INDEX IF NOT EXISTS idx_goals_status ON goals(status)")
2123        .execute(pool)
2124        .await;
2125    let _ = sqlx::query("CREATE INDEX IF NOT EXISTS idx_goals_session ON goals(session_id)")
2126        .execute(pool)
2127        .await;
2128    let _ =
2129        sqlx::query("CREATE INDEX IF NOT EXISTS idx_goals_domain_status ON goals(domain, status)")
2130            .execute(pool)
2131            .await;
2132    let _ = sqlx::query("CREATE INDEX IF NOT EXISTS idx_tasks_goal ON tasks(goal_id)")
2133        .execute(pool)
2134        .await;
2135    let _ = sqlx::query("CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks(status)")
2136        .execute(pool)
2137        .await;
2138    let _ =
2139        sqlx::query("CREATE INDEX IF NOT EXISTS idx_task_activity_task ON task_activity(task_id)")
2140            .execute(pool)
2141            .await;
2142    let _ = sqlx::query(
2143        "CREATE INDEX IF NOT EXISTS idx_task_activity_created_at ON task_activity(created_at)",
2144    )
2145    .execute(pool)
2146    .await;
2147    // Self-correcting-resilience Component A: the inactivity watchdog does a
2148    // lexical MAX(created_at) per task, so all rows must share one sortable UTC
2149    // format. Normalize any legacy RFC3339 rows ('...T...Z') to SQLite datetime,
2150    // and add a composite index to serve the correlated per-task MAX.
2151    let _ = sqlx::query(
2152        "UPDATE task_activity SET created_at = datetime(created_at) WHERE created_at LIKE '%T%'",
2153    )
2154    .execute(pool)
2155    .await;
2156    let _ = sqlx::query(
2157        "CREATE INDEX IF NOT EXISTS idx_task_activity_task_created_at \
2158         ON task_activity(task_id, created_at)",
2159    )
2160    .execute(pool)
2161    .await;
2162    let _ = sqlx::query(
2163        "CREATE INDEX IF NOT EXISTS idx_goal_schedules_goal ON goal_schedules(goal_id)",
2164    )
2165    .execute(pool)
2166    .await;
2167    let _ = sqlx::query(
2168        "CREATE INDEX IF NOT EXISTS idx_goal_schedules_next_run
2169         ON goal_schedules(next_run_at) WHERE is_paused = 0",
2170    )
2171    .execute(pool)
2172    .await;
2173    let _ = sqlx::query(
2174        "CREATE INDEX IF NOT EXISTS idx_scheduled_run_state_root_task
2175         ON scheduled_run_state(root_task_id)",
2176    )
2177    .execute(pool)
2178    .await;
2179
2180    // Notification queue — queued when channel unavailable, delivered on reconnect.
2181    // Retention: status_update expires after 24h, critical persists indefinitely.
2182    sqlx::query(
2183        "CREATE TABLE IF NOT EXISTS notification_queue (
2184            id TEXT PRIMARY KEY,
2185            goal_id TEXT NOT NULL,
2186            session_id TEXT NOT NULL,
2187            notification_type TEXT NOT NULL,
2188            priority TEXT NOT NULL DEFAULT 'status_update',
2189            message TEXT NOT NULL,
2190            created_at TEXT NOT NULL DEFAULT (datetime('now')),
2191            delivered_at TEXT,
2192            attempts INTEGER NOT NULL DEFAULT 0,
2193            expires_at TEXT
2194        )",
2195    )
2196    .execute(pool)
2197    .await?;
2198
2199    aidaemon_tools::sqlite_schema::add_column_if_missing(
2200        pool,
2201        "ALTER TABLE notification_queue ADD COLUMN task_id TEXT",
2202    )
2203    .await?;
2204    aidaemon_tools::sqlite_schema::add_column_if_missing(
2205        pool,
2206        "ALTER TABLE notification_queue ADD COLUMN action_token TEXT",
2207    )
2208    .await?;
2209    aidaemon_tools::sqlite_schema::add_column_if_missing(
2210        pool,
2211        "ALTER TABLE notification_queue ADD COLUMN untrusted INTEGER NOT NULL DEFAULT 0",
2212    )
2213    .await?;
2214
2215    sqlx::query(
2216        "CREATE INDEX IF NOT EXISTS idx_notification_queue_pending
2217         ON notification_queue(delivered_at, priority, created_at)
2218         WHERE delivered_at IS NULL",
2219    )
2220    .execute(pool)
2221    .await?;
2222
2223    Ok(())
2224}
2225
2226/// Repairs and tables that have always run after the host's own.
2227pub async fn migrate_work_tail(pool: &SqlitePool) -> anyhow::Result<()> {
2228    // Normalize legacy optional task fields. Empty strings caused completed
2229    // tasks to be misclassified as failures by callers expecting NULL.
2230    sqlx::query(
2231        "UPDATE tasks
2232         SET result = NULLIF(TRIM(result), ''),
2233             error = NULLIF(TRIM(error), ''),
2234             blocker = NULLIF(TRIM(blocker), '')
2235         WHERE (result IS NOT NULL AND TRIM(result) = '')
2236            OR (error IS NOT NULL AND TRIM(error) = '')
2237            OR (blocker IS NOT NULL AND TRIM(blocker) = '')",
2238    )
2239    .execute(pool)
2240    .await?;
2241
2242    // Repair the historical race where an executor durably blocked an attempt,
2243    // then a stale coordinator overwrote the task row as completed without an
2244    // unblock or a newer attempt. The latest fenced attempt is authoritative.
2245    sqlx::query(
2246        "UPDATE tasks
2247         SET status = 'blocked',
2248             blocker = COALESCE(blocker, 'Latest execution attempt is blocked.'),
2249             completed_at = COALESCE(
2250                 (SELECT a.completed_at FROM task_attempts a
2251                  WHERE a.task_id = tasks.id
2252                  ORDER BY julianday(a.started_at) DESC, a.id DESC LIMIT 1),
2253                 completed_at
2254             ),
2255             updated_at = datetime('now'), version = version + 1
2256         WHERE status = 'completed'
2257           AND (
2258               SELECT a.status FROM task_attempts a
2259               WHERE a.task_id = tasks.id
2260               ORDER BY julianday(a.started_at) DESC, a.id DESC LIMIT 1
2261           ) = 'blocked'",
2262    )
2263    .execute(pool)
2264    .await?;
2265
2266    // Task-linked escalation notifications are actionable only while the task
2267    // remains blocked. Close obsolete critical rows so they cannot surface
2268    // hours later after an unblock, retry, cancellation, or completion.
2269    sqlx::query(
2270        "UPDATE notification_queue
2271         SET delivered_at = datetime('now')
2272         WHERE delivered_at IS NULL
2273           AND notification_type = 'escalation'
2274           AND task_id IS NOT NULL
2275           AND NOT EXISTS (
2276               SELECT 1 FROM tasks t
2277               WHERE t.id = notification_queue.task_id AND t.status = 'blocked'
2278           )",
2279    )
2280    .execute(pool)
2281    .await?;
2282
2283    // Migration: scheduled continuous goals were historically created with incorrect
2284    // 5K/20K budgets. Bump them to the current continuous defaults (100K/500K).
2285    // Safe + idempotent.
2286    let _ = sqlx::query(
2287        "UPDATE goals
2288         SET budget_per_check = 100000,
2289             budget_daily = 500000
2290         WHERE domain = 'orchestration'
2291           AND goal_type = 'continuous'
2292           AND budget_per_check = 5000
2293           AND budget_daily = 20000
2294           AND EXISTS (SELECT 1 FROM goal_schedules s WHERE s.goal_id = goals.id)",
2295    )
2296    .execute(pool)
2297    .await;
2298
2299    // Migration: raise previously standard scheduled continuous defaults
2300    // (50K/200K) to the newer defaults (100K/500K). This only touches goals
2301    // still at the exact historical defaults, so explicit user-set budgets are
2302    // preserved.
2303    let _ = sqlx::query(
2304        "UPDATE goals
2305         SET budget_per_check = 100000,
2306             budget_daily = 500000
2307         WHERE domain = 'orchestration'
2308           AND goal_type = 'continuous'
2309           AND budget_per_check = 50000
2310           AND budget_daily = 200000
2311           AND EXISTS (SELECT 1 FROM goal_schedules s WHERE s.goal_id = goals.id)",
2312    )
2313    .execute(pool)
2314    .await;
2315
2316    // Cleanup: schedules attached to terminal goals are dead rows. They can exist
2317    // after migrations from legacy schemas or older bulk-cancel implementations.
2318    // Safe + idempotent.
2319    let _ = sqlx::query(
2320        "DELETE FROM goal_schedules
2321         WHERE goal_id IN (
2322            SELECT id FROM goals WHERE status IN ('cancelled', 'completed')
2323         )",
2324    )
2325    .execute(pool)
2326    .await;
2327
2328    let _ = sqlx::query(
2329        "DELETE FROM scheduled_run_state
2330         WHERE goal_id IN (
2331            SELECT id FROM goals WHERE status IN ('cancelled', 'completed', 'failed')
2332         )",
2333    )
2334    .execute(pool)
2335    .await;
2336
2337    // Token arithmetic is an internal runaway guard for mandates. Migrate
2338    // historical low defaults to the automatic balanced policy and derive a
2339    // daily envelope that can fund every cadence slot. This only raises
2340    // capacity; explicit efficient/thorough choices are persisted separately.
2341    let _ = sqlx::query(
2342        "UPDATE goals
2343         SET budget_per_check = MAX(COALESCE(budget_per_check, 0), 250000),
2344             budget_daily = MAX(
2345                 COALESCE(budget_daily, 0),
2346                 2000000,
2347                 ((86400 + m.default_review_secs - 1) / m.default_review_secs)
2348                    * MAX(COALESCE(budget_per_check, 0), 250000)
2349             )
2350         FROM mandates AS m
2351         WHERE m.goal_id = goals.id
2352           AND m.review_effort = 'balanced'
2353           AND (
2354               COALESCE(goals.budget_per_check, 0) < 250000
2355               OR COALESCE(goals.budget_daily, 0) < MAX(
2356                   2000000,
2357                   ((86400 + m.default_review_secs - 1) / m.default_review_secs)
2358                       * MAX(COALESCE(goals.budget_per_check, 0), 250000)
2359               )
2360           )
2361           AND goals.status IN ('active', 'pending', 'pending_confirmation')",
2362    )
2363    .execute(pool)
2364    .await;
2365
2366    // Bound only obviously runaway historical values. Managed thorough mode
2367    // legitimately exceeds the old two-million-token ceiling at fast cadences.
2368    let _ = sqlx::query(
2369        "UPDATE goals
2370         SET budget_daily = 50000000
2371         WHERE budget_daily > 50000000
2372           AND status IN ('active', 'pending', 'pending_confirmation')",
2373    )
2374    .execute(pool)
2375    .await;
2376
2377    // Background sub-agents still running. In-memory work does not survive a
2378    // restart; this is how the owner hears that it was lost.
2379    sqlx::query(
2380        "CREATE TABLE IF NOT EXISTS background_spawns (
2381            id TEXT PRIMARY KEY,
2382            session_id TEXT NOT NULL,
2383            mission TEXT NOT NULL,
2384            started_at TEXT NOT NULL
2385        )",
2386    )
2387    .execute(pool)
2388    .await?;
2389
2390    // Normalize task dependency edges. `tasks.depends_on` remains as a JSON
2391    // compatibility projection, while schedulers and claims use this table as
2392    // their authoritative graph. The join skips invalid legacy references so
2393    // migration cannot manufacture an edge to a nonexistent task.
2394    sqlx::query(
2395        "CREATE TABLE IF NOT EXISTS task_dependencies (
2396            task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
2397            depends_on_task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
2398            created_at TEXT NOT NULL DEFAULT (datetime('now')),
2399            PRIMARY KEY(task_id, depends_on_task_id),
2400            CHECK(task_id <> depends_on_task_id)
2401        )",
2402    )
2403    .execute(pool)
2404    .await?;
2405    sqlx::query(
2406        "CREATE INDEX IF NOT EXISTS idx_task_dependencies_prerequisite
2407         ON task_dependencies(depends_on_task_id, task_id)",
2408    )
2409    .execute(pool)
2410    .await?;
2411    // The table from the tasks' own lists, once ([`WORK_BACKFILLS_DONE_VERSION`]):
2412    // every task write keeps it (`replace_task_dependencies`).
2413    if !work_backfills_done(pool).await? {
2414        sqlx::query(
2415            "INSERT OR IGNORE INTO task_dependencies(task_id, depends_on_task_id)
2416             SELECT t.id, CAST(dep.value AS TEXT)
2417             FROM tasks t
2418             JOIN json_each(
2419                CASE
2420                    WHEN json_valid(COALESCE(t.depends_on, '[]'))
2421                     AND json_type(COALESCE(t.depends_on, '[]')) = 'array'
2422                    THEN COALESCE(t.depends_on, '[]')
2423                    ELSE '[]'
2424                END
2425             ) dep
2426             JOIN tasks prerequisite ON prerequisite.id = CAST(dep.value AS TEXT)
2427             WHERE CAST(dep.value AS TEXT) <> t.id",
2428        )
2429        .execute(pool)
2430        .await?;
2431    }
2432    sqlx::query(
2433        "CREATE TRIGGER IF NOT EXISTS trg_task_dependencies_no_cycle
2434         BEFORE INSERT ON task_dependencies
2435         WHEN EXISTS (
2436            WITH RECURSIVE prerequisites(id) AS (
2437                SELECT NEW.depends_on_task_id
2438                UNION
2439                SELECT edge.depends_on_task_id
2440                FROM task_dependencies edge
2441                JOIN prerequisites prior ON edge.task_id = prior.id
2442            )
2443            SELECT 1 FROM prerequisites WHERE id = NEW.task_id
2444         )
2445         BEGIN
2446            SELECT RAISE(ABORT, 'task dependency cycle');
2447         END",
2448    )
2449    .execute(pool)
2450    .await?;
2451
2452    Ok(())
2453}