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#[async_trait]
500impl<S: WorkDatabase> crate::traits::TaskStore for S {
501    async fn create_task(&self, task: &Task) -> anyhow::Result<()> {
502        let dependency_ids = task.dependency_ids().map_err(anyhow::Error::msg)?;
503        let goal_run = match self.get_current_goal_run(&task.goal_id).await? {
504            Some(run) => run,
505            None => {
506                let trigger_type = if self
507                    .get_goal(&task.goal_id)
508                    .await?
509                    .is_some_and(|goal| goal.goal_type == "finite")
510                {
511                    "finite"
512                } else {
513                    "manual"
514                };
515                // An ordinary task is not a run root merely because it was
516                // created first. Callers that create an orchestration wrapper
517                // persist that typed relationship through `start_goal_run`.
518                self.start_goal_run(&task.goal_id, trigger_type, None, None)
519                    .await?
520            }
521        };
522        let result = task
523            .result
524            .as_deref()
525            .filter(|value| !value.trim().is_empty());
526        let error = task
527            .error
528            .as_deref()
529            .filter(|value| !value.trim().is_empty());
530        let blocker = task
531            .blocker
532            .as_deref()
533            .filter(|value| !value.trim().is_empty());
534        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
535        sqlx::query(
536            "INSERT INTO tasks (id, goal_id, goal_run_id, description, status, priority, task_order,
537             parallel_group, depends_on, agent_id, context, result, error, blocker,
538             idempotent, retry_count, max_retries, created_at, started_at, completed_at, updated_at)
539             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
540        )
541        .bind(&task.id)
542        .bind(&task.goal_id)
543        .bind(&goal_run.id)
544        .bind(&task.description)
545        .bind(&task.status)
546        .bind(&task.priority)
547        .bind(task.task_order)
548        .bind(&task.parallel_group)
549        .bind(&task.depends_on)
550        .bind(&task.agent_id)
551        .bind(&task.context)
552        .bind(result)
553        .bind(error)
554        .bind(blocker)
555        .bind(task.idempotent as i32)
556        .bind(task.retry_count)
557        .bind(task.max_retries)
558        .bind(&task.created_at)
559        .bind(&task.started_at)
560        .bind(&task.completed_at)
561        .bind(&task.created_at)
562        .execute(&mut *tx)
563        .await?;
564        for dependency_id in dependency_ids {
565            sqlx::query("INSERT INTO task_dependencies(task_id, depends_on_task_id) VALUES (?, ?)")
566                .bind(&task.id)
567                .bind(dependency_id)
568                .execute(&mut *tx)
569                .await?;
570        }
571
572        tx.commit().await?;
573        Ok(())
574    }
575
576    async fn get_task(&self, id: &str) -> anyhow::Result<Option<Task>> {
577        let row = sqlx::query(
578            "SELECT id, goal_id, description, status, priority, task_order,
579             parallel_group, depends_on, agent_id, context, result, error, blocker,
580             idempotent, retry_count, max_retries, created_at, started_at, completed_at
581             FROM tasks WHERE id = ?",
582        )
583        .bind(id)
584        .fetch_optional(self.work_pool())
585        .await?;
586
587        Ok(row.map(|r| Task {
588            id: r.get("id"),
589            goal_id: r.get("goal_id"),
590            description: r.get("description"),
591            status: r.get("status"),
592            priority: r.get("priority"),
593            task_order: r.get("task_order"),
594            parallel_group: r.get("parallel_group"),
595            depends_on: r.get("depends_on"),
596            agent_id: r.get("agent_id"),
597            context: r.get("context"),
598            result: r.get("result"),
599            error: r.get("error"),
600            blocker: r.get("blocker"),
601            idempotent: r.get::<i32, _>("idempotent") != 0,
602            retry_count: r.get("retry_count"),
603            max_retries: r.get("max_retries"),
604            created_at: r.get("created_at"),
605            started_at: r.get("started_at"),
606            completed_at: r.get("completed_at"),
607        }))
608    }
609
610    async fn update_task(&self, task: &Task) -> anyhow::Result<()> {
611        let dependency_ids = task.dependency_ids().map_err(anyhow::Error::msg)?;
612        let result = task
613            .result
614            .as_deref()
615            .filter(|value| !value.trim().is_empty());
616        let error = task
617            .error
618            .as_deref()
619            .filter(|value| !value.trim().is_empty());
620        let blocker = task
621            .blocker
622            .as_deref()
623            .filter(|value| !value.trim().is_empty());
624        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
625        let updated = sqlx::query(
626            "UPDATE tasks SET description = ?, status = ?, priority = ?, task_order = ?,
627             parallel_group = ?, depends_on = ?, agent_id = ?, context = ?,
628             result = ?, error = ?, blocker = ?, idempotent = ?,
629             retry_count = ?, max_retries = ?, started_at = ?, completed_at = ?,
630             updated_at = datetime('now'), version = version + 1
631             WHERE id = ?
632               AND (status <> 'blocked' OR ? = 'blocked')",
633        )
634        .bind(&task.description)
635        .bind(&task.status)
636        .bind(&task.priority)
637        .bind(task.task_order)
638        .bind(&task.parallel_group)
639        .bind(&task.depends_on)
640        .bind(&task.agent_id)
641        .bind(&task.context)
642        .bind(result)
643        .bind(error)
644        .bind(blocker)
645        .bind(task.idempotent as i32)
646        .bind(task.retry_count)
647        .bind(task.max_retries)
648        .bind(&task.started_at)
649        .bind(&task.completed_at)
650        .bind(&task.id)
651        .bind(&task.status)
652        .execute(&mut *tx)
653        .await?;
654
655        if updated.rows_affected() == 0 {
656            let current_status =
657                sqlx::query_scalar::<_, String>("SELECT status FROM tasks WHERE id = ?")
658                    .bind(&task.id)
659                    .fetch_optional(&mut *tx)
660                    .await?;
661            if current_status.as_deref() == Some("blocked") && task.status != "blocked" {
662                anyhow::bail!(
663                    "blocked task {} must be explicitly unblocked or retried before transitioning to {}",
664                    task.id,
665                    task.status
666                );
667            }
668            anyhow::bail!("task {} no longer exists", task.id);
669        }
670
671        sqlx::query("DELETE FROM task_dependencies WHERE task_id = ?")
672            .bind(&task.id)
673            .execute(&mut *tx)
674            .await?;
675        for dependency_id in dependency_ids {
676            sqlx::query("INSERT INTO task_dependencies(task_id, depends_on_task_id) VALUES (?, ?)")
677                .bind(&task.id)
678                .bind(dependency_id)
679                .execute(&mut *tx)
680                .await?;
681        }
682
683        // A completed task counts as useful progress for its goal — refresh the
684        // goal's freshness so the >30-day idle auto-skip never mis-fires on a
685        // goal that's actively completing work. (A 0-row match if the goal is
686        // gone is not an error.)
687        if task.completed_successfully() {
688            let now = chrono::Utc::now().to_rfc3339();
689            sqlx::query("UPDATE goals SET last_useful_action = ?, updated_at = ? WHERE id = ?")
690                .bind(&now)
691                .bind(&now)
692                .bind(&task.goal_id)
693                .execute(&mut *tx)
694                .await?;
695        }
696        tx.commit().await?;
697        Ok(())
698    }
699
700    async fn get_tasks_for_goal(&self, goal_id: &str) -> anyhow::Result<Vec<Task>> {
701        let rows = sqlx::query(
702            "SELECT id, goal_id, description, status, priority, task_order,
703             parallel_group, depends_on, agent_id, context, result, error, blocker,
704             idempotent, retry_count, max_retries, created_at, started_at, completed_at
705             FROM tasks WHERE goal_id = ?
706             ORDER BY task_order ASC",
707        )
708        .bind(goal_id)
709        .fetch_all(self.work_pool())
710        .await?;
711
712        Ok(rows
713            .iter()
714            .map(|r| Task {
715                id: r.get("id"),
716                goal_id: r.get("goal_id"),
717                description: r.get("description"),
718                status: r.get("status"),
719                priority: r.get("priority"),
720                task_order: r.get("task_order"),
721                parallel_group: r.get("parallel_group"),
722                depends_on: r.get("depends_on"),
723                agent_id: r.get("agent_id"),
724                context: r.get("context"),
725                result: r.get("result"),
726                error: r.get("error"),
727                blocker: r.get("blocker"),
728                idempotent: r.get::<i32, _>("idempotent") != 0,
729                retry_count: r.get("retry_count"),
730                max_retries: r.get("max_retries"),
731                created_at: r.get("created_at"),
732                started_at: r.get("started_at"),
733                completed_at: r.get("completed_at"),
734            })
735            .collect())
736    }
737
738    async fn count_completed_tasks_for_goal(&self, goal_id: &str) -> anyhow::Result<i64> {
739        let row = sqlx::query(
740            "SELECT COUNT(*) as cnt FROM tasks
741             WHERE goal_id = ? AND status IN ('completed', 'skipped')",
742        )
743        .bind(goal_id)
744        .fetch_one(self.work_pool())
745        .await?;
746        Ok(row.get::<i64, _>("cnt"))
747    }
748
749    async fn claim_task(&self, task_id: &str, agent_id: &str) -> anyhow::Result<bool> {
750        Ok(self
751            .claim_task_with_lease(task_id, agent_id, None, 180)
752            .await?
753            .is_some())
754    }
755
756    async fn log_task_activity(&self, activity: &TaskActivity) -> anyhow::Result<()> {
757        // Redact secrets from tool_args and result before persisting
758        let redacted_args = activity
759            .tool_args
760            .as_deref()
761            .map(|text| self.redact_secrets(text));
762        let redacted_result = activity
763            .result
764            .as_deref()
765            .map(|text| self.redact_secrets(text));
766
767        sqlx::query(
768            "INSERT INTO task_activity (task_id, activity_type, tool_name, tool_args,
769             result, success, tokens_used, created_at)
770             VALUES (?, ?, ?, ?, ?, ?, ?, datetime(?))",
771        )
772        .bind(&activity.task_id)
773        .bind(&activity.activity_type)
774        .bind(&activity.tool_name)
775        .bind(&redacted_args)
776        .bind(&redacted_result)
777        .bind(activity.success.map(|b| b as i32))
778        .bind(activity.tokens_used)
779        .bind(&activity.created_at)
780        .execute(self.work_pool())
781        .await?;
782        Ok(())
783    }
784
785    async fn get_task_activities(&self, task_id: &str) -> anyhow::Result<Vec<TaskActivity>> {
786        let rows = sqlx::query(
787            "SELECT id, task_id, activity_type, tool_name, tool_args, result, success,
788             tokens_used, created_at
789             FROM task_activity WHERE task_id = ?
790             ORDER BY created_at ASC",
791        )
792        .bind(task_id)
793        .fetch_all(self.work_pool())
794        .await?;
795
796        Ok(rows
797            .iter()
798            .map(|r| TaskActivity {
799                id: r.get("id"),
800                task_id: r.get("task_id"),
801                activity_type: r.get("activity_type"),
802                tool_name: r.get("tool_name"),
803                tool_args: r.get("tool_args"),
804                result: r.get("result"),
805                success: r.get::<Option<i32>, _>("success").map(|v| v != 0),
806                tokens_used: r.get("tokens_used"),
807                created_at: r.get("created_at"),
808            })
809            .collect())
810    }
811}
812
813#[async_trait]
814impl<S: WorkDatabase> crate::traits::GoalScheduleStore for S {
815    async fn create_goal_schedule(&self, schedule: &GoalSchedule) -> anyhow::Result<()> {
816        crate::schedule::ScheduleZone::from_stored(&schedule.tz)?;
817
818        // Safety: schedules only apply to orchestration goals.
819        let domain_row = sqlx::query("SELECT domain FROM goals WHERE id = ?")
820            .bind(&schedule.goal_id)
821            .fetch_optional(self.work_pool())
822            .await?;
823        if let Some(row) = domain_row {
824            let domain: String = row.get("domain");
825            if domain != "orchestration" {
826                anyhow::bail!(
827                    "Cannot create schedule for non-orchestration goal {} (domain={})",
828                    schedule.goal_id,
829                    domain
830                );
831            }
832        }
833
834        sqlx::query(
835            "INSERT INTO goal_schedules
836                (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)
837             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
838        )
839        .bind(&schedule.id)
840        .bind(&schedule.goal_id)
841        .bind(&schedule.cron_expr)
842        .bind(&schedule.tz)
843        .bind(&schedule.original_schedule)
844        .bind(&schedule.fire_policy)
845        .bind(schedule.is_one_shot as i32)
846        .bind(schedule.is_paused as i32)
847        .bind(&schedule.last_run_at)
848        .bind(&schedule.next_run_at)
849        .bind(&schedule.created_at)
850        .bind(&schedule.updated_at)
851        .execute(self.work_pool())
852        .await?;
853        Ok(())
854    }
855
856    async fn get_goal_schedule(&self, schedule_id: &str) -> anyhow::Result<Option<GoalSchedule>> {
857        let row = sqlx::query(
858            "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
859             FROM goal_schedules WHERE id = ?",
860        )
861        .bind(schedule_id)
862        .fetch_optional(self.work_pool())
863        .await?;
864
865        Ok(row.map(|r| GoalSchedule {
866            id: r.get("id"),
867            goal_id: r.get("goal_id"),
868            cron_expr: r.get("cron_expr"),
869            tz: r.get("tz"),
870            original_schedule: r.get("original_schedule"),
871            fire_policy: r.get("fire_policy"),
872            is_one_shot: r.get::<i64, _>("is_one_shot") != 0,
873            is_paused: r.get::<i64, _>("is_paused") != 0,
874            last_run_at: r.get("last_run_at"),
875            next_run_at: r.get("next_run_at"),
876            created_at: r.get("created_at"),
877            updated_at: r.get("updated_at"),
878        }))
879    }
880
881    async fn get_schedules_for_goal(&self, goal_id: &str) -> anyhow::Result<Vec<GoalSchedule>> {
882        let rows = sqlx::query(
883            "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
884             FROM goal_schedules
885             WHERE goal_id = ?
886             ORDER BY next_run_at ASC",
887        )
888        .bind(goal_id)
889        .fetch_all(self.work_pool())
890        .await?;
891
892        Ok(rows
893            .iter()
894            .map(|r| GoalSchedule {
895                id: r.get("id"),
896                goal_id: r.get("goal_id"),
897                cron_expr: r.get("cron_expr"),
898                tz: r.get("tz"),
899                original_schedule: r.get("original_schedule"),
900                fire_policy: r.get("fire_policy"),
901                is_one_shot: r.get::<i64, _>("is_one_shot") != 0,
902                is_paused: r.get::<i64, _>("is_paused") != 0,
903                last_run_at: r.get("last_run_at"),
904                next_run_at: r.get("next_run_at"),
905                created_at: r.get("created_at"),
906                updated_at: r.get("updated_at"),
907            })
908            .collect())
909    }
910
911    async fn get_due_goal_schedules(&self, limit: i64) -> anyhow::Result<Vec<GoalSchedule>> {
912        let limit = limit.clamp(0, 500);
913        let now = chrono::Utc::now().to_rfc3339();
914        let rows = sqlx::query(
915            "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
916             FROM goal_schedules s
917             JOIN goals g ON g.id = s.goal_id
918             WHERE s.is_paused = 0
919               AND s.next_run_at <= ?
920               AND g.domain = 'orchestration'
921               AND g.status = 'active'
922             ORDER BY s.next_run_at ASC
923             LIMIT ?",
924        )
925        .bind(&now)
926        .bind(limit)
927        .fetch_all(self.work_pool())
928        .await?;
929
930        Ok(rows
931            .iter()
932            .map(|r| GoalSchedule {
933                id: r.get("id"),
934                goal_id: r.get("goal_id"),
935                cron_expr: r.get("cron_expr"),
936                tz: r.get("tz"),
937                original_schedule: r.get("original_schedule"),
938                fire_policy: r.get("fire_policy"),
939                is_one_shot: r.get::<i64, _>("is_one_shot") != 0,
940                is_paused: r.get::<i64, _>("is_paused") != 0,
941                last_run_at: r.get("last_run_at"),
942                next_run_at: r.get("next_run_at"),
943                created_at: r.get("created_at"),
944                updated_at: r.get("updated_at"),
945            })
946            .collect())
947    }
948
949    async fn update_goal_schedule(&self, schedule: &GoalSchedule) -> anyhow::Result<()> {
950        // A schedule that runs needs a zone this can read; one paused for an
951        // unreadable zone can still be saved.
952        if !schedule.is_paused {
953            crate::schedule::ScheduleZone::from_stored(&schedule.tz)?;
954        }
955
956        let now = chrono::Utc::now().to_rfc3339();
957        sqlx::query(
958            "UPDATE goal_schedules
959             SET goal_id = ?, cron_expr = ?, tz = ?, original_schedule = ?, fire_policy = ?,
960                 is_one_shot = ?, is_paused = ?, last_run_at = ?, next_run_at = ?, updated_at = ?
961             WHERE id = ?",
962        )
963        .bind(&schedule.goal_id)
964        .bind(&schedule.cron_expr)
965        .bind(&schedule.tz)
966        .bind(&schedule.original_schedule)
967        .bind(&schedule.fire_policy)
968        .bind(schedule.is_one_shot as i32)
969        .bind(schedule.is_paused as i32)
970        .bind(&schedule.last_run_at)
971        .bind(&schedule.next_run_at)
972        .bind(&now)
973        .bind(&schedule.id)
974        .execute(self.work_pool())
975        .await?;
976        Ok(())
977    }
978
979    async fn delete_goal_schedule(&self, schedule_id: &str) -> anyhow::Result<bool> {
980        let result = sqlx::query("DELETE FROM goal_schedules WHERE id = ?")
981            .bind(schedule_id)
982            .execute(self.work_pool())
983            .await?;
984        Ok(result.rows_affected() > 0)
985    }
986
987    async fn cancel_stale_pending_confirmation_goals(
988        &self,
989        max_age_secs: i64,
990    ) -> anyhow::Result<u64> {
991        let now = chrono::Utc::now().to_rfc3339();
992        let cutoff = (chrono::Utc::now() - chrono::Duration::seconds(max_age_secs)).to_rfc3339();
993        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
994
995        // If we're cancelling stale pending confirmations, remove their schedules
996        // so they don't appear as "scheduled" (zombie schedules).
997        sqlx::query(
998            "DELETE FROM goal_schedules
999             WHERE goal_id IN (
1000               SELECT id FROM goals WHERE status = 'pending_confirmation' AND created_at < ?
1001             )",
1002        )
1003        .bind(&cutoff)
1004        .execute(&mut *tx)
1005        .await?;
1006
1007        // A mandate pending confirmation carries no authority yet, but the
1008        // proof must remain coherent with its controller. Cancel both records
1009        // atomically so generic pending-confirmation cleanup cannot leave a
1010        // resumable paused mandate behind.
1011        sqlx::query(
1012            "UPDATE mandates
1013             SET status = 'cancelled', review_lease_token = NULL,
1014                 review_lease_expires_at = NULL, version = version + 1,
1015                 updated_at = ?
1016             WHERE status = 'paused' AND confirmed_at IS NULL
1017               AND goal_id IN (
1018                   SELECT id FROM goals
1019                   WHERE status = 'pending_confirmation' AND created_at < ?
1020               )",
1021        )
1022        .bind(&now)
1023        .bind(&cutoff)
1024        .execute(&mut *tx)
1025        .await?;
1026
1027        let result = sqlx::query(
1028            "UPDATE goals
1029             SET status = 'cancelled', updated_at = ?, completed_at = ?
1030             WHERE status = 'pending_confirmation' AND created_at < ?",
1031        )
1032        .bind(&now)
1033        .bind(&now)
1034        .bind(&cutoff)
1035        .execute(&mut *tx)
1036        .await?;
1037        tx.commit().await?;
1038        Ok(result.rows_affected())
1039    }
1040
1041    async fn get_scheduled_goals(&self) -> anyhow::Result<Vec<Goal>> {
1042        let rows = sqlx::query(sqlx::AssertSqlSafe(format!(
1043            "SELECT {GOAL_LIST_COLUMNS}
1044             FROM goals
1045             WHERE domain = 'orchestration'
1046               AND (
1047                 EXISTS (SELECT 1 FROM goal_schedules s WHERE s.goal_id = goals.id)
1048                 OR status = 'pending_confirmation'
1049               )
1050             ORDER BY created_at DESC"
1051        )))
1052        .fetch_all(self.work_pool())
1053        .await?;
1054        Ok(rows.iter().map(goal_from_list_row).collect())
1055    }
1056
1057    async fn get_unscheduled_active_goals(&self) -> anyhow::Result<Vec<Goal>> {
1058        let rows = sqlx::query(sqlx::AssertSqlSafe(format!(
1059            "SELECT {GOAL_LIST_COLUMNS}
1060             FROM goals
1061             WHERE domain = 'orchestration'
1062               AND goal_type = 'continuous'
1063               AND status = 'active'
1064               AND NOT EXISTS (SELECT 1 FROM goal_schedules s WHERE s.goal_id = goals.id)
1065               AND NOT EXISTS (SELECT 1 FROM mandates m WHERE m.goal_id = goals.id)
1066             ORDER BY created_at DESC"
1067        )))
1068        .fetch_all(self.work_pool())
1069        .await?;
1070        Ok(rows.iter().map(goal_from_list_row).collect())
1071    }
1072}
1073
1074const GOAL_LIST_COLUMNS: &str = "id, description, domain, goal_type, status, priority, conditions,
1075             context, resources, budget_per_check, budget_daily, tokens_used_today, tokens_used_day,
1076             last_useful_action, created_at, updated_at, completed_at, parent_goal_id, session_id,
1077             notified_at, notification_attempts, dispatch_failures, progress_notes, source_episode_id, legacy_int_id";
1078
1079fn goal_from_list_row(r: &sqlx::sqlite::SqliteRow) -> Goal {
1080    let progress_notes_json: Option<String> = r.get("progress_notes");
1081    let progress_notes = progress_notes_json.and_then(|j| serde_json::from_str(&j).ok());
1082    Goal {
1083        id: r.get("id"),
1084        description: r.get("description"),
1085        domain: r.get("domain"),
1086        goal_type: r.get("goal_type"),
1087        status: r.get("status"),
1088        priority: r.get("priority"),
1089        conditions: r.get("conditions"),
1090        context: r.get("context"),
1091        resources: r.get("resources"),
1092        budget_per_check: r.get("budget_per_check"),
1093        budget_daily: r.get("budget_daily"),
1094        tokens_used_today: r.get("tokens_used_today"),
1095        tokens_used_day: r.get("tokens_used_day"),
1096        last_useful_action: r.get("last_useful_action"),
1097        created_at: r.get("created_at"),
1098        updated_at: r.get("updated_at"),
1099        completed_at: r.get("completed_at"),
1100        parent_goal_id: r.get("parent_goal_id"),
1101        session_id: r.get("session_id"),
1102        notified_at: r.get("notified_at"),
1103        notification_attempts: r.get::<i32, _>("notification_attempts"),
1104        dispatch_failures: r.get::<i32, _>("dispatch_failures"),
1105        progress_notes,
1106        source_episode_id: r.get("source_episode_id"),
1107        legacy_int_id: r.get("legacy_int_id"),
1108    }
1109}
1110
1111#[async_trait]
1112impl<S: WorkDatabase> crate::traits::GoalBudgetStore for S {
1113    async fn reset_daily_token_budgets(&self) -> anyhow::Result<u64> {
1114        let result = sqlx::query(
1115            "UPDATE goals
1116             SET tokens_used_today = 0, tokens_used_day = date('now')
1117             WHERE domain = 'orchestration'
1118               AND status = 'active'
1119               AND tokens_used_day <> date('now')",
1120        )
1121        .execute(self.work_pool())
1122        .await?;
1123        Ok(result.rows_affected())
1124    }
1125
1126    async fn set_goal_budgets(
1127        &self,
1128        goal_id: &str,
1129        budget_per_check: Option<i64>,
1130        budget_daily: Option<i64>,
1131    ) -> anyhow::Result<()> {
1132        sqlx::query(
1133            "UPDATE goals SET budget_per_check = COALESCE(?, budget_per_check),
1134                              budget_daily = COALESCE(?, budget_daily),
1135                              updated_at = ? WHERE id = ?",
1136        )
1137        .bind(budget_per_check)
1138        .bind(budget_daily)
1139        .bind(chrono::Utc::now().to_rfc3339())
1140        .bind(goal_id)
1141        .execute(self.work_pool())
1142        .await?;
1143        Ok(())
1144    }
1145
1146    async fn add_goal_tokens_and_get_budget_status(
1147        &self,
1148        goal_id: &str,
1149        delta_tokens: i64,
1150    ) -> anyhow::Result<Option<GoalTokenBudgetStatus>> {
1151        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
1152        let today = chrono::Utc::now().date_naive().to_string();
1153
1154        // Lazy daily reset keyed by UTC day anchor.
1155        let _ = sqlx::query(
1156            "UPDATE goals
1157             SET tokens_used_today = 0, tokens_used_day = ?
1158             WHERE id = ? AND (tokens_used_day IS NULL OR tokens_used_day != ?)",
1159        )
1160        .bind(&today)
1161        .bind(goal_id)
1162        .bind(&today)
1163        .execute(&mut *tx)
1164        .await;
1165
1166        if delta_tokens != 0 {
1167            sqlx::query(
1168                "UPDATE goals
1169                 SET tokens_used_today = MAX(0, tokens_used_today + ?)
1170                 WHERE id = ?",
1171            )
1172            .bind(delta_tokens)
1173            .bind(goal_id)
1174            .execute(&mut *tx)
1175            .await?;
1176        }
1177
1178        let row = sqlx::query(
1179            "SELECT budget_per_check, budget_daily, tokens_used_today
1180             FROM goals
1181             WHERE id = ?",
1182        )
1183        .bind(goal_id)
1184        .fetch_optional(&mut *tx)
1185        .await?;
1186
1187        tx.commit().await?;
1188
1189        Ok(row.map(|r| GoalTokenBudgetStatus {
1190            budget_per_check: r.get("budget_per_check"),
1191            budget_daily: r.get("budget_daily"),
1192            tokens_used_today: r.get("tokens_used_today"),
1193        }))
1194    }
1195}
1196
1197#[async_trait]
1198impl<S: WorkDatabase> crate::traits::ScheduledRunStore for S {
1199    async fn upsert_scheduled_run_state(&self, state: &ScheduledRunState) -> anyhow::Result<()> {
1200        let health_json = serde_json::to_string(&state.health)?;
1201        sqlx::query(
1202            "INSERT INTO scheduled_run_state (
1203                goal_id, root_task_id, goal_run_id, effective_budget_per_check, tokens_used,
1204                budget_extensions_count, health_json, created_at, updated_at
1205             ) VALUES (?, ?, (SELECT goal_run_id FROM tasks WHERE id = ?), ?, ?, ?, ?, ?, ?)
1206             ON CONFLICT(goal_id) DO UPDATE SET
1207                root_task_id = excluded.root_task_id,
1208                goal_run_id = excluded.goal_run_id,
1209                effective_budget_per_check = excluded.effective_budget_per_check,
1210                tokens_used = excluded.tokens_used,
1211                budget_extensions_count = excluded.budget_extensions_count,
1212                health_json = excluded.health_json,
1213                updated_at = excluded.updated_at",
1214        )
1215        .bind(&state.goal_id)
1216        .bind(&state.root_task_id)
1217        .bind(&state.root_task_id)
1218        .bind(state.effective_budget_per_check)
1219        .bind(state.tokens_used)
1220        .bind(state.budget_extensions_count as i64)
1221        .bind(health_json)
1222        .bind(&state.created_at)
1223        .bind(&state.updated_at)
1224        .execute(self.work_pool())
1225        .await?;
1226        Ok(())
1227    }
1228
1229    async fn get_scheduled_run_state(
1230        &self,
1231        goal_id: &str,
1232    ) -> anyhow::Result<Option<ScheduledRunState>> {
1233        let row = sqlx::query(
1234            "SELECT goal_id, root_task_id, effective_budget_per_check, tokens_used,
1235                    budget_extensions_count, health_json, created_at, updated_at
1236             FROM scheduled_run_state
1237             WHERE goal_id = ?",
1238        )
1239        .bind(goal_id)
1240        .fetch_optional(self.work_pool())
1241        .await?;
1242
1243        Ok(row.map(|r| ScheduledRunState {
1244            goal_id: r.get("goal_id"),
1245            root_task_id: r.get("root_task_id"),
1246            effective_budget_per_check: r.get("effective_budget_per_check"),
1247            tokens_used: r.get("tokens_used"),
1248            budget_extensions_count: r.get::<i64, _>("budget_extensions_count") as usize,
1249            health: r
1250                .try_get::<String, _>("health_json")
1251                .ok()
1252                .and_then(|raw| serde_json::from_str(&raw).ok())
1253                .unwrap_or_default(),
1254            created_at: r.get("created_at"),
1255            updated_at: r.get("updated_at"),
1256        }))
1257    }
1258
1259    async fn get_scheduled_recovery_state(
1260        &self,
1261        goal_id: &str,
1262    ) -> anyhow::Result<Option<crate::traits::ScheduledRecoveryState>> {
1263        let row = sqlx::query(
1264            "SELECT goal_id, consecutive_failures, failure_budget, disposition,
1265                    latest_failure_kind, last_failed_run_id, last_recovery_run_id,
1266                    recovery_attempts, last_recovery_attempt_at, updated_at
1267             FROM scheduled_recovery_state WHERE goal_id = ?",
1268        )
1269        .bind(goal_id)
1270        .fetch_optional(self.work_pool())
1271        .await?;
1272        row.map(scheduled_recovery_state_from_row).transpose()
1273    }
1274
1275    async fn list_escalated_recovery_candidates(
1276        &self,
1277        cooldown_secs: i64,
1278        max_attempts: u16,
1279    ) -> anyhow::Result<Vec<crate::traits::ScheduledRecoveryState>> {
1280        // Only objectives the recovery machine itself paused are eligible;
1281        // an owner's independent pause never triggers automatic recovery.
1282        let rows = sqlx::query(
1283            "SELECT r.goal_id, r.consecutive_failures, r.failure_budget, r.disposition,
1284                    r.latest_failure_kind, r.last_failed_run_id, r.last_recovery_run_id,
1285                    r.recovery_attempts, r.last_recovery_attempt_at, r.updated_at
1286             FROM scheduled_recovery_state r
1287             JOIN goals g ON g.id = r.goal_id
1288             WHERE r.disposition = 'escalated'
1289               AND g.status = 'active'
1290               AND r.recovery_attempts < ?
1291               AND EXISTS (SELECT 1 FROM scheduled_recovery_paused_schedules p
1292                            WHERE p.goal_id = r.goal_id)
1293               AND (julianday('now') - julianday(COALESCE(r.last_recovery_attempt_at, r.updated_at)))
1294                   * 86400.0 >= ?
1295             ORDER BY r.updated_at ASC",
1296        )
1297        .bind(i64::from(max_attempts))
1298        .bind(cooldown_secs)
1299        .fetch_all(self.work_pool())
1300        .await?;
1301        rows.into_iter()
1302            .map(scheduled_recovery_state_from_row)
1303            .collect()
1304    }
1305
1306    async fn record_scheduled_recovery_attempt(&self, goal_id: &str) -> anyhow::Result<()> {
1307        sqlx::query(
1308            "UPDATE scheduled_recovery_state
1309                SET recovery_attempts = recovery_attempts + 1,
1310                    last_recovery_attempt_at = ?
1311              WHERE goal_id = ?",
1312        )
1313        .bind(chrono::Utc::now().to_rfc3339())
1314        .bind(goal_id)
1315        .execute(self.work_pool())
1316        .await?;
1317        Ok(())
1318    }
1319
1320    async fn delete_scheduled_run_state(&self, goal_id: &str) -> anyhow::Result<bool> {
1321        let result = sqlx::query("DELETE FROM scheduled_run_state WHERE goal_id = ?")
1322            .bind(goal_id)
1323            .execute(self.work_pool())
1324            .await?;
1325        Ok(result.rows_affected() > 0)
1326    }
1327}
1328
1329#[async_trait]
1330impl<S: WorkDatabase> crate::traits::TaskDispatchStore for S {
1331    async fn get_pending_tasks_by_priority(&self, limit: i64) -> anyhow::Result<Vec<Task>> {
1332        let rows = sqlx::query(
1333            "SELECT t.id, t.goal_id, t.description, t.status, t.priority, t.task_order,
1334             t.parallel_group, t.depends_on, t.agent_id, t.context, t.result, t.error,
1335             t.blocker, t.idempotent, t.retry_count, t.max_retries, t.created_at,
1336             t.started_at, t.completed_at
1337             FROM tasks t
1338             JOIN goals g ON t.goal_id = g.id
1339                         AND g.domain = 'orchestration'
1340                         AND g.status IN ('active', 'stalled')
1341             WHERE t.status = 'pending'
1342             AND NOT EXISTS (
1343                 SELECT 1 FROM json_each(COALESCE(t.depends_on, '[]')) AS dep
1344                 WHERE NOT EXISTS (
1345                     SELECT 1 FROM tasks d
1346                     WHERE d.id = dep.value
1347                       AND d.goal_run_id = t.goal_run_id
1348                       AND d.status IN ('completed', 'skipped', 'superseded')
1349                 )
1350             )
1351             ORDER BY
1352                 CASE t.priority WHEN 'high' THEN 1 WHEN 'medium' THEN 2 WHEN 'low' THEN 3 ELSE 4 END,
1353                 t.task_order ASC
1354             LIMIT ?",
1355        )
1356        .bind(limit)
1357        .fetch_all(self.work_pool())
1358        .await?;
1359
1360        Ok(rows
1361            .iter()
1362            .map(|r| Task {
1363                id: r.get("id"),
1364                goal_id: r.get("goal_id"),
1365                description: r.get("description"),
1366                status: r.get("status"),
1367                priority: r.get("priority"),
1368                task_order: r.get("task_order"),
1369                parallel_group: r.get("parallel_group"),
1370                depends_on: r.get("depends_on"),
1371                agent_id: r.get("agent_id"),
1372                context: r.get("context"),
1373                result: r.get("result"),
1374                error: r.get("error"),
1375                blocker: r.get("blocker"),
1376                idempotent: r.get::<i32, _>("idempotent") != 0,
1377                retry_count: r.get("retry_count"),
1378                max_retries: r.get("max_retries"),
1379                created_at: r.get("created_at"),
1380                started_at: r.get("started_at"),
1381                completed_at: r.get("completed_at"),
1382            })
1383            .collect())
1384    }
1385
1386    async fn get_stuck_tasks(&self, timeout_secs: i64) -> anyhow::Result<Vec<Task>> {
1387        let rows = sqlx::query(
1388            "SELECT id, goal_id, description, status, priority, task_order,
1389             parallel_group, depends_on, agent_id, context, result, error,
1390             blocker, idempotent, retry_count, max_retries, created_at,
1391             started_at, completed_at
1392             FROM tasks
1393             WHERE status IN ('running', 'claimed')
1394             AND (
1395                EXISTS (
1396                    SELECT 1 FROM task_attempts a
1397                    WHERE a.id = tasks.current_attempt_id
1398                      AND a.status IN ('claimed', 'running')
1399                      AND datetime(a.lease_expires_at) <= datetime('now')
1400                )
1401                OR (
1402                    tasks.current_attempt_id IS NULL
1403                    AND COALESCE(
1404                        (SELECT MAX(ta.created_at) FROM task_activity ta WHERE ta.task_id = tasks.id),
1405                        datetime(tasks.started_at)
1406                    ) < datetime('now', '-' || ? || ' seconds')
1407                )
1408             )
1409             ORDER BY started_at ASC",
1410        )
1411        .bind(timeout_secs)
1412        .fetch_all(self.work_pool())
1413        .await?;
1414
1415        Ok(rows
1416            .iter()
1417            .map(|r| Task {
1418                id: r.get("id"),
1419                goal_id: r.get("goal_id"),
1420                description: r.get("description"),
1421                status: r.get("status"),
1422                priority: r.get("priority"),
1423                task_order: r.get("task_order"),
1424                parallel_group: r.get("parallel_group"),
1425                depends_on: r.get("depends_on"),
1426                agent_id: r.get("agent_id"),
1427                context: r.get("context"),
1428                result: r.get("result"),
1429                error: r.get("error"),
1430                blocker: r.get("blocker"),
1431                idempotent: r.get::<i32, _>("idempotent") != 0,
1432                retry_count: r.get("retry_count"),
1433                max_retries: r.get("max_retries"),
1434                created_at: r.get("created_at"),
1435                started_at: r.get("started_at"),
1436                completed_at: r.get("completed_at"),
1437            })
1438            .collect())
1439    }
1440
1441    async fn get_recently_completed_tasks(&self, since: &str) -> anyhow::Result<Vec<Task>> {
1442        let rows = sqlx::query(
1443            "SELECT id, goal_id, description, status, priority, task_order,
1444             parallel_group, depends_on, agent_id, context, result, error,
1445             blocker, idempotent, retry_count, max_retries, created_at,
1446             started_at, completed_at
1447             FROM tasks
1448             WHERE status = 'completed' AND completed_at > ?
1449             ORDER BY completed_at DESC",
1450        )
1451        .bind(since)
1452        .fetch_all(self.work_pool())
1453        .await?;
1454
1455        Ok(rows
1456            .iter()
1457            .map(|r| Task {
1458                id: r.get("id"),
1459                goal_id: r.get("goal_id"),
1460                description: r.get("description"),
1461                status: r.get("status"),
1462                priority: r.get("priority"),
1463                task_order: r.get("task_order"),
1464                parallel_group: r.get("parallel_group"),
1465                depends_on: r.get("depends_on"),
1466                agent_id: r.get("agent_id"),
1467                context: r.get("context"),
1468                result: r.get("result"),
1469                error: r.get("error"),
1470                blocker: r.get("blocker"),
1471                idempotent: r.get::<i32, _>("idempotent") != 0,
1472                retry_count: r.get("retry_count"),
1473                max_retries: r.get("max_retries"),
1474                created_at: r.get("created_at"),
1475                started_at: r.get("started_at"),
1476                completed_at: r.get("completed_at"),
1477            })
1478            .collect())
1479    }
1480
1481    async fn mark_task_interrupted(&self, task_id: &str) -> anyhow::Result<bool> {
1482        let result = sqlx::query(
1483            "UPDATE tasks SET status = 'interrupted',
1484             completed_at = datetime('now')
1485             WHERE id = ? AND status IN ('running', 'claimed')",
1486        )
1487        .bind(task_id)
1488        .execute(self.work_pool())
1489        .await?;
1490        Ok(result.rows_affected() > 0)
1491    }
1492}
1493
1494#[async_trait]
1495impl<S: WorkDatabase> crate::traits::GoalNotificationStore for S {
1496    async fn count_active_evergreen_goals(&self) -> anyhow::Result<i64> {
1497        let row = sqlx::query(
1498            "SELECT COUNT(*) as cnt FROM goals
1499             WHERE domain = 'orchestration' AND goal_type = 'continuous' AND status = 'active'",
1500        )
1501        .fetch_one(self.work_pool())
1502        .await?;
1503        Ok(row.get::<i64, _>("cnt"))
1504    }
1505
1506    async fn get_goals_needing_notification(&self) -> anyhow::Result<Vec<Goal>> {
1507        let rows = sqlx::query(
1508            "SELECT id, description, domain, goal_type, status, priority, conditions,
1509             context, resources, budget_per_check, budget_daily, tokens_used_today, tokens_used_day,
1510             last_useful_action, created_at, updated_at, completed_at, parent_goal_id,
1511             session_id, notified_at, notification_attempts, dispatch_failures, progress_notes, source_episode_id, legacy_int_id
1512             FROM goals
1513             WHERE domain = 'orchestration'
1514               AND status IN ('completed', 'failed', 'stalled')
1515               AND notified_at IS NULL
1516               AND goal_type = 'finite'
1517               AND notification_attempts < 3",
1518        )
1519        .fetch_all(self.work_pool())
1520        .await?;
1521
1522        Ok(rows
1523            .iter()
1524            .map(|r| {
1525                let progress_notes_json: Option<String> = r.get("progress_notes");
1526                let progress_notes =
1527                    progress_notes_json.and_then(|j| serde_json::from_str(&j).ok());
1528                Goal {
1529                    id: r.get("id"),
1530                    description: r.get("description"),
1531                    domain: r.get("domain"),
1532                    goal_type: r.get("goal_type"),
1533                    status: r.get("status"),
1534                    priority: r.get("priority"),
1535                    conditions: r.get("conditions"),
1536                    context: r.get("context"),
1537                    resources: r.get("resources"),
1538                    budget_per_check: r.get("budget_per_check"),
1539                    budget_daily: r.get("budget_daily"),
1540                    tokens_used_today: r.get("tokens_used_today"),
1541                    tokens_used_day: r.get("tokens_used_day"),
1542                    last_useful_action: r.get("last_useful_action"),
1543                    created_at: r.get("created_at"),
1544                    updated_at: r.get("updated_at"),
1545                    completed_at: r.get("completed_at"),
1546                    parent_goal_id: r.get("parent_goal_id"),
1547                    session_id: r.get("session_id"),
1548                    notified_at: r.get("notified_at"),
1549                    notification_attempts: r.get::<i32, _>("notification_attempts"),
1550                    dispatch_failures: r.get::<i32, _>("dispatch_failures"),
1551                    progress_notes,
1552                    source_episode_id: r.get("source_episode_id"),
1553                    legacy_int_id: r.get("legacy_int_id"),
1554                }
1555            })
1556            .collect())
1557    }
1558
1559    async fn mark_goal_notified(&self, goal_id: &str) -> anyhow::Result<()> {
1560        let now = chrono::Utc::now().to_rfc3339();
1561        sqlx::query("UPDATE goals SET notified_at = ? WHERE id = ?")
1562            .bind(&now)
1563            .bind(goal_id)
1564            .execute(self.work_pool())
1565            .await?;
1566        Ok(())
1567    }
1568
1569    async fn cleanup_stale_goals(&self, stale_hours: i64) -> anyhow::Result<u64> {
1570        let cutoff = (chrono::Utc::now() - chrono::Duration::hours(stale_hours)).to_rfc3339();
1571        let now = chrono::Utc::now().to_rfc3339();
1572
1573        // Finite orchestration goals without schedules: stale active/pending -> failed.
1574        // This is administrative recovery for abandoned work, not a live task
1575        // failure. Mark it notified in the same atomic update so restart
1576        // recovery cannot flood the user with one misleading alert per row.
1577        let result = sqlx::query(
1578            "UPDATE goals
1579             SET status = 'failed', updated_at = ?, completed_at = ?,
1580                 notified_at = COALESCE(notified_at, ?)
1581             WHERE domain = 'orchestration'
1582               AND status IN ('active', 'pending')
1583               AND goal_type = 'finite'
1584               AND updated_at < ?
1585               AND NOT EXISTS (
1586                   SELECT 1 FROM goal_schedules s WHERE s.goal_id = goals.id
1587               )",
1588        )
1589        .bind(&now)
1590        .bind(&now)
1591        .bind(&now)
1592        .bind(&cutoff)
1593        .execute(self.work_pool())
1594        .await?;
1595
1596        Ok(result.rows_affected())
1597    }
1598}
1599
1600fn scheduled_recovery_state_from_row(
1601    row: sqlx::sqlite::SqliteRow,
1602) -> anyhow::Result<crate::traits::ScheduledRecoveryState> {
1603    let disposition_raw: String = row.get("disposition");
1604    let latest_failure_raw: Option<String> = row.get("latest_failure_kind");
1605    Ok(crate::traits::ScheduledRecoveryState {
1606        goal_id: row.get("goal_id"),
1607        consecutive_failures: u16::try_from(row.get::<i64, _>("consecutive_failures"))?,
1608        failure_budget: u16::try_from(row.get::<i64, _>("failure_budget"))?,
1609        disposition: crate::traits::ScheduledRecoveryDisposition::parse(&disposition_raw)
1610            .ok_or_else(|| {
1611                anyhow::anyhow!("invalid scheduled recovery disposition `{disposition_raw}`")
1612            })?,
1613        latest_failure_kind: latest_failure_raw
1614            .as_deref()
1615            .map(|value| {
1616                crate::traits::ScheduledFailureKind::parse(value)
1617                    .ok_or_else(|| anyhow::anyhow!("invalid scheduled failure kind `{value}`"))
1618            })
1619            .transpose()?,
1620        last_failed_run_id: row.get("last_failed_run_id"),
1621        last_recovery_run_id: row.get("last_recovery_run_id"),
1622        recovery_attempts: u16::try_from(row.try_get::<i64, _>("recovery_attempts").unwrap_or(0))?,
1623        last_recovery_attempt_at: row
1624            .try_get::<Option<String>, _>("last_recovery_attempt_at")
1625            .unwrap_or(None),
1626        updated_at: row.get("updated_at"),
1627    })
1628}