Skip to main content

aidaemon_work/sqlite/
goals.rs

1use super::*;
2use crate::traits::{GoalNotificationStore, GoalStore, WorkCoordinationStore};
3
4#[async_trait]
5impl<S: WorkDatabase> crate::traits::GoalStore for S {
6    async fn create_goal(&self, goal: &Goal) -> anyhow::Result<()> {
7        // Enforce hard cap of 10 active evergreen goals (orchestration only).
8        if goal.domain == "orchestration" && goal.goal_type == "continuous" {
9            let count = self.count_active_evergreen_goals().await?;
10            if count >= 10 {
11                anyhow::bail!(
12                    "Cannot create evergreen goal: hard cap of 10 active evergreen goals reached (current: {})",
13                    count
14                );
15            }
16        }
17
18        let progress_notes_json = goal
19            .progress_notes
20            .as_ref()
21            .map(|p| serde_json::to_string(p).unwrap_or_default());
22
23        sqlx::query(
24            "INSERT INTO goals (
25                id, description, domain, goal_type, status, priority, conditions, context, resources,
26                budget_per_check, budget_daily, tokens_used_today, tokens_used_day, last_useful_action,
27                created_at, updated_at, completed_at, parent_goal_id, session_id, notified_at,
28                notification_attempts, dispatch_failures, progress_notes, source_episode_id, legacy_int_id,
29                project_id
30             )
31             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
32                     COALESCE((SELECT project_id FROM session_work_projects WHERE session_id = ?), 'default'))",
33        )
34        .bind(&goal.id)
35        .bind(&goal.description)
36        .bind(&goal.domain)
37        .bind(&goal.goal_type)
38        .bind(&goal.status)
39        .bind(&goal.priority)
40        .bind(&goal.conditions)
41        .bind(&goal.context)
42        .bind(&goal.resources)
43        .bind(goal.budget_per_check)
44        .bind(goal.budget_daily)
45        .bind(goal.tokens_used_today)
46        .bind(&goal.tokens_used_day)
47        .bind(&goal.last_useful_action)
48        .bind(&goal.created_at)
49        .bind(&goal.updated_at)
50        .bind(&goal.completed_at)
51        .bind(&goal.parent_goal_id)
52        .bind(&goal.session_id)
53        .bind(&goal.notified_at)
54        .bind(goal.notification_attempts)
55        .bind(goal.dispatch_failures)
56        .bind(&progress_notes_json)
57        .bind(goal.source_episode_id)
58        .bind(goal.legacy_int_id)
59        .bind(&goal.session_id)
60        .execute(self.work_pool())
61        .await?;
62
63        if goal.domain == "orchestration" {
64            sqlx::query(
65                "INSERT OR IGNORE INTO work_channel_links
66                    (goal_id, channel_session_id, created_at, updated_at)
67                 VALUES (?, ?, datetime('now'), datetime('now'))",
68            )
69            .bind(&goal.id)
70            .bind(&goal.session_id)
71            .execute(self.work_pool())
72            .await?;
73
74            if goal.goal_type == "finite" && matches!(goal.status.as_str(), "active" | "pending") {
75                self.start_goal_run(&goal.id, "finite", None, None).await?;
76            }
77        }
78        Ok(())
79    }
80
81    async fn get_goal(&self, id: &str) -> anyhow::Result<Option<Goal>> {
82        let row = sqlx::query(
83            "SELECT id, description, domain, goal_type, status, priority, conditions,
84             context, resources, budget_per_check, budget_daily, tokens_used_today, tokens_used_day,
85             last_useful_action, created_at, updated_at, completed_at, parent_goal_id, session_id,
86             notified_at, notification_attempts, dispatch_failures, progress_notes, source_episode_id, legacy_int_id
87             FROM goals WHERE id = ?",
88        )
89        .bind(id)
90        .fetch_optional(self.work_pool())
91        .await?;
92
93        Ok(row.map(|r| {
94            let progress_notes_json: Option<String> = r.get("progress_notes");
95            let progress_notes = progress_notes_json.and_then(|j| serde_json::from_str(&j).ok());
96
97            Goal {
98                id: r.get("id"),
99                description: r.get("description"),
100                domain: r.get("domain"),
101                goal_type: r.get("goal_type"),
102                status: r.get("status"),
103                priority: r.get("priority"),
104                conditions: r.get("conditions"),
105                context: r.get("context"),
106                resources: r.get("resources"),
107                budget_per_check: r.get("budget_per_check"),
108                budget_daily: r.get("budget_daily"),
109                tokens_used_today: r.get("tokens_used_today"),
110                tokens_used_day: r.get("tokens_used_day"),
111                last_useful_action: r.get("last_useful_action"),
112                created_at: r.get("created_at"),
113                updated_at: r.get("updated_at"),
114                completed_at: r.get("completed_at"),
115                parent_goal_id: r.get("parent_goal_id"),
116                session_id: r.get("session_id"),
117                notified_at: r.get("notified_at"),
118                notification_attempts: r.get::<i32, _>("notification_attempts"),
119                dispatch_failures: r.get::<i32, _>("dispatch_failures"),
120                progress_notes,
121                source_episode_id: r.get("source_episode_id"),
122                legacy_int_id: r.get("legacy_int_id"),
123            }
124        }))
125    }
126
127    async fn update_goal(&self, goal: &Goal) -> anyhow::Result<()> {
128        let now = chrono::Utc::now().to_rfc3339();
129        let progress_notes_json = goal
130            .progress_notes
131            .as_ref()
132            .map(|p| serde_json::to_string(p).unwrap_or_default());
133        sqlx::query(
134            "UPDATE goals SET description = ?, domain = ?, goal_type = ?, status = ?, priority = ?,
135             conditions = ?, context = ?, resources = ?,
136             budget_per_check = ?, budget_daily = ?, tokens_used_today = ?, tokens_used_day = ?,
137             last_useful_action = ?, updated_at = ?, completed_at = ?,
138             parent_goal_id = ?, session_id = ?, notified_at = ?, notification_attempts = ?, dispatch_failures = ?,
139             progress_notes = ?, source_episode_id = ?, legacy_int_id = ?
140             WHERE id = ?",
141        )
142        .bind(&goal.description)
143        .bind(&goal.domain)
144        .bind(&goal.goal_type)
145        .bind(&goal.status)
146        .bind(&goal.priority)
147        .bind(&goal.conditions)
148        .bind(&goal.context)
149        .bind(&goal.resources)
150        .bind(goal.budget_per_check)
151        .bind(goal.budget_daily)
152        .bind(goal.tokens_used_today)
153        .bind(&goal.tokens_used_day)
154        .bind(&goal.last_useful_action)
155        .bind(&now)
156        .bind(&goal.completed_at)
157        .bind(&goal.parent_goal_id)
158        .bind(&goal.session_id)
159        .bind(&goal.notified_at)
160        .bind(goal.notification_attempts)
161        .bind(goal.dispatch_failures)
162        .bind(&progress_notes_json)
163        .bind(goal.source_episode_id)
164        .bind(goal.legacy_int_id)
165        .bind(&goal.id)
166        .execute(self.work_pool())
167        .await?;
168
169        // If a goal is terminal, purge schedules so they don't linger as dead rows.
170        // This keeps the DB consistent even when cancellation/completion happens via
171        // bulk tools or non-tool code paths.
172        if goal.domain == "orchestration"
173            && matches!(goal.status.as_str(), "cancelled" | "completed")
174        {
175            sqlx::query("DELETE FROM goal_schedules WHERE goal_id = ?")
176                .bind(&goal.id)
177                .execute(self.work_pool())
178                .await?;
179        }
180
181        Ok(())
182    }
183
184    async fn get_active_goals(&self) -> anyhow::Result<Vec<Goal>> {
185        let rows = sqlx::query(
186            "SELECT id, description, domain, goal_type, status, priority, conditions,
187             context, resources, budget_per_check, budget_daily, tokens_used_today, tokens_used_day,
188             last_useful_action, created_at, updated_at, completed_at, parent_goal_id, session_id,
189             notified_at, notification_attempts, dispatch_failures, progress_notes, source_episode_id, legacy_int_id
190             FROM goals
191             WHERE domain = 'orchestration' AND status IN ('active', 'pending')
192             ORDER BY created_at DESC",
193        )
194        .fetch_all(self.work_pool())
195        .await?;
196
197        Ok(rows
198            .iter()
199            .map(|r| {
200                let progress_notes_json: Option<String> = r.get("progress_notes");
201                let progress_notes =
202                    progress_notes_json.and_then(|j| serde_json::from_str(&j).ok());
203                Goal {
204                    id: r.get("id"),
205                    description: r.get("description"),
206                    domain: r.get("domain"),
207                    goal_type: r.get("goal_type"),
208                    status: r.get("status"),
209                    priority: r.get("priority"),
210                    conditions: r.get("conditions"),
211                    context: r.get("context"),
212                    resources: r.get("resources"),
213                    budget_per_check: r.get("budget_per_check"),
214                    budget_daily: r.get("budget_daily"),
215                    tokens_used_today: r.get("tokens_used_today"),
216                    tokens_used_day: r.get("tokens_used_day"),
217                    last_useful_action: r.get("last_useful_action"),
218                    created_at: r.get("created_at"),
219                    updated_at: r.get("updated_at"),
220                    completed_at: r.get("completed_at"),
221                    parent_goal_id: r.get("parent_goal_id"),
222                    session_id: r.get("session_id"),
223                    notified_at: r.get("notified_at"),
224                    notification_attempts: r.get::<i32, _>("notification_attempts"),
225                    dispatch_failures: r.get::<i32, _>("dispatch_failures"),
226                    progress_notes,
227                    source_episode_id: r.get("source_episode_id"),
228                    legacy_int_id: r.get("legacy_int_id"),
229                }
230            })
231            .collect())
232    }
233
234    async fn get_active_personal_goals(&self, limit: i64) -> anyhow::Result<Vec<Goal>> {
235        let limit = limit.clamp(0, 100);
236        let rows = sqlx::query(
237            "SELECT id, description, domain, goal_type, status, priority, conditions,
238             context, resources, budget_per_check, budget_daily, tokens_used_today, tokens_used_day,
239             last_useful_action, created_at, updated_at, completed_at, parent_goal_id, session_id,
240             notified_at, notification_attempts, dispatch_failures, progress_notes, source_episode_id, legacy_int_id
241             FROM goals
242             WHERE domain = 'personal' AND status = 'active'
243             ORDER BY
244               CASE priority WHEN 'high' THEN 1 WHEN 'medium' THEN 2 WHEN 'low' THEN 3 ELSE 4 END,
245               created_at DESC
246             LIMIT ?",
247        )
248        .bind(limit)
249        .fetch_all(self.work_pool())
250        .await?;
251
252        Ok(rows
253            .iter()
254            .map(|r| {
255                let progress_notes_json: Option<String> = r.get("progress_notes");
256                let progress_notes =
257                    progress_notes_json.and_then(|j| serde_json::from_str(&j).ok());
258                Goal {
259                    id: r.get("id"),
260                    description: r.get("description"),
261                    domain: r.get("domain"),
262                    goal_type: r.get("goal_type"),
263                    status: r.get("status"),
264                    priority: r.get("priority"),
265                    conditions: r.get("conditions"),
266                    context: r.get("context"),
267                    resources: r.get("resources"),
268                    budget_per_check: r.get("budget_per_check"),
269                    budget_daily: r.get("budget_daily"),
270                    tokens_used_today: r.get("tokens_used_today"),
271                    tokens_used_day: r.get("tokens_used_day"),
272                    last_useful_action: r.get("last_useful_action"),
273                    created_at: r.get("created_at"),
274                    updated_at: r.get("updated_at"),
275                    completed_at: r.get("completed_at"),
276                    parent_goal_id: r.get("parent_goal_id"),
277                    session_id: r.get("session_id"),
278                    notified_at: r.get("notified_at"),
279                    notification_attempts: r.get::<i32, _>("notification_attempts"),
280                    dispatch_failures: r.get::<i32, _>("dispatch_failures"),
281                    progress_notes,
282                    source_episode_id: r.get("source_episode_id"),
283                    legacy_int_id: r.get("legacy_int_id"),
284                }
285            })
286            .collect())
287    }
288
289    async fn update_personal_goal(
290        &self,
291        goal_id: &str,
292        status: Option<&str>,
293        progress_note: Option<&str>,
294    ) -> anyhow::Result<()> {
295        let now = chrono::Utc::now().to_rfc3339();
296
297        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
298
299        if let Some(note) = progress_note {
300            let row = sqlx::query(
301                "SELECT progress_notes FROM goals WHERE id = ? AND domain = 'personal'",
302            )
303            .bind(goal_id)
304            .fetch_optional(&mut *tx)
305            .await?;
306
307            let mut notes: Vec<String> = row
308                .and_then(|r| r.get::<Option<String>, _>("progress_notes"))
309                .and_then(|j| serde_json::from_str(&j).ok())
310                .unwrap_or_default();
311            notes.push(note.to_string());
312            let notes_json = serde_json::to_string(&notes)?;
313
314            sqlx::query(
315                "UPDATE goals
316                 SET progress_notes = ?, updated_at = ?
317                 WHERE id = ? AND domain = 'personal'",
318            )
319            .bind(&notes_json)
320            .bind(&now)
321            .bind(goal_id)
322            .execute(&mut *tx)
323            .await?;
324        }
325
326        if let Some(s) = status {
327            let completed_at = if s == "completed" {
328                Some(now.clone())
329            } else {
330                None
331            };
332            sqlx::query(
333                "UPDATE goals
334                 SET status = ?, updated_at = ?, completed_at = COALESCE(?, completed_at)
335                 WHERE id = ? AND domain = 'personal'",
336            )
337            .bind(s)
338            .bind(&now)
339            .bind(&completed_at)
340            .bind(goal_id)
341            .execute(&mut *tx)
342            .await?;
343        }
344
345        tx.commit().await?;
346        Ok(())
347    }
348
349    async fn get_goals_for_session(&self, session_id: &str) -> anyhow::Result<Vec<Goal>> {
350        let rows = sqlx::query(
351            "SELECT id, description, domain, goal_type, status, priority, conditions,
352             context, resources, budget_per_check, budget_daily, tokens_used_today, tokens_used_day,
353             last_useful_action, created_at, updated_at, completed_at, parent_goal_id, session_id,
354             notified_at, notification_attempts, dispatch_failures, progress_notes, source_episode_id, legacy_int_id
355             FROM goals
356             WHERE domain = 'orchestration' AND session_id = ?
357             ORDER BY created_at DESC",
358        )
359        .bind(session_id)
360        .fetch_all(self.work_pool())
361        .await?;
362
363        Ok(rows
364            .iter()
365            .map(|r| {
366                let progress_notes_json: Option<String> = r.get("progress_notes");
367                let progress_notes =
368                    progress_notes_json.and_then(|j| serde_json::from_str(&j).ok());
369                Goal {
370                    id: r.get("id"),
371                    description: r.get("description"),
372                    domain: r.get("domain"),
373                    goal_type: r.get("goal_type"),
374                    status: r.get("status"),
375                    priority: r.get("priority"),
376                    conditions: r.get("conditions"),
377                    context: r.get("context"),
378                    resources: r.get("resources"),
379                    budget_per_check: r.get("budget_per_check"),
380                    budget_daily: r.get("budget_daily"),
381                    tokens_used_today: r.get("tokens_used_today"),
382                    tokens_used_day: r.get("tokens_used_day"),
383                    last_useful_action: r.get("last_useful_action"),
384                    created_at: r.get("created_at"),
385                    updated_at: r.get("updated_at"),
386                    completed_at: r.get("completed_at"),
387                    parent_goal_id: r.get("parent_goal_id"),
388                    session_id: r.get("session_id"),
389                    notified_at: r.get("notified_at"),
390                    notification_attempts: r.get::<i32, _>("notification_attempts"),
391                    dispatch_failures: r.get::<i32, _>("dispatch_failures"),
392                    progress_notes,
393                    source_episode_id: r.get("source_episode_id"),
394                    legacy_int_id: r.get("legacy_int_id"),
395                }
396            })
397            .collect())
398    }
399
400    async fn get_pending_confirmation_goals(&self, session_id: &str) -> anyhow::Result<Vec<Goal>> {
401        let rows = sqlx::query(
402            "SELECT id, description, domain, goal_type, status, priority, conditions,
403             context, resources, budget_per_check, budget_daily, tokens_used_today, tokens_used_day,
404             last_useful_action, created_at, updated_at, completed_at, parent_goal_id, session_id,
405             notified_at, notification_attempts, dispatch_failures, progress_notes, source_episode_id, legacy_int_id
406             FROM goals
407             WHERE domain = 'orchestration' AND session_id = ? AND status = 'pending_confirmation'
408             ORDER BY created_at DESC",
409        )
410        .bind(session_id)
411        .fetch_all(self.work_pool())
412        .await?;
413
414        Ok(rows
415            .iter()
416            .map(|r| {
417                let progress_notes_json: Option<String> = r.get("progress_notes");
418                let progress_notes =
419                    progress_notes_json.and_then(|j| serde_json::from_str(&j).ok());
420                Goal {
421                    id: r.get("id"),
422                    description: r.get("description"),
423                    domain: r.get("domain"),
424                    goal_type: r.get("goal_type"),
425                    status: r.get("status"),
426                    priority: r.get("priority"),
427                    conditions: r.get("conditions"),
428                    context: r.get("context"),
429                    resources: r.get("resources"),
430                    budget_per_check: r.get("budget_per_check"),
431                    budget_daily: r.get("budget_daily"),
432                    tokens_used_today: r.get("tokens_used_today"),
433                    tokens_used_day: r.get("tokens_used_day"),
434                    last_useful_action: r.get("last_useful_action"),
435                    created_at: r.get("created_at"),
436                    updated_at: r.get("updated_at"),
437                    completed_at: r.get("completed_at"),
438                    parent_goal_id: r.get("parent_goal_id"),
439                    session_id: r.get("session_id"),
440                    notified_at: r.get("notified_at"),
441                    notification_attempts: r.get::<i32, _>("notification_attempts"),
442                    dispatch_failures: r.get::<i32, _>("dispatch_failures"),
443                    progress_notes,
444                    source_episode_id: r.get("source_episode_id"),
445                    legacy_int_id: r.get("legacy_int_id"),
446                }
447            })
448            .collect())
449    }
450
451    async fn activate_goal(&self, goal_id: &str) -> anyhow::Result<bool> {
452        let goal_row = sqlx::query(
453            "SELECT goal_type
454             FROM goals
455             WHERE id = ? AND domain = 'orchestration' AND status = 'pending_confirmation'",
456        )
457        .bind(goal_id)
458        .fetch_optional(self.work_pool())
459        .await?;
460
461        let Some(row) = goal_row else {
462            return Ok(false);
463        };
464
465        let goal_type: String = row.get("goal_type");
466        if goal_type == "continuous" {
467            let active_evergreen = self.count_active_evergreen_goals().await?;
468            if active_evergreen >= 10 {
469                anyhow::bail!(
470                    "Cannot activate recurring goal: hard cap of 10 active evergreen goals reached (current: {})",
471                    active_evergreen
472                );
473            }
474        }
475
476        let now = chrono::Utc::now().to_rfc3339();
477        let result = sqlx::query(
478            "UPDATE goals
479             SET status = 'active', updated_at = ?
480             WHERE id = ? AND domain = 'orchestration' AND status = 'pending_confirmation'",
481        )
482        .bind(&now)
483        .bind(goal_id)
484        .execute(self.work_pool())
485        .await?;
486
487        let activated = result.rows_affected() > 0;
488        if activated
489            && let Some(goal) = self.get_goal(goal_id).await?
490            && goal.goal_type == "finite"
491            && self.get_current_goal_run(goal_id).await?.is_none()
492        {
493            self.start_goal_run(goal_id, "finite", None, None).await?;
494        }
495        Ok(activated)
496    }
497}
498
499/// Make `task_id`'s rows in `task_dependencies` exactly `dependency_ids`.
500/// The table is the one source every reader uses (dispatch, claims, the work
501/// view); `tasks.depends_on` keeps the same list for the task as written.
502/// Every task write goes through here, in the write's own transaction
503/// (2026-11-21: mandate tasks were written without their rows, which only a
504/// rebuild at the next start filled in).
505pub(crate) async fn replace_task_dependencies(
506    conn: &mut sqlx::SqliteConnection,
507    task_id: &str,
508    dependency_ids: &[String],
509) -> anyhow::Result<()> {
510    sqlx::query("DELETE FROM task_dependencies WHERE task_id = ?")
511        .bind(task_id)
512        .execute(&mut *conn)
513        .await?;
514    for dependency_id in dependency_ids {
515        sqlx::query("INSERT INTO task_dependencies(task_id, depends_on_task_id) VALUES (?, ?)")
516            .bind(task_id)
517            .bind(dependency_id)
518            .execute(&mut *conn)
519            .await?;
520    }
521    Ok(())
522}
523
524#[async_trait]
525impl<S: WorkDatabase> crate::traits::TaskStore for S {
526    async fn create_task(&self, task: &Task) -> anyhow::Result<()> {
527        let dependency_ids = task.dependency_ids().map_err(anyhow::Error::msg)?;
528        let goal_run = match self.get_current_goal_run(&task.goal_id).await? {
529            Some(run) => run,
530            None => {
531                let trigger_type = if self
532                    .get_goal(&task.goal_id)
533                    .await?
534                    .is_some_and(|goal| goal.goal_type == "finite")
535                {
536                    "finite"
537                } else {
538                    "manual"
539                };
540                // An ordinary task is not a run root merely because it was
541                // created first. Callers that create an orchestration wrapper
542                // persist that typed relationship through `start_goal_run`.
543                self.start_goal_run(&task.goal_id, trigger_type, None, None)
544                    .await?
545            }
546        };
547        let result = task
548            .result
549            .as_deref()
550            .filter(|value| !value.trim().is_empty());
551        let error = task
552            .error
553            .as_deref()
554            .filter(|value| !value.trim().is_empty());
555        let blocker = task
556            .blocker
557            .as_deref()
558            .filter(|value| !value.trim().is_empty());
559        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
560        sqlx::query(
561            "INSERT INTO tasks (id, goal_id, goal_run_id, description, status, priority, task_order,
562             parallel_group, depends_on, agent_id, context, result, error, blocker,
563             idempotent, retry_count, max_retries, created_at, started_at, completed_at, updated_at)
564             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
565        )
566        .bind(&task.id)
567        .bind(&task.goal_id)
568        .bind(&goal_run.id)
569        .bind(&task.description)
570        .bind(&task.status)
571        .bind(&task.priority)
572        .bind(task.task_order)
573        .bind(&task.parallel_group)
574        .bind(&task.depends_on)
575        .bind(&task.agent_id)
576        .bind(&task.context)
577        .bind(result)
578        .bind(error)
579        .bind(blocker)
580        .bind(task.idempotent as i32)
581        .bind(task.retry_count)
582        .bind(task.max_retries)
583        .bind(&task.created_at)
584        .bind(&task.started_at)
585        .bind(&task.completed_at)
586        .bind(&task.created_at)
587        .execute(&mut *tx)
588        .await?;
589        replace_task_dependencies(&mut tx, &task.id, &dependency_ids).await?;
590
591        tx.commit().await?;
592        Ok(())
593    }
594
595    async fn get_task(&self, id: &str) -> anyhow::Result<Option<Task>> {
596        let row = sqlx::query(
597            "SELECT id, goal_id, description, status, priority, task_order,
598             parallel_group, depends_on, agent_id, context, result, error, blocker,
599             idempotent, retry_count, max_retries, created_at, started_at, completed_at
600             FROM tasks WHERE id = ?",
601        )
602        .bind(id)
603        .fetch_optional(self.work_pool())
604        .await?;
605
606        Ok(row.map(|r| Task {
607            id: r.get("id"),
608            goal_id: r.get("goal_id"),
609            description: r.get("description"),
610            status: r.get("status"),
611            priority: r.get("priority"),
612            task_order: r.get("task_order"),
613            parallel_group: r.get("parallel_group"),
614            depends_on: r.get("depends_on"),
615            agent_id: r.get("agent_id"),
616            context: r.get("context"),
617            result: r.get("result"),
618            error: r.get("error"),
619            blocker: r.get("blocker"),
620            idempotent: r.get::<i32, _>("idempotent") != 0,
621            retry_count: r.get("retry_count"),
622            max_retries: r.get("max_retries"),
623            created_at: r.get("created_at"),
624            started_at: r.get("started_at"),
625            completed_at: r.get("completed_at"),
626        }))
627    }
628
629    async fn update_task(&self, task: &Task) -> anyhow::Result<()> {
630        let dependency_ids = task.dependency_ids().map_err(anyhow::Error::msg)?;
631        let result = task
632            .result
633            .as_deref()
634            .filter(|value| !value.trim().is_empty());
635        let error = task
636            .error
637            .as_deref()
638            .filter(|value| !value.trim().is_empty());
639        let blocker = task
640            .blocker
641            .as_deref()
642            .filter(|value| !value.trim().is_empty());
643        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
644        let updated = sqlx::query(
645            "UPDATE tasks SET description = ?, status = ?, priority = ?, task_order = ?,
646             parallel_group = ?, depends_on = ?, agent_id = ?, context = ?,
647             result = ?, error = ?, blocker = ?, idempotent = ?,
648             retry_count = ?, max_retries = ?, started_at = ?, completed_at = ?,
649             updated_at = datetime('now'), version = version + 1
650             WHERE id = ?
651               AND (status <> 'blocked' OR ? = 'blocked')",
652        )
653        .bind(&task.description)
654        .bind(&task.status)
655        .bind(&task.priority)
656        .bind(task.task_order)
657        .bind(&task.parallel_group)
658        .bind(&task.depends_on)
659        .bind(&task.agent_id)
660        .bind(&task.context)
661        .bind(result)
662        .bind(error)
663        .bind(blocker)
664        .bind(task.idempotent as i32)
665        .bind(task.retry_count)
666        .bind(task.max_retries)
667        .bind(&task.started_at)
668        .bind(&task.completed_at)
669        .bind(&task.id)
670        .bind(&task.status)
671        .execute(&mut *tx)
672        .await?;
673
674        if updated.rows_affected() == 0 {
675            let current_status =
676                sqlx::query_scalar::<_, String>("SELECT status FROM tasks WHERE id = ?")
677                    .bind(&task.id)
678                    .fetch_optional(&mut *tx)
679                    .await?;
680            if current_status.as_deref() == Some("blocked") && task.status != "blocked" {
681                anyhow::bail!(
682                    "blocked task {} must be explicitly unblocked or retried before transitioning to {}",
683                    task.id,
684                    task.status
685                );
686            }
687            anyhow::bail!("task {} no longer exists", task.id);
688        }
689
690        replace_task_dependencies(&mut tx, &task.id, &dependency_ids).await?;
691
692        // A completed task counts as useful progress for its goal — refresh the
693        // goal's freshness so the >30-day idle auto-skip never mis-fires on a
694        // goal that's actively completing work. (A 0-row match if the goal is
695        // gone is not an error.)
696        if task.completed_successfully() {
697            let now = chrono::Utc::now().to_rfc3339();
698            sqlx::query("UPDATE goals SET last_useful_action = ?, updated_at = ? WHERE id = ?")
699                .bind(&now)
700                .bind(&now)
701                .bind(&task.goal_id)
702                .execute(&mut *tx)
703                .await?;
704        }
705        tx.commit().await?;
706        Ok(())
707    }
708
709    async fn get_tasks_for_goal(&self, goal_id: &str) -> anyhow::Result<Vec<Task>> {
710        let rows = sqlx::query(
711            "SELECT id, goal_id, description, status, priority, task_order,
712             parallel_group, depends_on, agent_id, context, result, error, blocker,
713             idempotent, retry_count, max_retries, created_at, started_at, completed_at
714             FROM tasks WHERE goal_id = ?
715             ORDER BY task_order ASC",
716        )
717        .bind(goal_id)
718        .fetch_all(self.work_pool())
719        .await?;
720
721        Ok(rows
722            .iter()
723            .map(|r| Task {
724                id: r.get("id"),
725                goal_id: r.get("goal_id"),
726                description: r.get("description"),
727                status: r.get("status"),
728                priority: r.get("priority"),
729                task_order: r.get("task_order"),
730                parallel_group: r.get("parallel_group"),
731                depends_on: r.get("depends_on"),
732                agent_id: r.get("agent_id"),
733                context: r.get("context"),
734                result: r.get("result"),
735                error: r.get("error"),
736                blocker: r.get("blocker"),
737                idempotent: r.get::<i32, _>("idempotent") != 0,
738                retry_count: r.get("retry_count"),
739                max_retries: r.get("max_retries"),
740                created_at: r.get("created_at"),
741                started_at: r.get("started_at"),
742                completed_at: r.get("completed_at"),
743            })
744            .collect())
745    }
746
747    async fn count_completed_tasks_for_goal(&self, goal_id: &str) -> anyhow::Result<i64> {
748        let row = sqlx::query(
749            "SELECT COUNT(*) as cnt FROM tasks
750             WHERE goal_id = ? AND status IN ('completed', 'skipped')",
751        )
752        .bind(goal_id)
753        .fetch_one(self.work_pool())
754        .await?;
755        Ok(row.get::<i64, _>("cnt"))
756    }
757
758    async fn claim_task(&self, task_id: &str, agent_id: &str) -> anyhow::Result<bool> {
759        Ok(self
760            .claim_task_with_lease(task_id, agent_id, None, 180)
761            .await?
762            .is_some())
763    }
764
765    async fn log_task_activity(&self, activity: &TaskActivity) -> anyhow::Result<()> {
766        // Redact secrets from tool_args and result before persisting
767        let redacted_args = activity
768            .tool_args
769            .as_deref()
770            .map(|text| self.redact_secrets(text));
771        let redacted_result = activity
772            .result
773            .as_deref()
774            .map(|text| self.redact_secrets(text));
775
776        sqlx::query(
777            "INSERT INTO task_activity (task_id, activity_type, tool_name, tool_args,
778             result, success, tokens_used, created_at)
779             VALUES (?, ?, ?, ?, ?, ?, ?, datetime(?))",
780        )
781        .bind(&activity.task_id)
782        .bind(&activity.activity_type)
783        .bind(&activity.tool_name)
784        .bind(&redacted_args)
785        .bind(&redacted_result)
786        .bind(activity.success.map(|b| b as i32))
787        .bind(activity.tokens_used)
788        .bind(&activity.created_at)
789        .execute(self.work_pool())
790        .await?;
791        Ok(())
792    }
793
794    async fn get_task_activities(&self, task_id: &str) -> anyhow::Result<Vec<TaskActivity>> {
795        let rows = sqlx::query(
796            "SELECT id, task_id, activity_type, tool_name, tool_args, result, success,
797             tokens_used, created_at
798             FROM task_activity WHERE task_id = ?
799             ORDER BY created_at ASC",
800        )
801        .bind(task_id)
802        .fetch_all(self.work_pool())
803        .await?;
804
805        Ok(rows
806            .iter()
807            .map(|r| TaskActivity {
808                id: r.get("id"),
809                task_id: r.get("task_id"),
810                activity_type: r.get("activity_type"),
811                tool_name: r.get("tool_name"),
812                tool_args: r.get("tool_args"),
813                result: r.get("result"),
814                success: r.get::<Option<i32>, _>("success").map(|v| v != 0),
815                tokens_used: r.get("tokens_used"),
816                created_at: r.get("created_at"),
817            })
818            .collect())
819    }
820}
821
822#[async_trait]
823impl<S: WorkDatabase> crate::traits::GoalScheduleStore for S {
824    async fn create_goal_schedule(&self, schedule: &GoalSchedule) -> anyhow::Result<()> {
825        crate::schedule::ScheduleZone::from_stored(&schedule.tz)?;
826
827        // Safety: schedules only apply to orchestration goals.
828        let domain_row = sqlx::query("SELECT domain FROM goals WHERE id = ?")
829            .bind(&schedule.goal_id)
830            .fetch_optional(self.work_pool())
831            .await?;
832        if let Some(row) = domain_row {
833            let domain: String = row.get("domain");
834            if domain != "orchestration" {
835                anyhow::bail!(
836                    "Cannot create schedule for non-orchestration goal {} (domain={})",
837                    schedule.goal_id,
838                    domain
839                );
840            }
841        }
842
843        sqlx::query(
844            "INSERT INTO goal_schedules
845                (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)
846             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
847        )
848        .bind(&schedule.id)
849        .bind(&schedule.goal_id)
850        .bind(&schedule.cron_expr)
851        .bind(&schedule.tz)
852        .bind(&schedule.original_schedule)
853        .bind(&schedule.fire_policy)
854        .bind(schedule.is_one_shot as i32)
855        .bind(schedule.is_paused as i32)
856        .bind(&schedule.last_run_at)
857        .bind(&schedule.next_run_at)
858        .bind(&schedule.created_at)
859        .bind(&schedule.updated_at)
860        .execute(self.work_pool())
861        .await?;
862        Ok(())
863    }
864
865    async fn get_goal_schedule(&self, schedule_id: &str) -> anyhow::Result<Option<GoalSchedule>> {
866        let row = sqlx::query(
867            "SELECT 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
868             FROM goal_schedules WHERE id = ?",
869        )
870        .bind(schedule_id)
871        .fetch_optional(self.work_pool())
872        .await?;
873
874        Ok(row.map(|r| GoalSchedule {
875            id: r.get("id"),
876            goal_id: r.get("goal_id"),
877            cron_expr: r.get("cron_expr"),
878            tz: r.get("tz"),
879            original_schedule: r.get("original_schedule"),
880            fire_policy: r.get("fire_policy"),
881            is_one_shot: r.get::<i64, _>("is_one_shot") != 0,
882            is_paused: r.get::<i64, _>("is_paused") != 0,
883            last_run_at: r.get("last_run_at"),
884            next_run_at: r.get("next_run_at"),
885            created_at: r.get("created_at"),
886            updated_at: r.get("updated_at"),
887        }))
888    }
889
890    async fn get_schedules_for_goal(&self, goal_id: &str) -> anyhow::Result<Vec<GoalSchedule>> {
891        let rows = sqlx::query(
892            "SELECT 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
893             FROM goal_schedules
894             WHERE goal_id = ?
895             ORDER BY next_run_at ASC",
896        )
897        .bind(goal_id)
898        .fetch_all(self.work_pool())
899        .await?;
900
901        Ok(rows
902            .iter()
903            .map(|r| GoalSchedule {
904                id: r.get("id"),
905                goal_id: r.get("goal_id"),
906                cron_expr: r.get("cron_expr"),
907                tz: r.get("tz"),
908                original_schedule: r.get("original_schedule"),
909                fire_policy: r.get("fire_policy"),
910                is_one_shot: r.get::<i64, _>("is_one_shot") != 0,
911                is_paused: r.get::<i64, _>("is_paused") != 0,
912                last_run_at: r.get("last_run_at"),
913                next_run_at: r.get("next_run_at"),
914                created_at: r.get("created_at"),
915                updated_at: r.get("updated_at"),
916            })
917            .collect())
918    }
919
920    async fn get_due_goal_schedules(&self, limit: i64) -> anyhow::Result<Vec<GoalSchedule>> {
921        let limit = limit.clamp(0, 500);
922        let now = chrono::Utc::now().to_rfc3339();
923        let rows = sqlx::query(
924            "SELECT s.id, s.goal_id, s.cron_expr, s.tz, s.original_schedule, s.fire_policy, s.is_one_shot, s.is_paused, s.last_run_at, s.next_run_at, s.created_at, s.updated_at
925             FROM goal_schedules s
926             JOIN goals g ON g.id = s.goal_id
927             WHERE s.is_paused = 0
928               AND s.next_run_at <= ?
929               AND g.domain = 'orchestration'
930               AND g.status = 'active'
931             ORDER BY s.next_run_at ASC
932             LIMIT ?",
933        )
934        .bind(&now)
935        .bind(limit)
936        .fetch_all(self.work_pool())
937        .await?;
938
939        Ok(rows
940            .iter()
941            .map(|r| GoalSchedule {
942                id: r.get("id"),
943                goal_id: r.get("goal_id"),
944                cron_expr: r.get("cron_expr"),
945                tz: r.get("tz"),
946                original_schedule: r.get("original_schedule"),
947                fire_policy: r.get("fire_policy"),
948                is_one_shot: r.get::<i64, _>("is_one_shot") != 0,
949                is_paused: r.get::<i64, _>("is_paused") != 0,
950                last_run_at: r.get("last_run_at"),
951                next_run_at: r.get("next_run_at"),
952                created_at: r.get("created_at"),
953                updated_at: r.get("updated_at"),
954            })
955            .collect())
956    }
957
958    async fn update_goal_schedule(&self, schedule: &GoalSchedule) -> anyhow::Result<()> {
959        // A schedule that runs needs a zone this can read; one paused for an
960        // unreadable zone can still be saved.
961        if !schedule.is_paused {
962            crate::schedule::ScheduleZone::from_stored(&schedule.tz)?;
963        }
964
965        let now = chrono::Utc::now().to_rfc3339();
966        sqlx::query(
967            "UPDATE goal_schedules
968             SET goal_id = ?, cron_expr = ?, tz = ?, original_schedule = ?, fire_policy = ?,
969                 is_one_shot = ?, is_paused = ?, last_run_at = ?, next_run_at = ?, updated_at = ?
970             WHERE id = ?",
971        )
972        .bind(&schedule.goal_id)
973        .bind(&schedule.cron_expr)
974        .bind(&schedule.tz)
975        .bind(&schedule.original_schedule)
976        .bind(&schedule.fire_policy)
977        .bind(schedule.is_one_shot as i32)
978        .bind(schedule.is_paused as i32)
979        .bind(&schedule.last_run_at)
980        .bind(&schedule.next_run_at)
981        .bind(&now)
982        .bind(&schedule.id)
983        .execute(self.work_pool())
984        .await?;
985        Ok(())
986    }
987
988    async fn delete_goal_schedule(&self, schedule_id: &str) -> anyhow::Result<bool> {
989        let result = sqlx::query("DELETE FROM goal_schedules WHERE id = ?")
990            .bind(schedule_id)
991            .execute(self.work_pool())
992            .await?;
993        Ok(result.rows_affected() > 0)
994    }
995
996    async fn cancel_stale_pending_confirmation_goals(
997        &self,
998        max_age_secs: i64,
999    ) -> anyhow::Result<u64> {
1000        let now = chrono::Utc::now().to_rfc3339();
1001        let cutoff = (chrono::Utc::now() - chrono::Duration::seconds(max_age_secs)).to_rfc3339();
1002        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
1003
1004        // If we're cancelling stale pending confirmations, remove their schedules
1005        // so they don't appear as "scheduled" (zombie schedules).
1006        sqlx::query(
1007            "DELETE FROM goal_schedules
1008             WHERE goal_id IN (
1009               SELECT id FROM goals WHERE status = 'pending_confirmation' AND created_at < ?
1010             )",
1011        )
1012        .bind(&cutoff)
1013        .execute(&mut *tx)
1014        .await?;
1015
1016        // A mandate pending confirmation carries no authority yet, but the
1017        // proof must remain coherent with its controller. Cancel both records
1018        // atomically so generic pending-confirmation cleanup cannot leave a
1019        // resumable paused mandate behind.
1020        sqlx::query(
1021            "UPDATE mandates
1022             SET status = 'cancelled', review_lease_token = NULL,
1023                 review_lease_expires_at = NULL, version = version + 1,
1024                 updated_at = ?
1025             WHERE status = 'paused' AND confirmed_at IS NULL
1026               AND goal_id IN (
1027                   SELECT id FROM goals
1028                   WHERE status = 'pending_confirmation' AND created_at < ?
1029               )",
1030        )
1031        .bind(&now)
1032        .bind(&cutoff)
1033        .execute(&mut *tx)
1034        .await?;
1035
1036        let result = sqlx::query(
1037            "UPDATE goals
1038             SET status = 'cancelled', updated_at = ?, completed_at = ?
1039             WHERE status = 'pending_confirmation' AND created_at < ?",
1040        )
1041        .bind(&now)
1042        .bind(&now)
1043        .bind(&cutoff)
1044        .execute(&mut *tx)
1045        .await?;
1046        tx.commit().await?;
1047        Ok(result.rows_affected())
1048    }
1049
1050    async fn get_scheduled_goals(&self) -> anyhow::Result<Vec<Goal>> {
1051        let rows = sqlx::query(sqlx::AssertSqlSafe(format!(
1052            "SELECT {GOAL_LIST_COLUMNS}
1053             FROM goals
1054             WHERE domain = 'orchestration'
1055               AND (
1056                 EXISTS (SELECT 1 FROM goal_schedules s WHERE s.goal_id = goals.id)
1057                 OR status = 'pending_confirmation'
1058               )
1059             ORDER BY created_at DESC"
1060        )))
1061        .fetch_all(self.work_pool())
1062        .await?;
1063        Ok(rows.iter().map(goal_from_list_row).collect())
1064    }
1065
1066    async fn get_unscheduled_active_goals(&self) -> anyhow::Result<Vec<Goal>> {
1067        let rows = sqlx::query(sqlx::AssertSqlSafe(format!(
1068            "SELECT {GOAL_LIST_COLUMNS}
1069             FROM goals
1070             WHERE domain = 'orchestration'
1071               AND goal_type = 'continuous'
1072               AND status = 'active'
1073               AND NOT EXISTS (SELECT 1 FROM goal_schedules s WHERE s.goal_id = goals.id)
1074               AND NOT EXISTS (SELECT 1 FROM mandates m WHERE m.goal_id = goals.id)
1075             ORDER BY created_at DESC"
1076        )))
1077        .fetch_all(self.work_pool())
1078        .await?;
1079        Ok(rows.iter().map(goal_from_list_row).collect())
1080    }
1081}
1082
1083const GOAL_LIST_COLUMNS: &str = "id, description, domain, goal_type, status, priority, conditions,
1084             context, resources, budget_per_check, budget_daily, tokens_used_today, tokens_used_day,
1085             last_useful_action, created_at, updated_at, completed_at, parent_goal_id, session_id,
1086             notified_at, notification_attempts, dispatch_failures, progress_notes, source_episode_id, legacy_int_id";
1087
1088fn goal_from_list_row(r: &sqlx::sqlite::SqliteRow) -> Goal {
1089    let progress_notes_json: Option<String> = r.get("progress_notes");
1090    let progress_notes = progress_notes_json.and_then(|j| serde_json::from_str(&j).ok());
1091    Goal {
1092        id: r.get("id"),
1093        description: r.get("description"),
1094        domain: r.get("domain"),
1095        goal_type: r.get("goal_type"),
1096        status: r.get("status"),
1097        priority: r.get("priority"),
1098        conditions: r.get("conditions"),
1099        context: r.get("context"),
1100        resources: r.get("resources"),
1101        budget_per_check: r.get("budget_per_check"),
1102        budget_daily: r.get("budget_daily"),
1103        tokens_used_today: r.get("tokens_used_today"),
1104        tokens_used_day: r.get("tokens_used_day"),
1105        last_useful_action: r.get("last_useful_action"),
1106        created_at: r.get("created_at"),
1107        updated_at: r.get("updated_at"),
1108        completed_at: r.get("completed_at"),
1109        parent_goal_id: r.get("parent_goal_id"),
1110        session_id: r.get("session_id"),
1111        notified_at: r.get("notified_at"),
1112        notification_attempts: r.get::<i32, _>("notification_attempts"),
1113        dispatch_failures: r.get::<i32, _>("dispatch_failures"),
1114        progress_notes,
1115        source_episode_id: r.get("source_episode_id"),
1116        legacy_int_id: r.get("legacy_int_id"),
1117    }
1118}
1119
1120#[async_trait]
1121impl<S: WorkDatabase> crate::traits::GoalBudgetStore for S {
1122    async fn reset_daily_token_budgets(&self) -> anyhow::Result<u64> {
1123        let result = sqlx::query(
1124            "UPDATE goals
1125             SET tokens_used_today = 0, tokens_used_day = date('now')
1126             WHERE domain = 'orchestration'
1127               AND status = 'active'
1128               AND tokens_used_day <> date('now')",
1129        )
1130        .execute(self.work_pool())
1131        .await?;
1132        Ok(result.rows_affected())
1133    }
1134
1135    async fn set_goal_budgets(
1136        &self,
1137        goal_id: &str,
1138        budget_per_check: Option<i64>,
1139        budget_daily: Option<i64>,
1140    ) -> anyhow::Result<()> {
1141        sqlx::query(
1142            "UPDATE goals SET budget_per_check = COALESCE(?, budget_per_check),
1143                              budget_daily = COALESCE(?, budget_daily),
1144                              updated_at = ? WHERE id = ?",
1145        )
1146        .bind(budget_per_check)
1147        .bind(budget_daily)
1148        .bind(chrono::Utc::now().to_rfc3339())
1149        .bind(goal_id)
1150        .execute(self.work_pool())
1151        .await?;
1152        Ok(())
1153    }
1154
1155    async fn add_goal_tokens_and_get_budget_status(
1156        &self,
1157        goal_id: &str,
1158        delta_tokens: i64,
1159    ) -> anyhow::Result<Option<GoalTokenBudgetStatus>> {
1160        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
1161        let today = chrono::Utc::now().date_naive().to_string();
1162
1163        // Lazy daily reset keyed by UTC day anchor.
1164        let _ = sqlx::query(
1165            "UPDATE goals
1166             SET tokens_used_today = 0, tokens_used_day = ?
1167             WHERE id = ? AND (tokens_used_day IS NULL OR tokens_used_day != ?)",
1168        )
1169        .bind(&today)
1170        .bind(goal_id)
1171        .bind(&today)
1172        .execute(&mut *tx)
1173        .await;
1174
1175        if delta_tokens != 0 {
1176            sqlx::query(
1177                "UPDATE goals
1178                 SET tokens_used_today = MAX(0, tokens_used_today + ?)
1179                 WHERE id = ?",
1180            )
1181            .bind(delta_tokens)
1182            .bind(goal_id)
1183            .execute(&mut *tx)
1184            .await?;
1185        }
1186
1187        let row = sqlx::query(
1188            "SELECT budget_per_check, budget_daily, tokens_used_today
1189             FROM goals
1190             WHERE id = ?",
1191        )
1192        .bind(goal_id)
1193        .fetch_optional(&mut *tx)
1194        .await?;
1195
1196        tx.commit().await?;
1197
1198        Ok(row.map(|r| GoalTokenBudgetStatus {
1199            budget_per_check: r.get("budget_per_check"),
1200            budget_daily: r.get("budget_daily"),
1201            tokens_used_today: r.get("tokens_used_today"),
1202        }))
1203    }
1204}
1205
1206#[async_trait]
1207impl<S: WorkDatabase> crate::traits::ScheduledRunStore for S {
1208    async fn upsert_scheduled_run_state(&self, state: &ScheduledRunState) -> anyhow::Result<()> {
1209        let health_json = serde_json::to_string(&state.health)?;
1210        sqlx::query(
1211            "INSERT INTO scheduled_run_state (
1212                goal_id, root_task_id, goal_run_id, effective_budget_per_check, tokens_used,
1213                budget_extensions_count, health_json, created_at, updated_at
1214             ) VALUES (?, ?, (SELECT goal_run_id FROM tasks WHERE id = ?), ?, ?, ?, ?, ?, ?)
1215             ON CONFLICT(goal_id) DO UPDATE SET
1216                root_task_id = excluded.root_task_id,
1217                goal_run_id = excluded.goal_run_id,
1218                effective_budget_per_check = excluded.effective_budget_per_check,
1219                tokens_used = excluded.tokens_used,
1220                budget_extensions_count = excluded.budget_extensions_count,
1221                health_json = excluded.health_json,
1222                updated_at = excluded.updated_at",
1223        )
1224        .bind(&state.goal_id)
1225        .bind(&state.root_task_id)
1226        .bind(&state.root_task_id)
1227        .bind(state.effective_budget_per_check)
1228        .bind(state.tokens_used)
1229        .bind(state.budget_extensions_count as i64)
1230        .bind(health_json)
1231        .bind(&state.created_at)
1232        .bind(&state.updated_at)
1233        .execute(self.work_pool())
1234        .await?;
1235        Ok(())
1236    }
1237
1238    async fn get_scheduled_run_state(
1239        &self,
1240        goal_id: &str,
1241    ) -> anyhow::Result<Option<ScheduledRunState>> {
1242        let row = sqlx::query(
1243            "SELECT goal_id, root_task_id, effective_budget_per_check, tokens_used,
1244                    budget_extensions_count, health_json, created_at, updated_at
1245             FROM scheduled_run_state
1246             WHERE goal_id = ?",
1247        )
1248        .bind(goal_id)
1249        .fetch_optional(self.work_pool())
1250        .await?;
1251
1252        Ok(row.map(|r| ScheduledRunState {
1253            goal_id: r.get("goal_id"),
1254            root_task_id: r.get("root_task_id"),
1255            effective_budget_per_check: r.get("effective_budget_per_check"),
1256            tokens_used: r.get("tokens_used"),
1257            budget_extensions_count: r.get::<i64, _>("budget_extensions_count") as usize,
1258            health: r
1259                .try_get::<String, _>("health_json")
1260                .ok()
1261                .and_then(|raw| serde_json::from_str(&raw).ok())
1262                .unwrap_or_default(),
1263            created_at: r.get("created_at"),
1264            updated_at: r.get("updated_at"),
1265        }))
1266    }
1267
1268    async fn get_scheduled_recovery_state(
1269        &self,
1270        goal_id: &str,
1271    ) -> anyhow::Result<Option<crate::traits::ScheduledRecoveryState>> {
1272        let row = sqlx::query(
1273            "SELECT goal_id, consecutive_failures, failure_budget, disposition,
1274                    latest_failure_kind, last_failed_run_id, last_recovery_run_id,
1275                    recovery_attempts, last_recovery_attempt_at, updated_at
1276             FROM scheduled_recovery_state WHERE goal_id = ?",
1277        )
1278        .bind(goal_id)
1279        .fetch_optional(self.work_pool())
1280        .await?;
1281        row.map(scheduled_recovery_state_from_row).transpose()
1282    }
1283
1284    async fn list_escalated_recovery_candidates(
1285        &self,
1286        cooldown_secs: i64,
1287        max_attempts: u16,
1288    ) -> anyhow::Result<Vec<crate::traits::ScheduledRecoveryState>> {
1289        // Only objectives the recovery machine itself paused are eligible;
1290        // an owner's independent pause never triggers automatic recovery.
1291        let rows = sqlx::query(
1292            "SELECT r.goal_id, r.consecutive_failures, r.failure_budget, r.disposition,
1293                    r.latest_failure_kind, r.last_failed_run_id, r.last_recovery_run_id,
1294                    r.recovery_attempts, r.last_recovery_attempt_at, r.updated_at
1295             FROM scheduled_recovery_state r
1296             JOIN goals g ON g.id = r.goal_id
1297             WHERE r.disposition = 'escalated'
1298               AND g.status = 'active'
1299               AND r.recovery_attempts < ?
1300               AND EXISTS (SELECT 1 FROM scheduled_recovery_paused_schedules p
1301                            WHERE p.goal_id = r.goal_id)
1302               AND (julianday('now') - julianday(COALESCE(r.last_recovery_attempt_at, r.updated_at)))
1303                   * 86400.0 >= ?
1304             ORDER BY r.updated_at ASC",
1305        )
1306        .bind(i64::from(max_attempts))
1307        .bind(cooldown_secs)
1308        .fetch_all(self.work_pool())
1309        .await?;
1310        rows.into_iter()
1311            .map(scheduled_recovery_state_from_row)
1312            .collect()
1313    }
1314
1315    async fn record_scheduled_recovery_attempt(&self, goal_id: &str) -> anyhow::Result<()> {
1316        sqlx::query(
1317            "UPDATE scheduled_recovery_state
1318                SET recovery_attempts = recovery_attempts + 1,
1319                    last_recovery_attempt_at = ?
1320              WHERE goal_id = ?",
1321        )
1322        .bind(chrono::Utc::now().to_rfc3339())
1323        .bind(goal_id)
1324        .execute(self.work_pool())
1325        .await?;
1326        Ok(())
1327    }
1328
1329    async fn delete_scheduled_run_state(&self, goal_id: &str) -> anyhow::Result<bool> {
1330        let result = sqlx::query("DELETE FROM scheduled_run_state WHERE goal_id = ?")
1331            .bind(goal_id)
1332            .execute(self.work_pool())
1333            .await?;
1334        Ok(result.rows_affected() > 0)
1335    }
1336}
1337
1338#[async_trait]
1339impl<S: WorkDatabase> crate::traits::TaskDispatchStore for S {
1340    async fn get_pending_tasks_by_priority(&self, limit: i64) -> anyhow::Result<Vec<Task>> {
1341        let rows = sqlx::query(
1342            "SELECT t.id, t.goal_id, t.description, t.status, t.priority, t.task_order,
1343             t.parallel_group, t.depends_on, t.agent_id, t.context, t.result, t.error,
1344             t.blocker, t.idempotent, t.retry_count, t.max_retries, t.created_at,
1345             t.started_at, t.completed_at
1346             FROM tasks t
1347             JOIN goals g ON t.goal_id = g.id
1348                         AND g.domain = 'orchestration'
1349                         AND g.status IN ('active', 'stalled')
1350             WHERE t.status = 'pending'
1351             AND NOT EXISTS (
1352                 SELECT 1 FROM task_dependencies dep
1353                 WHERE dep.task_id = t.id
1354                   AND NOT EXISTS (
1355                     SELECT 1 FROM tasks d
1356                     WHERE d.id = dep.depends_on_task_id
1357                       AND d.goal_run_id = t.goal_run_id
1358                       AND d.status IN ('completed', 'skipped', 'superseded')
1359                 )
1360             )
1361             ORDER BY
1362                 CASE t.priority WHEN 'high' THEN 1 WHEN 'medium' THEN 2 WHEN 'low' THEN 3 ELSE 4 END,
1363                 t.task_order ASC
1364             LIMIT ?",
1365        )
1366        .bind(limit)
1367        .fetch_all(self.work_pool())
1368        .await?;
1369
1370        Ok(rows
1371            .iter()
1372            .map(|r| Task {
1373                id: r.get("id"),
1374                goal_id: r.get("goal_id"),
1375                description: r.get("description"),
1376                status: r.get("status"),
1377                priority: r.get("priority"),
1378                task_order: r.get("task_order"),
1379                parallel_group: r.get("parallel_group"),
1380                depends_on: r.get("depends_on"),
1381                agent_id: r.get("agent_id"),
1382                context: r.get("context"),
1383                result: r.get("result"),
1384                error: r.get("error"),
1385                blocker: r.get("blocker"),
1386                idempotent: r.get::<i32, _>("idempotent") != 0,
1387                retry_count: r.get("retry_count"),
1388                max_retries: r.get("max_retries"),
1389                created_at: r.get("created_at"),
1390                started_at: r.get("started_at"),
1391                completed_at: r.get("completed_at"),
1392            })
1393            .collect())
1394    }
1395
1396    async fn get_stuck_tasks(&self, timeout_secs: i64) -> anyhow::Result<Vec<Task>> {
1397        let rows = sqlx::query(
1398            "SELECT id, goal_id, description, status, priority, task_order,
1399             parallel_group, depends_on, agent_id, context, result, error,
1400             blocker, idempotent, retry_count, max_retries, created_at,
1401             started_at, completed_at
1402             FROM tasks
1403             WHERE status IN ('running', 'claimed')
1404             AND (
1405                EXISTS (
1406                    SELECT 1 FROM task_attempts a
1407                    WHERE a.id = tasks.current_attempt_id
1408                      AND a.status IN ('claimed', 'running')
1409                      AND datetime(a.lease_expires_at) <= datetime('now')
1410                )
1411                OR (
1412                    tasks.current_attempt_id IS NULL
1413                    AND COALESCE(
1414                        (SELECT MAX(ta.created_at) FROM task_activity ta WHERE ta.task_id = tasks.id),
1415                        datetime(tasks.started_at)
1416                    ) < datetime('now', '-' || ? || ' seconds')
1417                )
1418             )
1419             ORDER BY started_at ASC",
1420        )
1421        .bind(timeout_secs)
1422        .fetch_all(self.work_pool())
1423        .await?;
1424
1425        Ok(rows
1426            .iter()
1427            .map(|r| Task {
1428                id: r.get("id"),
1429                goal_id: r.get("goal_id"),
1430                description: r.get("description"),
1431                status: r.get("status"),
1432                priority: r.get("priority"),
1433                task_order: r.get("task_order"),
1434                parallel_group: r.get("parallel_group"),
1435                depends_on: r.get("depends_on"),
1436                agent_id: r.get("agent_id"),
1437                context: r.get("context"),
1438                result: r.get("result"),
1439                error: r.get("error"),
1440                blocker: r.get("blocker"),
1441                idempotent: r.get::<i32, _>("idempotent") != 0,
1442                retry_count: r.get("retry_count"),
1443                max_retries: r.get("max_retries"),
1444                created_at: r.get("created_at"),
1445                started_at: r.get("started_at"),
1446                completed_at: r.get("completed_at"),
1447            })
1448            .collect())
1449    }
1450
1451    async fn get_recently_completed_tasks(&self, since: &str) -> anyhow::Result<Vec<Task>> {
1452        let rows = sqlx::query(
1453            "SELECT id, goal_id, description, status, priority, task_order,
1454             parallel_group, depends_on, agent_id, context, result, error,
1455             blocker, idempotent, retry_count, max_retries, created_at,
1456             started_at, completed_at
1457             FROM tasks
1458             WHERE status = 'completed' AND completed_at > ?
1459             ORDER BY completed_at DESC",
1460        )
1461        .bind(since)
1462        .fetch_all(self.work_pool())
1463        .await?;
1464
1465        Ok(rows
1466            .iter()
1467            .map(|r| Task {
1468                id: r.get("id"),
1469                goal_id: r.get("goal_id"),
1470                description: r.get("description"),
1471                status: r.get("status"),
1472                priority: r.get("priority"),
1473                task_order: r.get("task_order"),
1474                parallel_group: r.get("parallel_group"),
1475                depends_on: r.get("depends_on"),
1476                agent_id: r.get("agent_id"),
1477                context: r.get("context"),
1478                result: r.get("result"),
1479                error: r.get("error"),
1480                blocker: r.get("blocker"),
1481                idempotent: r.get::<i32, _>("idempotent") != 0,
1482                retry_count: r.get("retry_count"),
1483                max_retries: r.get("max_retries"),
1484                created_at: r.get("created_at"),
1485                started_at: r.get("started_at"),
1486                completed_at: r.get("completed_at"),
1487            })
1488            .collect())
1489    }
1490
1491    async fn mark_task_interrupted(&self, task_id: &str) -> anyhow::Result<bool> {
1492        let result = sqlx::query(
1493            "UPDATE tasks SET status = 'interrupted',
1494             completed_at = datetime('now')
1495             WHERE id = ? AND status IN ('running', 'claimed')",
1496        )
1497        .bind(task_id)
1498        .execute(self.work_pool())
1499        .await?;
1500        Ok(result.rows_affected() > 0)
1501    }
1502}
1503
1504#[async_trait]
1505impl<S: WorkDatabase> crate::traits::GoalNotificationStore for S {
1506    async fn count_active_evergreen_goals(&self) -> anyhow::Result<i64> {
1507        let row = sqlx::query(
1508            "SELECT COUNT(*) as cnt FROM goals
1509             WHERE domain = 'orchestration' AND goal_type = 'continuous' AND status = 'active'",
1510        )
1511        .fetch_one(self.work_pool())
1512        .await?;
1513        Ok(row.get::<i64, _>("cnt"))
1514    }
1515
1516    async fn get_goals_needing_notification(&self) -> anyhow::Result<Vec<Goal>> {
1517        let rows = sqlx::query(
1518            "SELECT id, description, domain, goal_type, status, priority, conditions,
1519             context, resources, budget_per_check, budget_daily, tokens_used_today, tokens_used_day,
1520             last_useful_action, created_at, updated_at, completed_at, parent_goal_id,
1521             session_id, notified_at, notification_attempts, dispatch_failures, progress_notes, source_episode_id, legacy_int_id
1522             FROM goals
1523             WHERE domain = 'orchestration'
1524               AND status IN ('completed', 'failed', 'stalled')
1525               AND notified_at IS NULL
1526               AND goal_type = 'finite'
1527               AND notification_attempts < 3",
1528        )
1529        .fetch_all(self.work_pool())
1530        .await?;
1531
1532        Ok(rows
1533            .iter()
1534            .map(|r| {
1535                let progress_notes_json: Option<String> = r.get("progress_notes");
1536                let progress_notes =
1537                    progress_notes_json.and_then(|j| serde_json::from_str(&j).ok());
1538                Goal {
1539                    id: r.get("id"),
1540                    description: r.get("description"),
1541                    domain: r.get("domain"),
1542                    goal_type: r.get("goal_type"),
1543                    status: r.get("status"),
1544                    priority: r.get("priority"),
1545                    conditions: r.get("conditions"),
1546                    context: r.get("context"),
1547                    resources: r.get("resources"),
1548                    budget_per_check: r.get("budget_per_check"),
1549                    budget_daily: r.get("budget_daily"),
1550                    tokens_used_today: r.get("tokens_used_today"),
1551                    tokens_used_day: r.get("tokens_used_day"),
1552                    last_useful_action: r.get("last_useful_action"),
1553                    created_at: r.get("created_at"),
1554                    updated_at: r.get("updated_at"),
1555                    completed_at: r.get("completed_at"),
1556                    parent_goal_id: r.get("parent_goal_id"),
1557                    session_id: r.get("session_id"),
1558                    notified_at: r.get("notified_at"),
1559                    notification_attempts: r.get::<i32, _>("notification_attempts"),
1560                    dispatch_failures: r.get::<i32, _>("dispatch_failures"),
1561                    progress_notes,
1562                    source_episode_id: r.get("source_episode_id"),
1563                    legacy_int_id: r.get("legacy_int_id"),
1564                }
1565            })
1566            .collect())
1567    }
1568
1569    async fn mark_goal_notified(&self, goal_id: &str) -> anyhow::Result<()> {
1570        let now = chrono::Utc::now().to_rfc3339();
1571        sqlx::query("UPDATE goals SET notified_at = ? WHERE id = ?")
1572            .bind(&now)
1573            .bind(goal_id)
1574            .execute(self.work_pool())
1575            .await?;
1576        Ok(())
1577    }
1578
1579    async fn cleanup_stale_goals(&self, stale_hours: i64) -> anyhow::Result<u64> {
1580        let cutoff = (chrono::Utc::now() - chrono::Duration::hours(stale_hours)).to_rfc3339();
1581        let now = chrono::Utc::now().to_rfc3339();
1582
1583        // Finite orchestration goals without schedules: stale active/pending -> failed.
1584        // This is administrative recovery for abandoned work, not a live task
1585        // failure. Mark it notified in the same atomic update so restart
1586        // recovery cannot flood the user with one misleading alert per row.
1587        let result = sqlx::query(
1588            "UPDATE goals
1589             SET status = 'failed', updated_at = ?, completed_at = ?,
1590                 notified_at = COALESCE(notified_at, ?)
1591             WHERE domain = 'orchestration'
1592               AND status IN ('active', 'pending')
1593               AND goal_type = 'finite'
1594               AND updated_at < ?
1595               AND NOT EXISTS (
1596                   SELECT 1 FROM goal_schedules s WHERE s.goal_id = goals.id
1597               )",
1598        )
1599        .bind(&now)
1600        .bind(&now)
1601        .bind(&now)
1602        .bind(&cutoff)
1603        .execute(self.work_pool())
1604        .await?;
1605
1606        Ok(result.rows_affected())
1607    }
1608}
1609
1610fn scheduled_recovery_state_from_row(
1611    row: sqlx::sqlite::SqliteRow,
1612) -> anyhow::Result<crate::traits::ScheduledRecoveryState> {
1613    let disposition_raw: String = row.get("disposition");
1614    let latest_failure_raw: Option<String> = row.get("latest_failure_kind");
1615    Ok(crate::traits::ScheduledRecoveryState {
1616        goal_id: row.get("goal_id"),
1617        consecutive_failures: u16::try_from(row.get::<i64, _>("consecutive_failures"))?,
1618        failure_budget: u16::try_from(row.get::<i64, _>("failure_budget"))?,
1619        disposition: crate::traits::ScheduledRecoveryDisposition::parse(&disposition_raw)
1620            .ok_or_else(|| {
1621                anyhow::anyhow!("invalid scheduled recovery disposition `{disposition_raw}`")
1622            })?,
1623        latest_failure_kind: latest_failure_raw
1624            .as_deref()
1625            .map(|value| {
1626                crate::traits::ScheduledFailureKind::parse(value)
1627                    .ok_or_else(|| anyhow::anyhow!("invalid scheduled failure kind `{value}`"))
1628            })
1629            .transpose()?,
1630        last_failed_run_id: row.get("last_failed_run_id"),
1631        last_recovery_run_id: row.get("last_recovery_run_id"),
1632        recovery_attempts: u16::try_from(row.try_get::<i64, _>("recovery_attempts").unwrap_or(0))?,
1633        last_recovery_attempt_at: row
1634            .try_get::<Option<String>, _>("last_recovery_attempt_at")
1635            .unwrap_or(None),
1636        updated_at: row.get("updated_at"),
1637    })
1638}