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