1use super::*;
2use crate::traits::{
3 DEFAULT_PROJECT_ID, GOAL_RUN_MISSED, GoalRun, HandoffArtifact, TaskAttempt, TaskAttemptPatch,
4 TaskHandoff, TaskJournalEntry, TaskWorkspace, WorkCoordinationStore, WorkGoalSummary,
5 WorkProject, WorkTaskSummary, WorkerProfile,
6};
7
8const DEFAULT_LEASE_SECS: i64 = 180;
9
10fn normalized_lease_secs(lease_secs: i64) -> i64 {
11 if lease_secs <= 0 {
12 DEFAULT_LEASE_SECS
13 } else {
14 lease_secs.clamp(30, 3600)
15 }
16}
17
18fn goal_run_from_row(row: &sqlx::sqlite::SqliteRow) -> GoalRun {
19 GoalRun {
20 id: row.get("id"),
21 project_id: row.get("project_id"),
22 goal_id: row.get("goal_id"),
23 trigger_type: row.get("trigger_type"),
24 schedule_id: row.get("schedule_id"),
25 root_task_id: row.get("root_task_id"),
26 status: row.get("status"),
27 outcome_summary: row.get("outcome_summary"),
28 started_at: row.get("started_at"),
29 completed_at: row.get("completed_at"),
30 created_at: row.get("created_at"),
31 updated_at: row.get("updated_at"),
32 }
33}
34
35fn task_attempt_from_row(row: &sqlx::sqlite::SqliteRow) -> TaskAttempt {
36 TaskAttempt {
37 id: row.get("id"),
38 task_id: row.get("task_id"),
39 goal_run_id: row.get("goal_run_id"),
40 worker_profile_id: row.get("worker_profile_id"),
41 worker_instance_id: row.get("worker_instance_id"),
42 lease_token: row.get("lease_token"),
43 status: row.get("status"),
44 lease_expires_at: row.get("lease_expires_at"),
45 last_heartbeat_at: row.get("last_heartbeat_at"),
46 workspace_id: row.get("workspace_id"),
47 started_at: row.get("started_at"),
48 completed_at: row.get("completed_at"),
49 }
50}
51
52fn worker_profile_from_row(row: &sqlx::sqlite::SqliteRow) -> WorkerProfile {
53 WorkerProfile {
54 id: row.get("id"),
55 project_id: row.get("project_id"),
56 name: row.get("name"),
57 specialist: row.get("specialist"),
58 model: row.get("model"),
59 tools_json: row.get("tools_json"),
60 max_iterations: row.get("max_iterations"),
61 tool_budget: row.get("tool_budget"),
62 timeout_secs: row.get("timeout_secs"),
63 max_concurrency: row.get("max_concurrency"),
64 workspace_policy: row.get("workspace_policy"),
65 memory_scope: row.get("memory_scope"),
66 version: row.get("version"),
67 enabled: row.get::<i64, _>("enabled") != 0,
68 created_at: row.get("created_at"),
69 updated_at: row.get("updated_at"),
70 }
71}
72
73fn task_from_row(row: &sqlx::sqlite::SqliteRow) -> Task {
74 Task {
75 id: row.get("id"),
76 goal_id: row.get("goal_id"),
77 description: row.get("description"),
78 status: row.get("status"),
79 priority: row.get("priority"),
80 task_order: row.get("task_order"),
81 parallel_group: row.get("parallel_group"),
82 depends_on: row.get("depends_on"),
83 agent_id: row.get("agent_id"),
84 context: row.get("context"),
85 result: row.get("result"),
86 error: row.get("error"),
87 blocker: row.get("blocker"),
88 idempotent: row.get::<i64, _>("idempotent") != 0,
89 retry_count: row.get("retry_count"),
90 max_retries: row.get("max_retries"),
91 created_at: row.get("created_at"),
92 started_at: row.get("started_at"),
93 completed_at: row.get("completed_at"),
94 }
95}
96
97async fn insert_journal<S: WorkDatabase>(
98 db: &S,
99 tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
100 entry: &TaskJournalEntry,
101) -> anyhow::Result<()> {
102 let payload = entry.payload.as_deref().map(|text| db.redact_secrets(text));
103 sqlx::query(
104 "INSERT INTO task_journal
105 (id, project_id, goal_id, goal_run_id, task_id, attempt_id,
106 entry_type, actor_type, actor_id, source_channel, body, payload, created_at)
107 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
108 )
109 .bind(&entry.id)
110 .bind(&entry.project_id)
111 .bind(&entry.goal_id)
112 .bind(&entry.goal_run_id)
113 .bind(&entry.task_id)
114 .bind(&entry.attempt_id)
115 .bind(&entry.entry_type)
116 .bind(&entry.actor_type)
117 .bind(&entry.actor_id)
118 .bind(&entry.source_channel)
119 .bind(db.redact_secrets(&entry.body))
120 .bind(payload)
121 .bind(&entry.created_at)
122 .execute(&mut **tx)
123 .await?;
124 Ok(())
125}
126
127async fn task_scope(
128 tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
129 task_id: &str,
130) -> anyhow::Result<Option<(String, String, String)>> {
131 let row = sqlx::query(
132 "SELECT g.project_id, t.goal_id, t.goal_run_id
133 FROM tasks t
134 JOIN goals g ON g.id = t.goal_id
135 WHERE t.id = ?",
136 )
137 .bind(task_id)
138 .fetch_optional(&mut **tx)
139 .await?;
140 Ok(row.map(|row| {
141 (
142 row.get("project_id"),
143 row.get("goal_id"),
144 row.get("goal_run_id"),
145 )
146 }))
147}
148
149async fn close_pending_task_escalations(
150 tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
151 task_id: &str,
152) -> anyhow::Result<()> {
153 sqlx::query(
154 "UPDATE notification_queue
155 SET delivered_at = datetime('now')
156 WHERE task_id = ? AND notification_type = 'escalation'
157 AND delivered_at IS NULL",
158 )
159 .bind(task_id)
160 .execute(&mut **tx)
161 .await?;
162 Ok(())
163}
164
165#[async_trait]
166impl<S: WorkDatabase> WorkCoordinationStore for S {
167 async fn create_work_project(
168 &self,
169 name: &str,
170 description: Option<&str>,
171 ) -> anyhow::Result<WorkProject> {
172 let name = name.trim();
173 anyhow::ensure!(!name.is_empty(), "project name cannot be empty");
174 anyhow::ensure!(name.chars().count() <= 80, "project name is too long");
175 let now = chrono::Utc::now().to_rfc3339();
176 let project = WorkProject {
177 id: format!("project-{}", uuid::Uuid::new_v4()),
178 name: name.to_string(),
179 description: description
180 .map(str::trim)
181 .filter(|v| !v.is_empty())
182 .map(str::to_string),
183 path: None,
184 created_at: now.clone(),
185 updated_at: now,
186 };
187 sqlx::query(
188 "INSERT INTO work_projects (id, name, description, created_at, updated_at)
189 VALUES (?, ?, ?, ?, ?)",
190 )
191 .bind(&project.id)
192 .bind(&project.name)
193 .bind(&project.description)
194 .bind(&project.created_at)
195 .bind(&project.updated_at)
196 .execute(self.work_pool())
197 .await?;
198 Ok(project)
199 }
200
201 async fn list_work_projects(&self) -> anyhow::Result<Vec<WorkProject>> {
202 let rows = sqlx::query(
203 "SELECT id, name, description, path, created_at, updated_at
204 FROM work_projects ORDER BY name COLLATE NOCASE",
205 )
206 .fetch_all(self.work_pool())
207 .await?;
208 Ok(rows
209 .iter()
210 .map(|row| WorkProject {
211 id: row.get("id"),
212 name: row.get("name"),
213 description: row.get("description"),
214 path: row.get("path"),
215 created_at: row.get("created_at"),
216 updated_at: row.get("updated_at"),
217 })
218 .collect())
219 }
220
221 async fn update_work_project(
222 &self,
223 id: &str,
224 name: Option<&str>,
225 path: Option<Option<&str>>,
226 ) -> anyhow::Result<Option<WorkProject>> {
227 let name = name.map(str::trim);
228 if let Some(name) = name {
229 anyhow::ensure!(!name.is_empty(), "project name cannot be empty");
230 anyhow::ensure!(name.chars().count() <= 80, "project name is too long");
231 }
232 let path = path.map(|p| p.map(str::trim).filter(|p| !p.is_empty()));
233 let now = chrono::Utc::now().to_rfc3339();
234 let updated = sqlx::query(
235 "UPDATE work_projects
236 SET name = COALESCE(?, name),
237 path = CASE WHEN ? THEN ? ELSE path END,
238 updated_at = ?
239 WHERE id = ?",
240 )
241 .bind(name)
242 .bind(path.is_some())
243 .bind(path.flatten())
244 .bind(&now)
245 .bind(id)
246 .execute(self.work_pool())
247 .await?
248 .rows_affected();
249 if updated == 0 {
250 return Ok(None);
251 }
252 Ok(self
253 .list_work_projects()
254 .await?
255 .into_iter()
256 .find(|project| project.id == id))
257 }
258
259 async fn delete_work_project(&self, id: &str) -> anyhow::Result<bool> {
260 anyhow::ensure!(
261 id != DEFAULT_PROJECT_ID,
262 "conversations in no project cannot be deleted"
263 );
264 let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
265 for moved in [
266 "UPDATE session_work_projects SET project_id = ?, updated_at = datetime('now') WHERE project_id = ?",
267 "UPDATE goals SET project_id = ? WHERE project_id = ?",
268 "UPDATE goal_runs SET project_id = ? WHERE project_id = ?",
269 "UPDATE task_journal SET project_id = ? WHERE project_id = ?",
270 ] {
271 sqlx::query(moved)
272 .bind(DEFAULT_PROJECT_ID)
273 .bind(id)
274 .execute(&mut *tx)
275 .await?;
276 }
277 for gone in [
278 "DELETE FROM channel_work_projects WHERE project_id = ?",
279 "DELETE FROM worker_profiles WHERE project_id = ?",
280 ] {
281 sqlx::query(gone).bind(id).execute(&mut *tx).await?;
282 }
283 let deleted = sqlx::query("DELETE FROM work_projects WHERE id = ?")
284 .bind(id)
285 .execute(&mut *tx)
286 .await?
287 .rows_affected();
288 if deleted == 0 {
289 tx.rollback().await?;
290 return Ok(false);
291 }
292 tx.commit().await?;
293 Ok(true)
294 }
295
296 async fn session_work_projects(&self) -> anyhow::Result<Vec<(String, String)>> {
297 Ok(sqlx::query_as::<_, (String, String)>(
298 "SELECT session_id, project_id FROM session_work_projects WHERE project_id != ?",
299 )
300 .bind(DEFAULT_PROJECT_ID)
301 .fetch_all(self.work_pool())
302 .await?)
303 }
304
305 async fn get_session_work_project(&self, session_id: &str) -> anyhow::Result<String> {
306 let project = sqlx::query_scalar::<_, String>(
307 "SELECT project_id FROM session_work_projects WHERE session_id = ?",
308 )
309 .bind(session_id)
310 .fetch_optional(self.work_pool())
311 .await?;
312 Ok(project.unwrap_or_else(|| DEFAULT_PROJECT_ID.to_string()))
313 }
314
315 async fn set_session_work_project(
316 &self,
317 session_id: &str,
318 project_id: &str,
319 ) -> anyhow::Result<bool> {
320 let exists =
321 sqlx::query_scalar::<_, i64>("SELECT 1 FROM work_projects WHERE id = ? LIMIT 1")
322 .bind(project_id)
323 .fetch_optional(self.work_pool())
324 .await?
325 .is_some();
326 if !exists {
327 return Ok(false);
328 }
329 sqlx::query(
330 "INSERT INTO session_work_projects (session_id, project_id, updated_at)
331 VALUES (?, ?, datetime('now'))
332 ON CONFLICT(session_id) DO UPDATE
333 SET project_id = excluded.project_id, updated_at = excluded.updated_at",
334 )
335 .bind(session_id)
336 .bind(project_id)
337 .execute(self.work_pool())
338 .await?;
339 Ok(true)
340 }
341
342 async fn channel_work_projects(&self) -> anyhow::Result<Vec<(String, String)>> {
343 Ok(sqlx::query_as::<_, (String, String)>(
344 "SELECT channel, project_id FROM channel_work_projects ORDER BY channel",
345 )
346 .fetch_all(self.work_pool())
347 .await?)
348 }
349
350 async fn set_channel_work_project(
351 &self,
352 channel: &str,
353 project_id: Option<&str>,
354 ) -> anyhow::Result<bool> {
355 let Some(project_id) = project_id.filter(|id| *id != DEFAULT_PROJECT_ID) else {
356 sqlx::query("DELETE FROM channel_work_projects WHERE channel = ?")
357 .bind(channel)
358 .execute(self.work_pool())
359 .await?;
360 return Ok(true);
361 };
362 let exists =
363 sqlx::query_scalar::<_, i64>("SELECT 1 FROM work_projects WHERE id = ? LIMIT 1")
364 .bind(project_id)
365 .fetch_optional(self.work_pool())
366 .await?
367 .is_some();
368 if !exists {
369 return Ok(false);
370 }
371 sqlx::query(
372 "INSERT INTO channel_work_projects (channel, project_id, updated_at)
373 VALUES (?, ?, datetime('now'))
374 ON CONFLICT(channel) DO UPDATE
375 SET project_id = excluded.project_id, updated_at = excluded.updated_at",
376 )
377 .bind(channel)
378 .bind(project_id)
379 .execute(self.work_pool())
380 .await?;
381 Ok(true)
382 }
383
384 async fn place_chat_by_channel(&self, session_id: &str, channel: &str) -> anyhow::Result<bool> {
385 let placed = sqlx::query(
388 "INSERT INTO session_work_projects (session_id, project_id, updated_at)
389 SELECT ?, project_id, datetime('now') FROM channel_work_projects
390 WHERE channel = ?
391 ON CONFLICT(session_id) DO NOTHING",
392 )
393 .bind(session_id)
394 .bind(channel)
395 .execute(self.work_pool())
396 .await?;
397 Ok(placed.rows_affected() > 0)
398 }
399
400 async fn start_goal_run(
401 &self,
402 goal_id: &str,
403 trigger_type: &str,
404 schedule_id: Option<&str>,
405 root_task_id: Option<&str>,
406 ) -> anyhow::Result<GoalRun> {
407 anyhow::ensure!(
408 matches!(
409 trigger_type,
410 "finite" | "scheduled" | "manual" | "mandate" | "recovery" | "legacy"
411 ),
412 "unsupported goal run trigger type"
413 );
414 let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
415 let project_id = sqlx::query_scalar::<_, String>(
416 "SELECT project_id FROM goals
417 WHERE id = ? AND domain = 'orchestration'",
418 )
419 .bind(goal_id)
420 .fetch_optional(&mut *tx)
421 .await?
422 .ok_or_else(|| anyhow::anyhow!("goal not found or not dispatchable"))?;
423
424 if let Some(row) = sqlx::query(
425 "SELECT id, project_id, goal_id, trigger_type, schedule_id, root_task_id,
426 status, outcome_summary, started_at, completed_at, created_at, updated_at
427 FROM goal_runs
428 WHERE goal_id = ? AND status IN ('pending', 'running', 'blocked')
429 ORDER BY julianday(started_at) DESC, id DESC LIMIT 1",
430 )
431 .bind(goal_id)
432 .fetch_optional(&mut *tx)
433 .await?
434 {
435 let mut existing = goal_run_from_row(&row);
436 let task_count =
437 sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM tasks WHERE goal_run_id = ?")
438 .bind(&existing.id)
439 .fetch_one(&mut *tx)
440 .await?;
441 if task_count == 0 {
442 sqlx::query(
443 "UPDATE goal_runs
444 SET trigger_type = ?, schedule_id = ?, root_task_id = COALESCE(?, root_task_id),
445 status = 'pending', updated_at = datetime('now')
446 WHERE id = ?",
447 )
448 .bind(trigger_type)
449 .bind(schedule_id)
450 .bind(root_task_id)
451 .bind(&existing.id)
452 .execute(&mut *tx)
453 .await?;
454 existing.trigger_type = trigger_type.to_string();
455 existing.schedule_id = schedule_id.map(str::to_string);
456 if root_task_id.is_some() {
457 existing.root_task_id = root_task_id.map(str::to_string);
458 }
459 existing.status = "pending".to_string();
460 existing.updated_at = chrono::Utc::now().to_rfc3339();
461 tx.commit().await?;
462 return Ok(existing);
463 }
464 if trigger_type != "scheduled" {
465 anyhow::bail!(
466 "goal already has an open run {}; finish or cancel it before starting another",
467 existing.id
468 );
469 }
470 }
471
472 let mut run = GoalRun::new(goal_id, &project_id, trigger_type);
473 run.schedule_id = schedule_id.map(str::to_string);
474 run.root_task_id = root_task_id.map(str::to_string);
475 sqlx::query(
476 "INSERT INTO goal_runs
477 (id, project_id, goal_id, trigger_type, schedule_id, root_task_id,
478 status, outcome_summary, started_at, completed_at, created_at, updated_at)
479 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
480 )
481 .bind(&run.id)
482 .bind(&run.project_id)
483 .bind(&run.goal_id)
484 .bind(&run.trigger_type)
485 .bind(&run.schedule_id)
486 .bind(&run.root_task_id)
487 .bind(&run.status)
488 .bind(&run.outcome_summary)
489 .bind(&run.started_at)
490 .bind(&run.completed_at)
491 .bind(&run.created_at)
492 .bind(&run.updated_at)
493 .execute(&mut *tx)
494 .await?;
495 tx.commit().await?;
496 Ok(run)
497 }
498
499 async fn record_missed_goal_run(
500 &self,
501 goal_id: &str,
502 schedule_id: Option<&str>,
503 due_at: &str,
504 summary: &str,
505 ) -> anyhow::Result<GoalRun> {
506 let project_id = sqlx::query_scalar::<_, String>(
507 "SELECT project_id FROM goals
508 WHERE id = ? AND domain = 'orchestration'",
509 )
510 .bind(goal_id)
511 .fetch_optional(self.work_pool())
512 .await?
513 .ok_or_else(|| anyhow::anyhow!("goal not found or not dispatchable"))?;
514 let mut run = GoalRun::new(goal_id, &project_id, "scheduled");
518 run.schedule_id = schedule_id.map(str::to_string);
519 run.status = GOAL_RUN_MISSED.to_string();
520 run.outcome_summary = Some(summary.to_string());
521 run.started_at = due_at.to_string();
522 run.completed_at = Some(run.created_at.clone());
523 sqlx::query(
524 "INSERT INTO goal_runs
525 (id, project_id, goal_id, trigger_type, schedule_id, root_task_id,
526 status, outcome_summary, started_at, completed_at, created_at, updated_at)
527 VALUES (?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?)",
528 )
529 .bind(&run.id)
530 .bind(&run.project_id)
531 .bind(&run.goal_id)
532 .bind(&run.trigger_type)
533 .bind(&run.schedule_id)
534 .bind(&run.status)
535 .bind(&run.outcome_summary)
536 .bind(&run.started_at)
537 .bind(&run.completed_at)
538 .bind(&run.created_at)
539 .bind(&run.updated_at)
540 .execute(self.work_pool())
541 .await?;
542 Ok(run)
543 }
544
545 async fn get_current_goal_run(&self, goal_id: &str) -> anyhow::Result<Option<GoalRun>> {
546 let row = sqlx::query(
547 "SELECT id, project_id, goal_id, trigger_type, schedule_id, root_task_id,
548 status, outcome_summary, started_at, completed_at, created_at, updated_at
549 FROM goal_runs
550 WHERE goal_id = ? AND status IN ('pending', 'running', 'blocked')
551 ORDER BY julianday(started_at) DESC, id DESC LIMIT 1",
552 )
553 .bind(goal_id)
554 .fetch_optional(self.work_pool())
555 .await?;
556 Ok(row.as_ref().map(goal_run_from_row))
557 }
558
559 async fn get_goal_runs(&self, goal_id: &str) -> anyhow::Result<Vec<GoalRun>> {
560 let rows = sqlx::query(
561 "SELECT id, project_id, goal_id, trigger_type, schedule_id, root_task_id,
562 status, outcome_summary, started_at, completed_at, created_at, updated_at
563 FROM goal_runs WHERE goal_id = ?
564 ORDER BY julianday(started_at) DESC, id DESC",
565 )
566 .bind(goal_id)
567 .fetch_all(self.work_pool())
568 .await?;
569 Ok(rows.iter().map(goal_run_from_row).collect())
570 }
571
572 async fn get_goal_run_for_task(&self, task_id: &str) -> anyhow::Result<Option<GoalRun>> {
573 let row = sqlx::query(
574 "SELECT gr.id, gr.project_id, gr.goal_id, gr.trigger_type, gr.schedule_id,
575 gr.root_task_id, gr.status, gr.outcome_summary, gr.started_at,
576 gr.completed_at, gr.created_at, gr.updated_at
577 FROM tasks AS t
578 JOIN goal_runs AS gr ON gr.id = t.goal_run_id
579 WHERE t.id = ?",
580 )
581 .bind(task_id)
582 .fetch_optional(self.work_pool())
583 .await?;
584 Ok(row.as_ref().map(goal_run_from_row))
585 }
586
587 async fn get_tasks_for_goal_run(&self, run_id: &str) -> anyhow::Result<Vec<Task>> {
588 let rows = sqlx::query(
589 "SELECT id, goal_id, description, status, priority, task_order,
590 parallel_group, depends_on, agent_id, context, result, error, blocker,
591 idempotent, retry_count, max_retries, created_at, started_at, completed_at
592 FROM tasks WHERE goal_run_id = ?
593 ORDER BY task_order ASC, julianday(created_at) ASC, id ASC",
594 )
595 .bind(run_id)
596 .fetch_all(self.work_pool())
597 .await?;
598 Ok(rows.iter().map(task_from_row).collect())
599 }
600
601 async fn finish_goal_run(
602 &self,
603 run_id: &str,
604 status: &str,
605 summary: Option<&str>,
606 ) -> anyhow::Result<bool> {
607 anyhow::ensure!(
608 matches!(status, "completed" | "failed" | "blocked" | "cancelled"),
609 "unsupported terminal run status"
610 );
611 let completed_at = if status == "blocked" {
612 None
613 } else {
614 Some(chrono::Utc::now().to_rfc3339())
615 };
616 let now = chrono::Utc::now().to_rfc3339();
617 let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
623 let run = sqlx::query(
624 "SELECT gr.goal_id, gr.status AS prior_status, gr.trigger_type, gr.root_task_id,
625 g.goal_type, g.session_id, g.description, g.context AS goal_context,
626 EXISTS(SELECT 1 FROM goal_schedules s WHERE s.goal_id = gr.goal_id) AS has_schedule,
627 json_extract(t.context, '$.recovery_for_run') AS recovery_for_run
628 FROM goal_runs gr
629 JOIN goals g ON g.id = gr.goal_id
630 LEFT JOIN tasks t ON t.id = gr.root_task_id
631 WHERE gr.id = ?",
632 )
633 .bind(run_id)
634 .fetch_optional(&mut *tx)
635 .await?;
636 let Some(run) = run else {
637 tx.rollback().await?;
638 return Ok(false);
639 };
640 let goal_id: String = run.get("goal_id");
641 let prior_status: String = run.get("prior_status");
642 let trigger_type: String = run.get("trigger_type");
643 let goal_type: String = run.get("goal_type");
644 let session_id: String = run.get("session_id");
645 let has_schedule = run.get::<i64, _>("has_schedule") != 0;
646 let recovery_for_run: Option<String> = run.get("recovery_for_run");
647 if trigger_type == "scheduled" && status == "completed" {
648 let root_task_id: Option<String> = run.get("root_task_id");
653 let incomplete_task_count = sqlx::query_scalar::<_, i64>(
654 "SELECT COUNT(*) FROM tasks
655 WHERE goal_run_id = ?
656 AND NOT (id IS ? AND status IN ('pending', 'claimed', 'running'))
657 -- Mirrors Task::satisfies_run_completion: skipped and
658 -- superseded work is resolved whatever note it carries;
659 -- a completed task must be clean.
660 AND status NOT IN ('skipped', 'superseded')
661 AND (status != 'completed'
662 OR length(trim(COALESCE(error, ''))) > 0
663 OR length(trim(COALESCE(blocker, ''))) > 0)",
664 )
665 .bind(run_id)
666 .bind(root_task_id)
667 .fetch_one(&mut *tx)
668 .await?;
669 anyhow::ensure!(
670 incomplete_task_count == 0,
671 "scheduled run cannot complete while {incomplete_task_count} task obligation(s) remain unresolved"
672 );
673 }
674 let result = sqlx::query(
675 "UPDATE goal_runs
676 SET status = ?, outcome_summary = ?, completed_at = ?,
677 updated_at = datetime('now')
678 WHERE id = ? AND status IN ('pending', 'running', 'blocked')",
679 )
680 .bind(status)
681 .bind(summary)
682 .bind(completed_at)
683 .bind(run_id)
684 .execute(&mut *tx)
685 .await?;
686 if result.rows_affected() == 0 {
687 tx.rollback().await?;
688 return Ok(false);
689 }
690 if trigger_type == "scheduled" && matches!(status, "failed" | "cancelled") {
691 sqlx::query(
692 "UPDATE tasks
693 SET status = 'cancelled',
694 error = COALESCE(NULLIF(error, ''),
695 'Parent scheduled occurrence reached a terminal state.'),
696 completed_at = COALESCE(completed_at, ?)
697 WHERE goal_run_id = ?
698 AND status IN ('pending', 'claimed', 'running')",
699 )
700 .bind(&now)
701 .bind(run_id)
702 .execute(&mut *tx)
703 .await?;
704 }
705
706 let scheduled_objective = goal_type == "continuous" && has_schedule;
707 if scheduled_objective {
708 let failure_budget: i64 = 3;
711 let recovery_proof_receipt_ids = if recovery_for_run.is_some() {
720 sqlx::query_scalar::<_, String>(
721 "SELECT json_extract(e.data, '$.tool_call_id') FROM events e
722 JOIN tasks t ON t.id = json_extract(e.data, '$.task_id')
723 WHERE t.goal_run_id = ?1 AND e.event_type = 'tool_result'
724 AND json_extract(t.context, '$.terminal_recovery') = 1
725 AND json_extract(t.context, '$.recovery_for_run') = ?2
726 AND json_extract(e.data, '$.receipt.outcome_status') = 'succeeded'
727 AND json_extract(e.data, '$.receipt.outcome_evidence')
728 IN ('tool_reported', 'structured_metadata', 'durable_replay')
729 UNION
730 SELECT json_extract(e.data, '$.tool_call_id') FROM events e
731 JOIN task_attempts ta ON ta.worker_instance_id = e.session_id
732 JOIN tasks t ON t.id = ta.task_id
733 WHERE t.goal_run_id = ?1 AND e.event_type = 'tool_result'
734 AND json_extract(t.context, '$.terminal_recovery') = 1
735 AND json_extract(t.context, '$.recovery_for_run') = ?2
736 AND json_extract(e.data, '$.receipt.outcome_status') = 'succeeded'
737 AND json_extract(e.data, '$.receipt.outcome_evidence')
738 IN ('tool_reported', 'structured_metadata', 'durable_replay')",
739 )
740 .bind(run_id)
741 .bind(recovery_for_run.as_deref())
742 .fetch_all(&mut *tx)
743 .await?
744 } else {
745 Vec::new()
746 };
747 let recovery_completion_verified =
748 recovery_for_run.is_none() || !recovery_proof_receipt_ids.is_empty();
749
750 if status == "completed" && recovery_completion_verified {
751 sqlx::query(
752 "INSERT INTO scheduled_recovery_state
753 (goal_id, consecutive_failures, failure_budget, disposition,
754 latest_failure_kind, last_failed_run_id, last_recovery_run_id, updated_at)
755 VALUES (?, 0, ?, 'healthy', NULL, NULL, ?, ?)
756 ON CONFLICT(goal_id) DO UPDATE SET
757 consecutive_failures = 0,
758 failure_budget = excluded.failure_budget,
759 disposition = 'healthy',
760 latest_failure_kind = NULL,
761 last_recovery_run_id = COALESCE(excluded.last_recovery_run_id,
762 scheduled_recovery_state.last_recovery_run_id),
763 updated_at = excluded.updated_at",
764 )
765 .bind(&goal_id)
766 .bind(failure_budget)
767 .bind(recovery_for_run.as_ref().map(|_| run_id))
768 .bind(&now)
769 .execute(&mut *tx)
770 .await?;
771 sqlx::query(
774 "UPDATE goal_schedules SET is_paused = 0, updated_at = ?
775 WHERE id IN (
776 SELECT schedule_id FROM scheduled_recovery_paused_schedules
777 WHERE goal_id = ?
778 )",
779 )
780 .bind(&now)
781 .bind(&goal_id)
782 .execute(&mut *tx)
783 .await?;
784 sqlx::query("DELETE FROM scheduled_recovery_paused_schedules WHERE goal_id = ?")
785 .bind(&goal_id)
786 .execute(&mut *tx)
787 .await?;
788 } else if (matches!(status, "failed" | "blocked")
789 || status == "completed" && !recovery_completion_verified)
790 && prior_status != "blocked"
795 {
796 let authorization_blocked = sqlx::query_scalar::<_, i64>(
797 "SELECT 1 FROM events e
798 JOIN tasks t ON t.id = json_extract(e.data, '$.task_id')
799 WHERE t.goal_run_id = ? AND e.event_type = 'tool_result'
800 AND json_extract(e.data, '$.receipt.authorization_preflight.status')
801 IN ('blocked', 'unverifiable') LIMIT 1",
802 )
803 .bind(run_id)
804 .fetch_optional(&mut *tx)
805 .await?
806 .is_some();
807 let retryable_tool = sqlx::query_scalar::<_, i64>(
808 "SELECT 1 FROM events e
809 JOIN tasks t ON t.id = json_extract(e.data, '$.task_id')
810 WHERE t.goal_run_id = ? AND e.event_type = 'tool_result'
811 AND json_extract(e.data, '$.receipt.outcome_status') = 'failed_retryable'
812 LIMIT 1",
813 )
814 .bind(run_id)
815 .fetch_optional(&mut *tx)
816 .await?
817 .is_some();
818 let permanent_tool = sqlx::query_scalar::<_, i64>(
819 "SELECT 1 FROM events e
820 JOIN tasks t ON t.id = json_extract(e.data, '$.task_id')
821 WHERE t.goal_run_id = ? AND e.event_type = 'tool_result'
822 AND json_extract(e.data, '$.receipt.outcome_status')
823 IN ('failed_permanent', 'blocked') LIMIT 1",
824 )
825 .bind(run_id)
826 .fetch_optional(&mut *tx)
827 .await?
828 .is_some();
829 let task_failed = sqlx::query_scalar::<_, i64>(
830 "SELECT 1 FROM tasks WHERE goal_run_id = ?
831 AND (status IN ('failed', 'interrupted')
832 OR error IS NOT NULL OR blocker IS NOT NULL) LIMIT 1",
833 )
834 .bind(run_id)
835 .fetch_optional(&mut *tx)
836 .await?
837 .is_some();
838 let failure_kind = if authorization_blocked {
839 crate::traits::ScheduledFailureKind::AuthorizationBlocked
840 } else if retryable_tool {
841 crate::traits::ScheduledFailureKind::RetryableTool
842 } else if permanent_tool {
843 crate::traits::ScheduledFailureKind::PermanentTool
844 } else if task_failed {
845 crate::traits::ScheduledFailureKind::TaskFailed
846 } else {
847 crate::traits::ScheduledFailureKind::OutcomeUnproven
848 };
849 let previous_failures = sqlx::query_scalar::<_, i64>(
850 "SELECT consecutive_failures FROM scheduled_recovery_state
851 WHERE goal_id = ?",
852 )
853 .bind(&goal_id)
854 .fetch_optional(&mut *tx)
855 .await?
856 .unwrap_or(0);
857 let consecutive_failures = previous_failures.saturating_add(1);
858 let escalated = consecutive_failures >= failure_budget;
859 let newly_escalated = escalated && previous_failures < failure_budget;
860 let disposition = if escalated {
861 crate::traits::ScheduledRecoveryDisposition::Escalated
862 } else {
863 crate::traits::ScheduledRecoveryDisposition::Recovering
864 };
865 sqlx::query(
866 "INSERT INTO scheduled_recovery_state
867 (goal_id, consecutive_failures, failure_budget, disposition,
868 latest_failure_kind, last_failed_run_id, last_recovery_run_id, updated_at)
869 VALUES (?, ?, ?, ?, ?, ?, ?, ?)
870 ON CONFLICT(goal_id) DO UPDATE SET
871 consecutive_failures = excluded.consecutive_failures,
872 failure_budget = excluded.failure_budget,
873 disposition = excluded.disposition,
874 latest_failure_kind = excluded.latest_failure_kind,
875 last_failed_run_id = excluded.last_failed_run_id,
876 last_recovery_run_id = COALESCE(excluded.last_recovery_run_id,
877 scheduled_recovery_state.last_recovery_run_id),
878 updated_at = excluded.updated_at",
879 )
880 .bind(&goal_id)
881 .bind(consecutive_failures)
882 .bind(failure_budget)
883 .bind(disposition.as_str())
884 .bind(failure_kind.as_str())
885 .bind(run_id)
886 .bind(recovery_for_run.as_ref().map(|_| run_id))
887 .bind(&now)
888 .execute(&mut *tx)
889 .await?;
890
891 if newly_escalated {
892 sqlx::query(
893 "INSERT OR IGNORE INTO scheduled_recovery_paused_schedules
894 (schedule_id, goal_id, paused_at)
895 SELECT id, goal_id, ? FROM goal_schedules
896 WHERE goal_id = ? AND is_paused = 0",
897 )
898 .bind(&now)
899 .bind(&goal_id)
900 .execute(&mut *tx)
901 .await?;
902 sqlx::query(
903 "UPDATE goal_schedules SET is_paused = 1, updated_at = ?
904 WHERE goal_id = ?",
905 )
906 .bind(&now)
907 .bind(&goal_id)
908 .execute(&mut *tx)
909 .await?;
910 let notification_id = format!(
911 "scheduled-recovery-budget:{}:{}",
912 goal_id, consecutive_failures
913 );
914 sqlx::query(
915 "INSERT OR IGNORE INTO notification_queue
916 (id, goal_id, session_id, notification_type, priority, message,
917 created_at, delivered_at, attempts, expires_at, task_id, action_token)
918 VALUES (?, ?, ?, 'escalation', 'critical', ?, ?, NULL, 0, NULL, NULL, NULL)",
919 )
920 .bind(notification_id)
921 .bind(&goal_id)
922 .bind(&session_id)
923 .bind(paused_notice(
924 &crate::automations::name_from_context(
925 run.get::<Option<String>, _>("goal_context").as_deref(),
926 )
927 .unwrap_or_else(|| {
928 aidaemon_tools::sanitize::short_goal_label(
929 &run.get::<String, _>("description"),
930 )
931 }),
932 consecutive_failures,
933 failure_kind,
934 summary,
935 ))
936 .bind(&now)
937 .execute(&mut *tx)
938 .await?;
939 }
940 }
941
942 if let Some(failed_run_id) = recovery_for_run.as_deref() {
943 let link_status = if status == "completed" && recovery_completion_verified {
944 "verified"
945 } else if matches!(status, "completed" | "failed" | "cancelled") {
946 "failed"
947 } else {
948 "recovering"
949 };
950 sqlx::query(
951 "INSERT INTO goal_run_recovery_links
952 (failed_run_id, recovery_run_id, outcome_status,
953 proof_receipt_ids_json, created_at, updated_at)
954 VALUES (?, ?, ?, ?, ?, ?)
955 ON CONFLICT(failed_run_id, recovery_run_id) DO UPDATE SET
956 outcome_status = excluded.outcome_status,
957 proof_receipt_ids_json = excluded.proof_receipt_ids_json,
958 updated_at = excluded.updated_at",
959 )
960 .bind(failed_run_id)
961 .bind(run_id)
962 .bind(link_status)
963 .bind(serde_json::to_string(&recovery_proof_receipt_ids)?)
964 .bind(&now)
965 .bind(&now)
966 .execute(&mut *tx)
967 .await?;
968 }
969 }
970 tx.commit().await?;
971 Ok(true)
972 }
973
974 async fn claim_task_with_lease(
975 &self,
976 task_id: &str,
977 worker_instance_id: &str,
978 worker_profile_id: Option<&str>,
979 lease_secs: i64,
980 ) -> anyhow::Result<Option<TaskAttempt>> {
981 let lease_secs = normalized_lease_secs(lease_secs);
982 let now = chrono::Utc::now();
983 let expires = now + chrono::Duration::seconds(lease_secs);
984 let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
985 let row = sqlx::query(
986 "SELECT t.goal_id, t.goal_run_id, t.worker_profile_id, g.project_id
987 FROM tasks t JOIN goals g ON g.id = t.goal_id
988 WHERE t.id = ? AND t.status IN ('pending', 'claimed')
989 AND t.current_attempt_id IS NULL",
990 )
991 .bind(task_id)
992 .fetch_optional(&mut *tx)
993 .await?;
994 let Some(row) = row else {
995 return Ok(None);
996 };
997 let goal_id: String = row.get("goal_id");
998 let goal_run_id: String = row.get("goal_run_id");
999 let project_id: String = row.get("project_id");
1000 let assigned_profile_id: Option<String> = row.get("worker_profile_id");
1001 let profile_id = assigned_profile_id
1002 .or_else(|| worker_profile_id.map(str::to_string))
1003 .unwrap_or_else(|| "profile-executor".to_string());
1004
1005 let unmet = sqlx::query_scalar::<_, i64>(
1006 "SELECT COUNT(*)
1007 FROM task_dependencies dep
1008 WHERE dep.task_id = ?
1009 AND NOT EXISTS (
1010 SELECT 1 FROM tasks d
1011 WHERE d.id = dep.depends_on_task_id
1012 AND d.goal_run_id = ?
1013 AND d.status IN ('completed', 'skipped', 'superseded')
1014 )",
1015 )
1016 .bind(task_id)
1017 .bind(&goal_run_id)
1018 .fetch_one(&mut *tx)
1019 .await?;
1020 if unmet > 0 {
1021 return Ok(None);
1022 }
1023
1024 let profile = sqlx::query(
1025 "SELECT max_concurrency FROM worker_profiles
1026 WHERE id = ? AND enabled = 1
1027 AND (project_id IS NULL OR project_id = ?)",
1028 )
1029 .bind(&profile_id)
1030 .bind(&project_id)
1031 .fetch_optional(&mut *tx)
1032 .await?;
1033 let Some(profile) = profile else {
1034 anyhow::bail!("worker profile '{}' is unavailable", profile_id);
1035 };
1036 sqlx::query("UPDATE worker_profiles SET updated_at = updated_at WHERE id = ?")
1039 .bind(&profile_id)
1040 .execute(&mut *tx)
1041 .await?;
1042 let max_concurrency: i64 = profile.get("max_concurrency");
1043 let active = sqlx::query_scalar::<_, i64>(
1044 "SELECT COUNT(*) FROM task_attempts
1045 WHERE worker_profile_id = ?
1046 AND status IN ('claimed', 'running')
1047 AND datetime(lease_expires_at) > datetime('now')",
1048 )
1049 .bind(&profile_id)
1050 .fetch_one(&mut *tx)
1051 .await?;
1052 if active >= max_concurrency {
1053 return Ok(None);
1054 }
1055
1056 let attempt = TaskAttempt {
1057 id: uuid::Uuid::new_v4().to_string(),
1058 task_id: task_id.to_string(),
1059 goal_run_id: goal_run_id.clone(),
1060 worker_profile_id: Some(profile_id.clone()),
1061 worker_instance_id: worker_instance_id.to_string(),
1062 lease_token: uuid::Uuid::new_v4().to_string(),
1063 status: "claimed".to_string(),
1064 lease_expires_at: expires.to_rfc3339(),
1065 last_heartbeat_at: now.to_rfc3339(),
1066 workspace_id: None,
1067 started_at: now.to_rfc3339(),
1068 completed_at: None,
1069 };
1070 sqlx::query(
1071 "INSERT INTO task_attempts
1072 (id, task_id, goal_run_id, worker_profile_id, worker_instance_id,
1073 lease_token, status, lease_expires_at, last_heartbeat_at,
1074 workspace_id, started_at, completed_at)
1075 VALUES (?, ?, ?, ?, ?, ?, 'claimed', ?, ?, NULL, ?, NULL)",
1076 )
1077 .bind(&attempt.id)
1078 .bind(&attempt.task_id)
1079 .bind(&attempt.goal_run_id)
1080 .bind(&attempt.worker_profile_id)
1081 .bind(&attempt.worker_instance_id)
1082 .bind(&attempt.lease_token)
1083 .bind(&attempt.lease_expires_at)
1084 .bind(&attempt.last_heartbeat_at)
1085 .bind(&attempt.started_at)
1086 .execute(&mut *tx)
1087 .await?;
1088 let updated = sqlx::query(
1089 "UPDATE tasks
1090 SET status = 'claimed', agent_id = ?, current_attempt_id = ?,
1091 worker_profile_id = ?, started_at = COALESCE(started_at, datetime('now')),
1092 result = NULL, error = NULL, blocker = NULL, completed_at = NULL,
1093 updated_at = datetime('now'), version = version + 1
1094 WHERE id = ? AND status IN ('pending', 'claimed')
1095 AND current_attempt_id IS NULL",
1096 )
1097 .bind(worker_instance_id)
1098 .bind(&attempt.id)
1099 .bind(&profile_id)
1100 .bind(task_id)
1101 .execute(&mut *tx)
1102 .await?;
1103 if updated.rows_affected() == 0 {
1104 tx.rollback().await?;
1105 return Ok(None);
1106 }
1107 sqlx::query(
1108 "UPDATE goal_runs SET status = 'running', updated_at = datetime('now')
1109 WHERE id = ? AND status IN ('pending', 'blocked', 'claimed')",
1110 )
1111 .bind(&goal_run_id)
1112 .execute(&mut *tx)
1113 .await?;
1114 let journal = TaskJournalEntry::new(
1115 &project_id,
1116 &goal_id,
1117 &goal_run_id,
1118 "assigned",
1119 "system",
1120 worker_instance_id,
1121 &format!("Claimed by worker profile {}", profile_id),
1122 )
1123 .with_task(Some(task_id), Some(&attempt.id));
1124 insert_journal(self, &mut tx, &journal).await?;
1125 tx.commit().await?;
1126 Ok(Some(attempt))
1127 }
1128
1129 async fn get_current_task_attempt(&self, task_id: &str) -> anyhow::Result<Option<TaskAttempt>> {
1130 let row = sqlx::query(
1131 "SELECT a.id, a.task_id, a.goal_run_id, a.worker_profile_id,
1132 a.worker_instance_id, a.lease_token, a.status,
1133 a.lease_expires_at, a.last_heartbeat_at, a.workspace_id,
1134 a.started_at, a.completed_at
1135 FROM task_attempts a
1136 JOIN tasks t ON t.current_attempt_id = a.id
1137 WHERE t.id = ? AND a.status IN ('claimed', 'running')",
1138 )
1139 .bind(task_id)
1140 .fetch_optional(self.work_pool())
1141 .await?;
1142 Ok(row.as_ref().map(task_attempt_from_row))
1143 }
1144
1145 async fn bind_task_attempt_worker(
1146 &self,
1147 attempt_id: &str,
1148 lease_token: &str,
1149 worker_instance_id: &str,
1150 worker_profile_id: Option<&str>,
1151 ) -> anyhow::Result<bool> {
1152 let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
1158 let row = sqlx::query(
1159 "SELECT a.worker_profile_id, g.project_id
1160 FROM task_attempts a
1161 JOIN tasks t ON t.current_attempt_id = a.id
1162 JOIN goals g ON g.id = t.goal_id
1163 WHERE a.id = ? AND a.lease_token = ?
1164 AND a.status IN ('claimed', 'running')
1165 AND datetime(a.lease_expires_at) > datetime('now')",
1166 )
1167 .bind(attempt_id)
1168 .bind(lease_token)
1169 .fetch_optional(&mut *tx)
1170 .await?;
1171 let Some(row) = row else {
1172 tx.rollback().await?;
1173 return Ok(false);
1174 };
1175 let current_profile_id: Option<String> = row.get("worker_profile_id");
1176 let project_id: String = row.get("project_id");
1177 let target_profile_id = worker_profile_id
1178 .map(str::to_string)
1179 .or_else(|| current_profile_id.clone());
1180
1181 if target_profile_id != current_profile_id {
1182 let Some(target_profile_id) = target_profile_id.as_deref() else {
1183 tx.rollback().await?;
1184 return Ok(false);
1185 };
1186 let profile = sqlx::query(
1187 "SELECT max_concurrency FROM worker_profiles
1188 WHERE id = ? AND enabled = 1
1189 AND (project_id IS NULL OR project_id = ?)",
1190 )
1191 .bind(target_profile_id)
1192 .bind(&project_id)
1193 .fetch_optional(&mut *tx)
1194 .await?;
1195 let Some(profile) = profile else {
1196 tx.rollback().await?;
1197 return Ok(false);
1198 };
1199 sqlx::query("UPDATE worker_profiles SET updated_at = updated_at WHERE id = ?")
1200 .bind(target_profile_id)
1201 .execute(&mut *tx)
1202 .await?;
1203 let active = sqlx::query_scalar::<_, i64>(
1204 "SELECT COUNT(*) FROM task_attempts
1205 WHERE worker_profile_id = ? AND id != ?
1206 AND status IN ('claimed', 'running')
1207 AND datetime(lease_expires_at) > datetime('now')",
1208 )
1209 .bind(target_profile_id)
1210 .bind(attempt_id)
1211 .fetch_one(&mut *tx)
1212 .await?;
1213 let max_concurrency: i64 = profile.get("max_concurrency");
1214 if active >= max_concurrency {
1215 tx.rollback().await?;
1216 return Ok(false);
1217 }
1218 }
1219
1220 let result = sqlx::query(
1221 "UPDATE task_attempts
1222 SET worker_instance_id = ?,
1223 worker_profile_id = COALESCE(?, worker_profile_id)
1224 WHERE id = ? AND lease_token = ?
1225 AND status IN ('claimed', 'running')
1226 AND datetime(lease_expires_at) > datetime('now')",
1227 )
1228 .bind(worker_instance_id)
1229 .bind(worker_profile_id)
1230 .bind(attempt_id)
1231 .bind(lease_token)
1232 .execute(&mut *tx)
1233 .await?;
1234 if result.rows_affected() > 0 {
1235 sqlx::query(
1236 "UPDATE tasks
1237 SET agent_id = ?,
1238 worker_profile_id = COALESCE(?, worker_profile_id),
1239 updated_at = datetime('now'), version = version + 1
1240 WHERE current_attempt_id = ?",
1241 )
1242 .bind(worker_instance_id)
1243 .bind(worker_profile_id)
1244 .bind(attempt_id)
1245 .execute(&mut *tx)
1246 .await?;
1247 tx.commit().await?;
1248 return Ok(true);
1249 }
1250 tx.rollback().await?;
1251 Ok(false)
1252 }
1253
1254 async fn heartbeat_task_attempt(
1255 &self,
1256 attempt_id: &str,
1257 lease_token: &str,
1258 lease_secs: i64,
1259 ) -> anyhow::Result<bool> {
1260 let lease_secs = normalized_lease_secs(lease_secs);
1261 let result = sqlx::query(
1262 "UPDATE task_attempts
1263 SET last_heartbeat_at = datetime('now'),
1264 lease_expires_at = datetime('now', '+' || ? || ' seconds')
1265 WHERE id = ? AND lease_token = ?
1266 AND status IN ('claimed', 'running')
1267 AND datetime(lease_expires_at) > datetime('now')",
1268 )
1269 .bind(lease_secs)
1270 .bind(attempt_id)
1271 .bind(lease_token)
1272 .execute(self.work_pool())
1273 .await?;
1274 Ok(result.rows_affected() > 0)
1275 }
1276
1277 async fn patch_task_from_attempt(
1278 &self,
1279 attempt_id: &str,
1280 lease_token: &str,
1281 patch: &TaskAttemptPatch,
1282 ) -> anyhow::Result<bool> {
1283 anyhow::ensure!(
1284 matches!(
1285 patch.status.as_str(),
1286 "running" | "completed" | "failed" | "blocked" | "cancelled"
1287 ),
1288 "unsupported attempt task transition"
1289 );
1290 let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
1295 let row = sqlx::query(
1296 "SELECT a.task_id, a.goal_run_id, a.status AS attempt_status,
1297 t.goal_id, g.project_id
1298 FROM task_attempts a
1299 JOIN tasks t ON t.id = a.task_id AND t.current_attempt_id = a.id
1300 JOIN goals g ON g.id = t.goal_id
1301 WHERE a.id = ? AND a.lease_token = ?
1302 AND a.status IN ('claimed', 'running')
1303 AND datetime(a.lease_expires_at) > datetime('now')",
1304 )
1305 .bind(attempt_id)
1306 .bind(lease_token)
1307 .fetch_optional(&mut *tx)
1308 .await?;
1309 let Some(row) = row else {
1310 return Ok(false);
1311 };
1312 let task_id: String = row.get("task_id");
1313 let goal_run_id: String = row.get("goal_run_id");
1314 let goal_id: String = row.get("goal_id");
1315 let project_id: String = row.get("project_id");
1316 let terminal = matches!(
1317 patch.status.as_str(),
1318 "completed" | "failed" | "blocked" | "cancelled"
1319 );
1320 let completed_at = terminal.then(|| chrono::Utc::now().to_rfc3339());
1321 let result = patch
1322 .result
1323 .as_deref()
1324 .filter(|value| !value.trim().is_empty());
1325 let error = patch
1326 .error
1327 .as_deref()
1328 .filter(|value| !value.trim().is_empty());
1329 let blocker = patch
1330 .blocker
1331 .as_deref()
1332 .filter(|value| !value.trim().is_empty());
1333 let updated = sqlx::query(
1334 "UPDATE tasks
1335 SET status = ?,
1336 result = COALESCE(?, result),
1337 error = CASE WHEN ? = 'completed' THEN NULL ELSE COALESCE(?, error) END,
1338 blocker = CASE WHEN ? IN ('completed', 'running') THEN NULL ELSE COALESCE(?, blocker) END,
1339 context = COALESCE(?, context),
1340 current_attempt_id = CASE WHEN ? THEN NULL ELSE current_attempt_id END,
1341 completed_at = CASE WHEN ? THEN ? ELSE NULL END,
1342 updated_at = datetime('now'), version = version + 1
1343 WHERE id = ? AND current_attempt_id = ?",
1344 )
1345 .bind(&patch.status)
1346 .bind(result)
1347 .bind(&patch.status)
1348 .bind(error)
1349 .bind(&patch.status)
1350 .bind(blocker)
1351 .bind(&patch.context)
1352 .bind(terminal)
1353 .bind(terminal)
1354 .bind(&completed_at)
1355 .bind(&task_id)
1356 .bind(attempt_id)
1357 .execute(&mut *tx)
1358 .await?;
1359 if updated.rows_affected() == 0 {
1360 tx.rollback().await?;
1361 return Ok(false);
1362 }
1363 sqlx::query(
1364 "UPDATE task_attempts
1365 SET status = ?, completed_at = CASE WHEN ? THEN ? ELSE completed_at END
1366 WHERE id = ? AND lease_token = ?",
1367 )
1368 .bind(&patch.status)
1369 .bind(terminal)
1370 .bind(&completed_at)
1371 .bind(attempt_id)
1372 .bind(lease_token)
1373 .execute(&mut *tx)
1374 .await?;
1375
1376 if patch.status == "completed" {
1377 sqlx::query(
1378 "UPDATE goals SET last_useful_action = datetime('now'), updated_at = datetime('now')
1379 WHERE id = ?",
1380 )
1381 .bind(&goal_id)
1382 .execute(&mut *tx)
1383 .await?;
1384 } else if patch.status == "blocked" {
1385 sqlx::query(
1389 "UPDATE goal_runs SET status = 'blocked', updated_at = datetime('now')
1390 WHERE id = ? AND status IN ('pending', 'running')
1391 AND (trigger_type <> 'mandate' OR root_task_id IS NULL OR root_task_id = ?)",
1392 )
1393 .bind(&goal_run_id)
1394 .bind(&task_id)
1395 .execute(&mut *tx)
1396 .await?;
1397 }
1398 if terminal && patch.status != "blocked" {
1399 close_pending_task_escalations(&mut tx, &task_id).await?;
1400 }
1401
1402 if let Some(handoff) = &patch.handoff {
1403 anyhow::ensure!(
1404 handoff.task_id == task_id && handoff.attempt_id == attempt_id,
1405 "handoff does not match current task attempt"
1406 );
1407 let artifacts = serde_json::to_string(&handoff.artifacts)?;
1408 let verification = serde_json::to_string(&handoff.verification)?;
1409 sqlx::query(
1410 "INSERT INTO task_handoffs
1411 (id, task_id, attempt_id, summary, artifacts_json,
1412 verification_json, remaining_risk, next_step, created_at)
1413 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
1414 )
1415 .bind(&handoff.id)
1416 .bind(&handoff.task_id)
1417 .bind(&handoff.attempt_id)
1418 .bind(self.redact_secrets(&handoff.summary))
1419 .bind(artifacts)
1420 .bind(verification)
1421 .bind(
1422 handoff
1423 .remaining_risk
1424 .as_deref()
1425 .map(|text| self.redact_secrets(text)),
1426 )
1427 .bind(
1428 handoff
1429 .next_step
1430 .as_deref()
1431 .map(|text| self.redact_secrets(text)),
1432 )
1433 .bind(&handoff.created_at)
1434 .execute(&mut *tx)
1435 .await?;
1436 }
1437
1438 let entry_type = match patch.status.as_str() {
1439 "blocked" => "blocked",
1440 "completed" | "failed" | "cancelled" => "handoff",
1441 _ => "transition",
1442 };
1443 let body = patch
1444 .handoff
1445 .as_ref()
1446 .map(|handoff| handoff.summary.as_str())
1447 .or(result)
1448 .or(error)
1449 .or(blocker)
1450 .unwrap_or(&patch.status);
1451 let journal = TaskJournalEntry::new(
1452 &project_id,
1453 &goal_id,
1454 &goal_run_id,
1455 entry_type,
1456 "agent",
1457 attempt_id,
1458 body,
1459 )
1460 .with_task(Some(&task_id), Some(attempt_id));
1461 insert_journal(self, &mut tx, &journal).await?;
1462 tx.commit().await?;
1463 Ok(true)
1464 }
1465
1466 async fn goal_run_has_live_attempt(&self, run_id: &str) -> anyhow::Result<bool> {
1467 let live = sqlx::query_scalar::<_, i64>(
1468 "SELECT COUNT(*) FROM task_attempts
1469 WHERE goal_run_id = ?
1470 AND status IN ('claimed', 'running')
1471 AND datetime(lease_expires_at) > datetime('now')",
1472 )
1473 .bind(run_id)
1474 .fetch_one(self.work_pool())
1475 .await?;
1476 Ok(live > 0)
1477 }
1478
1479 async fn recover_expired_task_attempts(&self) -> anyhow::Result<Vec<String>> {
1480 let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
1481 let rows = sqlx::query(
1482 "SELECT a.id AS attempt_id, a.task_id, a.goal_run_id,
1483 t.goal_id, g.project_id, t.idempotent, t.retry_count,
1484 t.max_retries, t.current_attempt_id
1485 FROM task_attempts a
1486 JOIN tasks t ON t.id = a.task_id
1487 JOIN goals g ON g.id = t.goal_id
1488 WHERE a.status IN ('claimed', 'running')
1489 AND datetime(a.lease_expires_at) <= datetime('now')",
1490 )
1491 .fetch_all(&mut *tx)
1492 .await?;
1493 let mut affected = Vec::new();
1494 for row in rows {
1495 let attempt_id: String = row.get("attempt_id");
1496 let task_id: String = row.get("task_id");
1497 let goal_run_id: String = row.get("goal_run_id");
1498 let goal_id: String = row.get("goal_id");
1499 let project_id: String = row.get("project_id");
1500 let is_current = row
1501 .get::<Option<String>, _>("current_attempt_id")
1502 .as_deref()
1503 == Some(attempt_id.as_str());
1504 let recovery = crate::traits::ExpiredAttemptRecovery::classify(
1505 row.get::<i64, _>("idempotent") != 0,
1506 row.get::<i64, _>("retry_count") as i32,
1507 row.get::<i64, _>("max_retries") as i32,
1508 );
1509 let attempt_status = match recovery {
1510 crate::traits::ExpiredAttemptRecovery::Requeue => "expired",
1511 crate::traits::ExpiredAttemptRecovery::RequireVerification => "needs_verification",
1512 };
1513 let expired = sqlx::query(
1514 "UPDATE task_attempts
1515 SET status = ?, completed_at = datetime('now')
1516 WHERE id = ? AND status IN ('claimed', 'running')
1517 AND datetime(lease_expires_at) <= datetime('now')",
1518 )
1519 .bind(attempt_status)
1520 .bind(&attempt_id)
1521 .execute(&mut *tx)
1522 .await?;
1523 if expired.rows_affected() == 0 {
1524 continue;
1525 }
1526 sqlx::query(
1527 "UPDATE task_workspaces SET status = 'preserved'
1528 WHERE attempt_id = ? AND status = 'active'",
1529 )
1530 .bind(&attempt_id)
1531 .execute(&mut *tx)
1532 .await?;
1533 if is_current {
1534 if recovery == crate::traits::ExpiredAttemptRecovery::Requeue {
1535 sqlx::query(
1536 "UPDATE tasks
1537 SET status = 'pending', current_attempt_id = NULL, agent_id = NULL,
1538 retry_count = retry_count + 1, started_at = NULL,
1539 completed_at = NULL, result = NULL, error = NULL, blocker = NULL,
1540 updated_at = datetime('now'), version = version + 1
1541 WHERE id = ? AND current_attempt_id = ?",
1542 )
1543 .bind(&task_id)
1544 .bind(&attempt_id)
1545 .execute(&mut *tx)
1546 .await?;
1547 } else {
1548 sqlx::query(
1549 "UPDATE tasks
1550 SET status = 'blocked', current_attempt_id = NULL,
1551 blocker = 'Execution lease expired. Verify external side effects before retrying.',
1552 result = NULL, error = NULL,
1553 completed_at = datetime('now'), updated_at = datetime('now'),
1554 version = version + 1
1555 WHERE id = ? AND current_attempt_id = ?",
1556 )
1557 .bind(&task_id)
1558 .bind(&attempt_id)
1559 .execute(&mut *tx)
1560 .await?;
1561 sqlx::query(
1562 "UPDATE goal_runs SET status = 'blocked', updated_at = datetime('now')
1563 WHERE id = ? AND status IN ('pending', 'running')",
1564 )
1565 .bind(&goal_run_id)
1566 .execute(&mut *tx)
1567 .await?;
1568 }
1569 affected.push(task_id.clone());
1570 }
1571 let body = match recovery {
1572 crate::traits::ExpiredAttemptRecovery::Requeue => {
1573 "Worker lease expired; task re-queued because the task is retryable."
1574 }
1575 crate::traits::ExpiredAttemptRecovery::RequireVerification => {
1576 "Worker lease expired; task requires human verification before another attempt."
1577 }
1578 };
1579 let journal = TaskJournalEntry::new(
1580 &project_id,
1581 &goal_id,
1582 &goal_run_id,
1583 "lease_lost",
1584 "system",
1585 "lease-recovery",
1586 body,
1587 )
1588 .with_task(Some(&task_id), Some(&attempt_id));
1589 insert_journal(self, &mut tx, &journal).await?;
1590 }
1591 tx.commit().await?;
1592 Ok(affected)
1593 }
1594
1595 async fn append_task_journal(&self, entry: &TaskJournalEntry) -> anyhow::Result<()> {
1596 let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
1597 insert_journal(self, &mut tx, entry).await?;
1598 tx.commit().await?;
1599 Ok(())
1600 }
1601
1602 async fn get_task_journal(
1603 &self,
1604 task_id: &str,
1605 limit: i64,
1606 ) -> anyhow::Result<Vec<TaskJournalEntry>> {
1607 let rows = sqlx::query(
1608 "SELECT id, project_id, goal_id, goal_run_id, task_id, attempt_id,
1609 entry_type, actor_type, actor_id, source_channel, body, payload, created_at
1610 FROM task_journal WHERE task_id = ?
1611 ORDER BY julianday(created_at) DESC, id DESC LIMIT ?",
1612 )
1613 .bind(task_id)
1614 .bind(limit.clamp(1, 200))
1615 .fetch_all(self.work_pool())
1616 .await?;
1617 Ok(rows
1618 .iter()
1619 .map(|row| TaskJournalEntry {
1620 id: row.get("id"),
1621 project_id: row.get("project_id"),
1622 goal_id: row.get("goal_id"),
1623 goal_run_id: row.get("goal_run_id"),
1624 task_id: row.get("task_id"),
1625 attempt_id: row.get("attempt_id"),
1626 entry_type: row.get("entry_type"),
1627 actor_type: row.get("actor_type"),
1628 actor_id: row.get("actor_id"),
1629 source_channel: row.get("source_channel"),
1630 body: row.get("body"),
1631 payload: row.get("payload"),
1632 created_at: row.get("created_at"),
1633 })
1634 .collect())
1635 }
1636
1637 async fn unblock_task(
1638 &self,
1639 task_id: &str,
1640 resolution: &str,
1641 actor_id: &str,
1642 source_channel: Option<&str>,
1643 ) -> anyhow::Result<bool> {
1644 anyhow::ensure!(!resolution.trim().is_empty(), "resolution cannot be empty");
1645 let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
1646 let Some((project_id, goal_id, goal_run_id)) = task_scope(&mut tx, task_id).await? else {
1647 return Ok(false);
1648 };
1649 let attempt_id = sqlx::query_scalar::<_, Option<String>>(
1650 "SELECT current_attempt_id FROM tasks
1651 WHERE id = ? AND status = 'blocked'",
1652 )
1653 .bind(task_id)
1654 .fetch_optional(&mut *tx)
1655 .await?
1656 .flatten();
1657 if let Some(attempt_id) = &attempt_id {
1658 sqlx::query(
1659 "UPDATE task_attempts SET status = 'cancelled', completed_at = datetime('now')
1660 WHERE id = ? AND status IN ('claimed', 'running')",
1661 )
1662 .bind(attempt_id)
1663 .execute(&mut *tx)
1664 .await?;
1665 }
1666 let updated = sqlx::query(
1667 "UPDATE tasks
1668 SET status = 'pending', result = NULL, blocker = NULL, error = NULL, completed_at = NULL,
1669 started_at = NULL, current_attempt_id = NULL, agent_id = NULL,
1670 updated_at = datetime('now'), version = version + 1
1671 WHERE id = ? AND status = 'blocked'",
1672 )
1673 .bind(task_id)
1674 .execute(&mut *tx)
1675 .await?;
1676 if updated.rows_affected() == 0 {
1677 tx.rollback().await?;
1678 return Ok(false);
1679 }
1680 close_pending_task_escalations(&mut tx, task_id).await?;
1681 sqlx::query(
1682 "UPDATE goal_runs SET status = 'running', updated_at = datetime('now')
1683 WHERE id = ? AND status = 'blocked'",
1684 )
1685 .bind(&goal_run_id)
1686 .execute(&mut *tx)
1687 .await?;
1688 let journal = TaskJournalEntry::new(
1689 &project_id,
1690 &goal_id,
1691 &goal_run_id,
1692 "unblocked",
1693 "human",
1694 actor_id,
1695 resolution.trim(),
1696 )
1697 .with_task(Some(task_id), attempt_id.as_deref())
1698 .with_source_channel(source_channel);
1699 insert_journal(self, &mut tx, &journal).await?;
1700 tx.commit().await?;
1701 Ok(true)
1702 }
1703
1704 async fn retry_work_task(
1705 &self,
1706 task_id: &str,
1707 actor_id: &str,
1708 source_channel: Option<&str>,
1709 ) -> anyhow::Result<bool> {
1710 let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
1711 let Some((project_id, goal_id, goal_run_id)) = task_scope(&mut tx, task_id).await? else {
1712 return Ok(false);
1713 };
1714 let updated = sqlx::query(
1715 "UPDATE tasks
1716 SET status = 'pending', result = NULL, blocker = NULL, error = NULL, completed_at = NULL,
1717 started_at = NULL, current_attempt_id = NULL, agent_id = NULL,
1718 retry_count = retry_count + 1,
1719 updated_at = datetime('now'), version = version + 1
1720 WHERE id = ? AND status IN ('failed', 'blocked', 'interrupted', 'cancelled')
1721 AND current_attempt_id IS NULL",
1722 )
1723 .bind(task_id)
1724 .execute(&mut *tx)
1725 .await?;
1726 if updated.rows_affected() == 0 {
1727 tx.rollback().await?;
1728 return Ok(false);
1729 }
1730 close_pending_task_escalations(&mut tx, task_id).await?;
1731 sqlx::query(
1732 "UPDATE goal_runs SET status = 'running', updated_at = datetime('now')
1733 WHERE id = ? AND status = 'blocked'",
1734 )
1735 .bind(&goal_run_id)
1736 .execute(&mut *tx)
1737 .await?;
1738 let journal = TaskJournalEntry::new(
1739 &project_id,
1740 &goal_id,
1741 &goal_run_id,
1742 "transition",
1743 "human",
1744 actor_id,
1745 "Task explicitly queued for another attempt.",
1746 )
1747 .with_task(Some(task_id), None)
1748 .with_source_channel(source_channel);
1749 insert_journal(self, &mut tx, &journal).await?;
1750 tx.commit().await?;
1751 Ok(true)
1752 }
1753
1754 async fn cancel_work_task(
1755 &self,
1756 task_id: &str,
1757 actor_id: &str,
1758 source_channel: Option<&str>,
1759 ) -> anyhow::Result<bool> {
1760 let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
1761 let Some((project_id, goal_id, goal_run_id)) = task_scope(&mut tx, task_id).await? else {
1762 return Ok(false);
1763 };
1764 let attempt_id = sqlx::query_scalar::<_, Option<String>>(
1765 "SELECT current_attempt_id FROM tasks WHERE id = ?",
1766 )
1767 .bind(task_id)
1768 .fetch_optional(&mut *tx)
1769 .await?
1770 .flatten();
1771 if let Some(attempt_id) = &attempt_id {
1772 sqlx::query(
1773 "UPDATE task_attempts SET status = 'cancelled', completed_at = datetime('now')
1774 WHERE id = ? AND status IN ('claimed', 'running')",
1775 )
1776 .bind(attempt_id)
1777 .execute(&mut *tx)
1778 .await?;
1779 }
1780 let updated = sqlx::query(
1781 "UPDATE tasks
1782 SET status = 'cancelled', current_attempt_id = NULL,
1783 completed_at = datetime('now'), updated_at = datetime('now'),
1784 version = version + 1
1785 WHERE id = ? AND status NOT IN ('completed', 'cancelled', 'skipped', 'superseded')",
1786 )
1787 .bind(task_id)
1788 .execute(&mut *tx)
1789 .await?;
1790 if updated.rows_affected() == 0 {
1791 tx.rollback().await?;
1792 return Ok(false);
1793 }
1794 close_pending_task_escalations(&mut tx, task_id).await?;
1795 let journal = TaskJournalEntry::new(
1796 &project_id,
1797 &goal_id,
1798 &goal_run_id,
1799 "transition",
1800 "human",
1801 actor_id,
1802 "Task cancelled.",
1803 )
1804 .with_task(Some(task_id), attempt_id.as_deref())
1805 .with_source_channel(source_channel);
1806 insert_journal(self, &mut tx, &journal).await?;
1807 tx.commit().await?;
1808 Ok(true)
1809 }
1810
1811 async fn upsert_worker_profile(&self, profile: &WorkerProfile) -> anyhow::Result<()> {
1812 anyhow::ensure!(
1813 profile.max_concurrency > 0,
1814 "profile concurrency must be positive"
1815 );
1816 anyhow::ensure!(
1817 matches!(
1818 profile.workspace_policy.as_str(),
1819 "shared" | "isolated" | "worktree"
1820 ),
1821 "unsupported workspace policy"
1822 );
1823 sqlx::query(
1824 "INSERT INTO worker_profiles
1825 (id, project_id, name, specialist, model, tools_json, max_iterations,
1826 tool_budget, timeout_secs, max_concurrency, workspace_policy,
1827 memory_scope, version, enabled, created_at, updated_at)
1828 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1829 ON CONFLICT(id) DO UPDATE SET
1830 project_id = excluded.project_id, name = excluded.name,
1831 specialist = excluded.specialist, model = excluded.model,
1832 tools_json = excluded.tools_json, max_iterations = excluded.max_iterations,
1833 tool_budget = excluded.tool_budget, timeout_secs = excluded.timeout_secs,
1834 max_concurrency = excluded.max_concurrency,
1835 workspace_policy = excluded.workspace_policy,
1836 memory_scope = excluded.memory_scope, version = excluded.version,
1837 enabled = excluded.enabled, updated_at = excluded.updated_at",
1838 )
1839 .bind(&profile.id)
1840 .bind(&profile.project_id)
1841 .bind(&profile.name)
1842 .bind(&profile.specialist)
1843 .bind(&profile.model)
1844 .bind(&profile.tools_json)
1845 .bind(profile.max_iterations)
1846 .bind(profile.tool_budget)
1847 .bind(profile.timeout_secs)
1848 .bind(profile.max_concurrency)
1849 .bind(&profile.workspace_policy)
1850 .bind(&profile.memory_scope)
1851 .bind(profile.version)
1852 .bind(profile.enabled as i64)
1853 .bind(&profile.created_at)
1854 .bind(&profile.updated_at)
1855 .execute(self.work_pool())
1856 .await?;
1857 Ok(())
1858 }
1859
1860 async fn get_worker_profile(&self, profile_id: &str) -> anyhow::Result<Option<WorkerProfile>> {
1861 let row = sqlx::query(
1862 "SELECT id, project_id, name, specialist, model, tools_json,
1863 max_iterations, tool_budget, timeout_secs, max_concurrency,
1864 workspace_policy, memory_scope, version, enabled, created_at, updated_at
1865 FROM worker_profiles WHERE id = ?",
1866 )
1867 .bind(profile_id)
1868 .fetch_optional(self.work_pool())
1869 .await?;
1870 Ok(row.as_ref().map(worker_profile_from_row))
1871 }
1872
1873 async fn list_worker_profiles(
1874 &self,
1875 project_id: Option<&str>,
1876 ) -> anyhow::Result<Vec<WorkerProfile>> {
1877 let rows = sqlx::query(
1878 "SELECT id, project_id, name, specialist, model, tools_json,
1879 max_iterations, tool_budget, timeout_secs, max_concurrency,
1880 workspace_policy, memory_scope, version, enabled, created_at, updated_at
1881 FROM worker_profiles
1882 WHERE enabled = 1 AND (project_id IS NULL OR project_id = ?)
1883 ORDER BY name COLLATE NOCASE",
1884 )
1885 .bind(project_id.unwrap_or(DEFAULT_PROJECT_ID))
1886 .fetch_all(self.work_pool())
1887 .await?;
1888 Ok(rows.iter().map(worker_profile_from_row).collect())
1889 }
1890
1891 async fn assign_task_worker_profile(
1892 &self,
1893 task_id: &str,
1894 profile_id: &str,
1895 actor_id: &str,
1896 source_channel: Option<&str>,
1897 ) -> anyhow::Result<bool> {
1898 let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
1899 let Some((project_id, goal_id, goal_run_id)) = task_scope(&mut tx, task_id).await? else {
1900 return Ok(false);
1901 };
1902 let profile_exists = sqlx::query_scalar::<_, i64>(
1903 "SELECT 1 FROM worker_profiles
1904 WHERE id = ? AND enabled = 1
1905 AND (project_id IS NULL OR project_id = ?) LIMIT 1",
1906 )
1907 .bind(profile_id)
1908 .bind(&project_id)
1909 .fetch_optional(&mut *tx)
1910 .await?
1911 .is_some();
1912 if !profile_exists {
1913 return Ok(false);
1914 }
1915 let updated = sqlx::query(
1916 "UPDATE tasks SET worker_profile_id = ?, updated_at = datetime('now'),
1917 version = version + 1
1918 WHERE id = ? AND status IN ('pending', 'blocked', 'failed', 'interrupted')",
1919 )
1920 .bind(profile_id)
1921 .bind(task_id)
1922 .execute(&mut *tx)
1923 .await?;
1924 if updated.rows_affected() == 0 {
1925 tx.rollback().await?;
1926 return Ok(false);
1927 }
1928 let journal = TaskJournalEntry::new(
1929 &project_id,
1930 &goal_id,
1931 &goal_run_id,
1932 "assigned",
1933 if source_channel.is_some() {
1934 "human"
1935 } else {
1936 "agent"
1937 },
1938 actor_id,
1939 &format!("Assigned worker profile {}", profile_id),
1940 )
1941 .with_task(Some(task_id), None)
1942 .with_source_channel(source_channel);
1943 insert_journal(self, &mut tx, &journal).await?;
1944 tx.commit().await?;
1945 Ok(true)
1946 }
1947
1948 async fn set_task_workspace_policy(&self, task_id: &str, policy: &str) -> anyhow::Result<bool> {
1949 anyhow::ensure!(
1950 matches!(policy, "shared" | "isolated" | "worktree"),
1951 "unsupported workspace policy"
1952 );
1953 let result = sqlx::query(
1954 "UPDATE tasks SET workspace_policy = ?, workspace_policy_explicit = 1,
1955 updated_at = datetime('now'),
1956 version = version + 1
1957 WHERE id = ? AND status IN ('pending', 'blocked', 'claimed')
1958 AND NOT EXISTS (
1959 SELECT 1 FROM task_workspaces w
1960 WHERE w.task_id = tasks.id AND w.status != 'failed'
1961 )",
1962 )
1963 .bind(policy)
1964 .bind(task_id)
1965 .execute(self.work_pool())
1966 .await?;
1967 Ok(result.rows_affected() > 0)
1968 }
1969
1970 async fn get_task_workspace_policy(&self, task_id: &str) -> anyhow::Result<String> {
1971 Ok(sqlx::query_scalar::<_, String>(
1972 "SELECT CASE
1973 WHEN t.workspace_policy_explicit = 1
1974 THEN t.workspace_policy
1975 ELSE COALESCE(wp.workspace_policy, 'shared')
1976 END
1977 FROM tasks t
1978 LEFT JOIN task_attempts a ON a.id = t.current_attempt_id
1979 LEFT JOIN worker_profiles wp
1980 ON wp.id = COALESCE(a.worker_profile_id, t.worker_profile_id)
1981 WHERE t.id = ?",
1982 )
1983 .bind(task_id)
1984 .fetch_optional(self.work_pool())
1985 .await?
1986 .unwrap_or_else(|| "shared".to_string()))
1987 }
1988
1989 async fn task_workspace_policy_is_explicit(&self, task_id: &str) -> anyhow::Result<bool> {
1990 Ok(sqlx::query_scalar::<_, i64>(
1991 "SELECT COALESCE(workspace_policy_explicit, 0) FROM tasks WHERE id = ?",
1992 )
1993 .bind(task_id)
1994 .fetch_optional(self.work_pool())
1995 .await?
1996 .is_some_and(|explicit| explicit == 1))
1997 }
1998
1999 async fn create_task_workspace(&self, workspace: &TaskWorkspace) -> anyhow::Result<()> {
2000 let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
2001 sqlx::query(
2002 "INSERT INTO task_workspaces
2003 (id, task_id, attempt_id, backend_id, policy, root_path,
2004 branch_name, base_ref, head_ref, status, created_at, released_at)
2005 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
2006 )
2007 .bind(&workspace.id)
2008 .bind(&workspace.task_id)
2009 .bind(&workspace.attempt_id)
2010 .bind(&workspace.backend_id)
2011 .bind(&workspace.policy)
2012 .bind(&workspace.root_path)
2013 .bind(&workspace.branch_name)
2014 .bind(&workspace.base_ref)
2015 .bind(&workspace.head_ref)
2016 .bind(&workspace.status)
2017 .bind(&workspace.created_at)
2018 .bind(&workspace.released_at)
2019 .execute(&mut *tx)
2020 .await?;
2021 sqlx::query("UPDATE task_attempts SET workspace_id = ? WHERE id = ?")
2022 .bind(&workspace.id)
2023 .bind(&workspace.attempt_id)
2024 .execute(&mut *tx)
2025 .await?;
2026 tx.commit().await?;
2027 Ok(())
2028 }
2029
2030 async fn update_task_workspace(&self, workspace: &TaskWorkspace) -> anyhow::Result<()> {
2031 sqlx::query(
2032 "UPDATE task_workspaces
2033 SET root_path = ?, branch_name = ?, base_ref = ?, head_ref = ?,
2034 status = ?, released_at = ?
2035 WHERE id = ? AND task_id = ? AND attempt_id = ?",
2036 )
2037 .bind(&workspace.root_path)
2038 .bind(&workspace.branch_name)
2039 .bind(&workspace.base_ref)
2040 .bind(&workspace.head_ref)
2041 .bind(&workspace.status)
2042 .bind(&workspace.released_at)
2043 .bind(&workspace.id)
2044 .bind(&workspace.task_id)
2045 .bind(&workspace.attempt_id)
2046 .execute(self.work_pool())
2047 .await?;
2048 Ok(())
2049 }
2050
2051 async fn get_task_workspace(&self, task_id: &str) -> anyhow::Result<Option<TaskWorkspace>> {
2052 let row = sqlx::query(
2053 "SELECT id, task_id, attempt_id, backend_id, policy, root_path,
2054 branch_name, base_ref, head_ref, status, created_at, released_at
2055 FROM task_workspaces WHERE task_id = ?
2056 ORDER BY julianday(created_at) DESC, id DESC LIMIT 1",
2057 )
2058 .bind(task_id)
2059 .fetch_optional(self.work_pool())
2060 .await?;
2061 Ok(row.map(|row| TaskWorkspace {
2062 id: row.get("id"),
2063 task_id: row.get("task_id"),
2064 attempt_id: row.get("attempt_id"),
2065 backend_id: row.get("backend_id"),
2066 policy: row.get("policy"),
2067 root_path: row.get("root_path"),
2068 branch_name: row.get("branch_name"),
2069 base_ref: row.get("base_ref"),
2070 head_ref: row.get("head_ref"),
2071 status: row.get("status"),
2072 created_at: row.get("created_at"),
2073 released_at: row.get("released_at"),
2074 }))
2075 }
2076
2077 async fn get_latest_task_handoff(&self, task_id: &str) -> anyhow::Result<Option<TaskHandoff>> {
2078 let row = sqlx::query(
2079 "SELECT id, task_id, attempt_id, summary, artifacts_json,
2080 verification_json, remaining_risk, next_step, created_at
2081 FROM task_handoffs WHERE task_id = ?
2082 ORDER BY julianday(created_at) DESC, id DESC LIMIT 1",
2083 )
2084 .bind(task_id)
2085 .fetch_optional(self.work_pool())
2086 .await?;
2087 Ok(row.map(|row| {
2088 let artifacts = row
2089 .get::<String, _>("artifacts_json")
2090 .parse::<serde_json::Value>()
2091 .ok()
2092 .and_then(|value| serde_json::from_value::<Vec<HandoffArtifact>>(value).ok())
2093 .unwrap_or_default();
2094 let verification =
2095 serde_json::from_str::<Vec<String>>(&row.get::<String, _>("verification_json"))
2096 .unwrap_or_default();
2097 TaskHandoff {
2098 id: row.get("id"),
2099 task_id: row.get("task_id"),
2100 attempt_id: row.get("attempt_id"),
2101 summary: row.get("summary"),
2102 artifacts,
2103 verification,
2104 remaining_risk: row.get("remaining_risk"),
2105 next_step: row.get("next_step"),
2106 created_at: row.get("created_at"),
2107 }
2108 }))
2109 }
2110
2111 async fn list_work_goals(
2112 &self,
2113 project_id: &str,
2114 include_terminal: bool,
2115 limit: i64,
2116 ) -> anyhow::Result<Vec<WorkGoalSummary>> {
2117 let rows = sqlx::query(
2118 "WITH ranked_runs AS (
2119 SELECT gr.*, rg.goal_type,
2120 ROW_NUMBER() OVER (
2121 PARTITION BY gr.goal_id
2122 ORDER BY julianday(gr.started_at) DESC, gr.id DESC
2123 ) AS recency,
2124 SUM(CASE WHEN gr.status IN ('pending', 'running', 'blocked')
2125 THEN 1 ELSE 0 END) OVER (
2126 PARTITION BY gr.goal_id
2127 ) AS active_count
2128 FROM goal_runs gr
2129 JOIN goals rg ON rg.id = gr.goal_id
2130 ),
2131 visible_runs AS (
2132 SELECT * FROM ranked_runs
2133 WHERE status IN ('pending', 'running', 'blocked')
2134 OR (active_count = 0 AND recency = 1
2135 AND NOT (trigger_type = 'legacy' AND goal_type = 'continuous'))
2136 ),
2137 lanes AS (
2138 SELECT t.id, t.goal_id, t.goal_run_id,
2139 CASE
2140 WHEN t.status = 'pending' AND EXISTS (
2141 SELECT 1 FROM task_dependencies dep
2142 WHERE dep.task_id = t.id
2143 AND NOT EXISTS (
2144 SELECT 1 FROM tasks d
2145 WHERE d.id = dep.depends_on_task_id
2146 AND d.goal_run_id = t.goal_run_id
2147 AND d.status IN ('completed', 'skipped', 'superseded')
2148 )
2149 ) THEN 'waiting'
2150 WHEN t.status = 'pending' THEN 'ready'
2151 WHEN t.status IN ('claimed', 'running') AND EXISTS (
2152 SELECT 1 FROM task_attempts a
2153 WHERE a.id = t.current_attempt_id
2154 AND a.status IN ('claimed', 'running')
2155 AND datetime(a.lease_expires_at) > datetime('now')
2156 ) THEN 'in_progress'
2157 WHEN t.status = 'blocked' THEN 'blocked'
2158 WHEN t.status IN ('completed', 'cancelled', 'skipped', 'superseded') THEN 'done'
2159 ELSE 'needs_attention'
2160 END AS lane
2161 FROM tasks t
2162 )
2163 SELECT g.project_id, g.id AS goal_id, g.description, g.status AS goal_status,
2164 vr.id AS run_id, vr.status AS run_status,
2165 SUM(CASE WHEN l.lane = 'waiting' THEN 1 ELSE 0 END) AS waiting,
2166 SUM(CASE WHEN l.lane = 'ready' THEN 1 ELSE 0 END) AS ready,
2167 SUM(CASE WHEN l.lane = 'in_progress' THEN 1 ELSE 0 END) AS in_progress,
2168 SUM(CASE WHEN l.lane = 'blocked' THEN 1 ELSE 0 END) AS blocked,
2169 SUM(CASE WHEN l.lane = 'needs_attention' THEN 1 ELSE 0 END) AS needs_attention,
2170 SUM(CASE WHEN l.lane = 'done' THEN 1 ELSE 0 END) AS done,
2171 datetime(MAX(julianday(COALESCE(t.updated_at, g.updated_at)))) AS updated_at,
2172 MAX(julianday(COALESCE(t.updated_at, g.updated_at))) AS updated_order
2173 FROM goals g
2174 LEFT JOIN visible_runs vr ON vr.goal_id = g.id
2175 LEFT JOIN tasks t ON t.goal_run_id = vr.id
2176 LEFT JOIN lanes l ON l.id = t.id
2177 WHERE g.project_id = ? AND g.domain = 'orchestration'
2178 AND (? OR g.status NOT IN ('completed', 'failed', 'cancelled', 'abandoned'))
2179 GROUP BY g.id, vr.id
2180 ORDER BY
2181 CASE g.priority WHEN 'critical' THEN 1 WHEN 'high' THEN 2
2182 WHEN 'medium' THEN 3 ELSE 4 END,
2183 updated_order DESC
2184 LIMIT ?",
2185 )
2186 .bind(project_id)
2187 .bind(include_terminal)
2188 .bind(limit.clamp(1, 200))
2189 .fetch_all(self.work_pool())
2190 .await?;
2191 Ok(rows
2192 .iter()
2193 .map(|row| WorkGoalSummary {
2194 project_id: row.get("project_id"),
2195 goal_id: row.get("goal_id"),
2196 description: row.get("description"),
2197 goal_status: row.get("goal_status"),
2198 run_id: row.get("run_id"),
2199 run_status: row.get("run_status"),
2200 waiting: row.get::<i64, _>("waiting"),
2201 ready: row.get::<i64, _>("ready"),
2202 in_progress: row.get::<i64, _>("in_progress"),
2203 blocked: row.get::<i64, _>("blocked"),
2204 needs_attention: row.get::<i64, _>("needs_attention"),
2205 done: row.get::<i64, _>("done"),
2206 updated_at: row.get("updated_at"),
2207 })
2208 .collect())
2209 }
2210
2211 async fn list_work_tasks(
2212 &self,
2213 project_id: &str,
2214 lane: Option<&str>,
2215 limit: i64,
2216 ) -> anyhow::Result<Vec<WorkTaskSummary>> {
2217 let rows = sqlx::query(
2218 "WITH ranked_runs AS (
2219 SELECT gr.*, rg.goal_type,
2220 ROW_NUMBER() OVER (
2221 PARTITION BY gr.goal_id
2222 ORDER BY julianday(gr.started_at) DESC, gr.id DESC
2223 ) AS recency,
2224 SUM(CASE WHEN gr.status IN ('pending', 'running', 'blocked')
2225 THEN 1 ELSE 0 END) OVER (
2226 PARTITION BY gr.goal_id
2227 ) AS active_count
2228 FROM goal_runs gr
2229 JOIN goals rg ON rg.id = gr.goal_id
2230 ),
2231 visible_runs AS (
2232 SELECT * FROM ranked_runs
2233 WHERE status IN ('pending', 'running', 'blocked')
2234 OR (active_count = 0 AND recency = 1
2235 AND NOT (trigger_type = 'legacy' AND goal_type = 'continuous'))
2236 ),
2237 projected AS (
2238 SELECT g.project_id, t.goal_id, g.description AS goal_description,
2239 t.goal_run_id, t.id AS task_id, t.description, t.status,
2240 t.priority, t.blocker, COALESCE(t.updated_at, t.created_at) AS updated_at,
2241 wp.name AS worker_profile, a.worker_instance_id, a.lease_expires_at,
2242 CASE
2243 WHEN t.status = 'pending' AND EXISTS (
2244 SELECT 1 FROM task_dependencies dep
2245 WHERE dep.task_id = t.id
2246 AND NOT EXISTS (
2247 SELECT 1 FROM tasks d
2248 WHERE d.id = dep.depends_on_task_id
2249 AND d.goal_run_id = t.goal_run_id
2250 AND d.status IN ('completed', 'skipped', 'superseded')
2251 )
2252 ) THEN 'waiting'
2253 WHEN t.status = 'pending' THEN 'ready'
2254 WHEN t.status IN ('claimed', 'running') AND a.id IS NOT NULL
2255 AND a.status IN ('claimed', 'running')
2256 AND datetime(a.lease_expires_at) > datetime('now')
2257 THEN 'in_progress'
2258 WHEN t.status = 'blocked' THEN 'blocked'
2259 WHEN t.status IN ('completed', 'cancelled', 'skipped', 'superseded') THEN 'done'
2260 ELSE 'needs_attention'
2261 END AS lane
2262 FROM tasks t
2263 JOIN goals g ON g.id = t.goal_id
2264 JOIN visible_runs vr ON vr.id = t.goal_run_id
2265 LEFT JOIN task_attempts a ON a.id = t.current_attempt_id
2266 LEFT JOIN worker_profiles wp ON wp.id = COALESCE(a.worker_profile_id, t.worker_profile_id)
2267 WHERE g.project_id = ? AND g.domain = 'orchestration'
2268 AND g.status NOT IN ('completed', 'failed', 'cancelled', 'abandoned')
2269 )
2270 SELECT * FROM projected
2271 WHERE (? IS NULL OR lane = ?)
2272 ORDER BY
2273 CASE priority WHEN 'high' THEN 1 WHEN 'medium' THEN 2 ELSE 3 END,
2274 julianday(updated_at) DESC
2275 LIMIT ?",
2276 )
2277 .bind(project_id)
2278 .bind(lane)
2279 .bind(lane)
2280 .bind(limit.clamp(1, 500))
2281 .fetch_all(self.work_pool())
2282 .await?;
2283 Ok(rows
2284 .iter()
2285 .map(|row| WorkTaskSummary {
2286 project_id: row.get("project_id"),
2287 goal_id: row.get("goal_id"),
2288 goal_description: row.get("goal_description"),
2289 goal_run_id: row.get("goal_run_id"),
2290 task_id: row.get("task_id"),
2291 description: row.get("description"),
2292 status: row.get("status"),
2293 lane: row.get("lane"),
2294 priority: row.get("priority"),
2295 worker_profile: row.get("worker_profile"),
2296 worker_instance_id: row.get("worker_instance_id"),
2297 lease_expires_at: row.get("lease_expires_at"),
2298 blocker: row.get("blocker"),
2299 updated_at: row.get("updated_at"),
2300 })
2301 .collect())
2302 }
2303}
2304
2305#[cfg(test)]
2306mod tests {
2307 use super::*;
2308 use crate::traits::*;
2309 use crate::traits::{Goal, GoalSchedule, Task};
2310 use std::sync::Arc;
2311
2312 async fn test_store() -> (SqliteWorkStore, tempfile::NamedTempFile) {
2313 let database = tempfile::NamedTempFile::new().unwrap();
2314 let store = open_for_tests(database.path().to_str().unwrap()).await;
2315 (store, database)
2316 }
2317
2318 fn task(goal_id: &str, description: &str, depends_on: Option<Vec<String>>) -> Task {
2319 Task {
2320 id: uuid::Uuid::new_v4().to_string(),
2321 goal_id: goal_id.to_string(),
2322 description: description.to_string(),
2323 status: "pending".to_string(),
2324 priority: "medium".to_string(),
2325 task_order: 0,
2326 parallel_group: None,
2327 depends_on: depends_on.map(|deps| serde_json::to_string(&deps).unwrap()),
2328 agent_id: None,
2329 context: None,
2330 result: None,
2331 error: None,
2332 blocker: None,
2333 idempotent: true,
2334 retry_count: 0,
2335 max_retries: 2,
2336 created_at: chrono::Utc::now().to_rfc3339(),
2337 started_at: None,
2338 completed_at: None,
2339 }
2340 }
2341
2342 fn handoff(task_id: &str, attempt_id: &str, summary: &str) -> TaskHandoff {
2343 TaskHandoff {
2344 id: uuid::Uuid::new_v4().to_string(),
2345 task_id: task_id.to_string(),
2346 attempt_id: attempt_id.to_string(),
2347 summary: summary.to_string(),
2348 artifacts: vec![HandoffArtifact {
2349 kind: "path".to_string(),
2350 reference: "/tmp/result".to_string(),
2351 digest: None,
2352 metadata: None,
2353 }],
2354 verification: vec!["check passed".to_string()],
2355 remaining_risk: None,
2356 next_step: None,
2357 created_at: chrono::Utc::now().to_rfc3339(),
2358 }
2359 }
2360
2361 #[tokio::test]
2362 async fn a_deleted_project_leaves_its_sessions_and_bots_in_no_project() {
2363 let (store, _db) = test_store().await;
2364 let project = store.create_work_project("Acme site", None).await.unwrap();
2365 let bot = "telegram:synthetic_coding_bot";
2366 assert!(
2367 store
2368 .set_session_work_project("app:a", &project.id)
2369 .await
2370 .unwrap()
2371 );
2372 assert!(
2373 store
2374 .set_channel_work_project(bot, Some(&project.id))
2375 .await
2376 .unwrap()
2377 );
2378
2379 assert!(store.delete_work_project(&project.id).await.unwrap());
2380
2381 assert!(
2382 store
2383 .list_work_projects()
2384 .await
2385 .unwrap()
2386 .iter()
2387 .all(|p| p.id != project.id)
2388 );
2389 assert_eq!(
2390 store.get_session_work_project("app:a").await.unwrap(),
2391 DEFAULT_PROJECT_ID
2392 );
2393 assert!(store.session_work_projects().await.unwrap().is_empty());
2394 assert!(store.channel_work_projects().await.unwrap().is_empty());
2395 assert!(!store.delete_work_project(&project.id).await.unwrap());
2396 assert!(store.delete_work_project(DEFAULT_PROJECT_ID).await.is_err());
2397 }
2398
2399 #[tokio::test]
2400 async fn a_project_keeps_its_folder_and_lists_the_sessions_placed_in_it() {
2401 let (store, _db) = test_store().await;
2402 let project = store.create_work_project("Acme site", None).await.unwrap();
2403 assert_eq!(project.path, None);
2404 let moved = store
2405 .update_work_project(&project.id, None, Some(Some("/home/synthetic/acme-site")))
2406 .await
2407 .unwrap()
2408 .unwrap();
2409 assert_eq!(moved.path.as_deref(), Some("/home/synthetic/acme-site"));
2410 assert_eq!(moved.name, "Acme site");
2411 let renamed = store
2412 .update_work_project(&project.id, Some("Acme Corp site"), None)
2413 .await
2414 .unwrap()
2415 .unwrap();
2416 assert_eq!(
2417 (renamed.name.as_str(), renamed.path.as_deref()),
2418 ("Acme Corp site", Some("/home/synthetic/acme-site"))
2419 );
2420 let cleared = store
2421 .update_work_project(&project.id, None, Some(None))
2422 .await
2423 .unwrap()
2424 .unwrap();
2425 assert_eq!(cleared.path, None);
2426 assert!(
2427 store
2428 .update_work_project("project-missing", Some("x"), None)
2429 .await
2430 .unwrap()
2431 .is_none()
2432 );
2433 assert!(
2434 store
2435 .set_session_work_project("app:a", &project.id)
2436 .await
2437 .unwrap()
2438 );
2439 assert!(
2440 store
2441 .set_session_work_project("app:b", DEFAULT_PROJECT_ID)
2442 .await
2443 .unwrap()
2444 );
2445 assert_eq!(
2446 store.session_work_projects().await.unwrap(),
2447 vec![("app:a".to_string(), project.id.clone())]
2448 );
2449
2450 let bot = "telegram:synthetic_coding_bot";
2453 assert!(
2454 !store
2455 .place_chat_by_channel("synthetic_coding_bot:1", bot)
2456 .await
2457 .unwrap()
2458 );
2459 assert!(
2460 store
2461 .set_channel_work_project(bot, Some(&project.id))
2462 .await
2463 .unwrap()
2464 );
2465 assert_eq!(
2466 store.channel_work_projects().await.unwrap(),
2467 vec![(bot.to_string(), project.id.clone())]
2468 );
2469 assert!(
2470 store
2471 .place_chat_by_channel("synthetic_coding_bot:1", bot)
2472 .await
2473 .unwrap()
2474 );
2475 assert!(
2476 !store
2477 .place_chat_by_channel("synthetic_coding_bot:1", bot)
2478 .await
2479 .unwrap()
2480 );
2481 assert!(!store.place_chat_by_channel("app:b", "app").await.unwrap());
2482 assert!(
2483 !store
2484 .set_channel_work_project(bot, Some("project-missing"))
2485 .await
2486 .unwrap()
2487 );
2488 assert!(store.set_channel_work_project(bot, None).await.unwrap());
2489 assert!(store.channel_work_projects().await.unwrap().is_empty());
2490 assert!(
2491 !store
2492 .place_chat_by_channel("synthetic_coding_bot:2", bot)
2493 .await
2494 .unwrap()
2495 );
2496 }
2497
2498 #[tokio::test]
2499 async fn goal_run_is_pending_until_a_worker_claims_its_task() {
2500 let (store, _database) = test_store().await;
2501 let goal = Goal::new_finite("execute exactly once", "session-a");
2502 store.create_goal(&goal).await.unwrap();
2503 let run = store
2504 .start_goal_run(&goal.id, "manual", None, None)
2505 .await
2506 .unwrap();
2507 assert_eq!(run.status, "pending");
2508
2509 let root = task(&goal.id, "manual root", None);
2510 store.create_task(&root).await.unwrap();
2511 assert_eq!(
2512 store
2513 .get_current_goal_run(&goal.id)
2514 .await
2515 .unwrap()
2516 .unwrap()
2517 .status,
2518 "pending"
2519 );
2520
2521 store
2522 .claim_task_with_lease(&root.id, "worker-a", Some("profile-task-lead"), 180)
2523 .await
2524 .unwrap()
2525 .expect("claim succeeds");
2526 assert_eq!(
2527 store
2528 .get_current_goal_run(&goal.id)
2529 .await
2530 .unwrap()
2531 .unwrap()
2532 .status,
2533 "running"
2534 );
2535 }
2536
2537 #[tokio::test]
2538 async fn live_lease_marks_the_goal_run_owned_until_the_lease_ends() {
2539 let (store, _database) = test_store().await;
2542 let goal = Goal::new_finite("execute exactly once", "session-a");
2543 store.create_goal(&goal).await.unwrap();
2544 let run = store
2545 .start_goal_run(&goal.id, "scheduled", None, None)
2546 .await
2547 .unwrap();
2548 let root = task(&goal.id, "scheduled root", None);
2549 store.create_task(&root).await.unwrap();
2550 assert!(!store.goal_run_has_live_attempt(&run.id).await.unwrap());
2551
2552 let attempt = store
2553 .claim_task_with_lease(&root.id, "worker-a", Some("profile-task-lead"), 180)
2554 .await
2555 .unwrap()
2556 .expect("claim succeeds");
2557 assert!(store.goal_run_has_live_attempt(&run.id).await.unwrap());
2558
2559 assert!(
2561 store
2562 .patch_task_from_attempt(
2563 &attempt.id,
2564 &attempt.lease_token,
2565 &TaskAttemptPatch {
2566 status: "completed".to_string(),
2567 result: Some("done".to_string()),
2568 error: None,
2569 blocker: None,
2570 context: None,
2571 handoff: None,
2572 },
2573 )
2574 .await
2575 .unwrap()
2576 );
2577 assert!(!store.goal_run_has_live_attempt(&run.id).await.unwrap());
2578 }
2579
2580 #[tokio::test]
2581 async fn scheduled_run_terminalization_reconciles_child_obligations() {
2582 let (store, _database) = test_store().await;
2583 let goal = Goal::new_continuous("synthetic recurrence", "session-a", None, None);
2584 store.create_goal(&goal).await.unwrap();
2585 let run = store
2586 .start_goal_run(&goal.id, "scheduled", None, None)
2587 .await
2588 .unwrap();
2589 let child = task(&goal.id, "unfinished scheduled child", None);
2590 store.create_task(&child).await.unwrap();
2591
2592 let premature = store
2593 .finish_goal_run(&run.id, "completed", Some("premature"))
2594 .await;
2595 assert!(premature.is_err());
2596 assert_eq!(
2597 store
2598 .get_current_goal_run(&goal.id)
2599 .await
2600 .unwrap()
2601 .unwrap()
2602 .id,
2603 run.id
2604 );
2605
2606 assert!(
2607 store
2608 .finish_goal_run(&run.id, "failed", Some("terminal failure"))
2609 .await
2610 .unwrap()
2611 );
2612 let reconciled = store.get_tasks_for_goal_run(&run.id).await.unwrap();
2613 assert_eq!(reconciled[0].status, "cancelled");
2614 assert!(
2615 reconciled[0]
2616 .error
2617 .as_deref()
2618 .is_some_and(|error| error.contains("Parent scheduled occurrence"))
2619 );
2620 }
2621
2622 #[tokio::test]
2623 async fn active_root_lead_can_complete_its_own_scheduled_run() {
2624 let (store, _database) = test_store().await;
2625 let goal = Goal::new_continuous("synthetic daily publication", "session-a", None, None);
2626 store.create_goal(&goal).await.unwrap();
2627 let root = task(&goal.id, "scheduled lead", None);
2628 let run = store
2629 .start_goal_run(&goal.id, "scheduled", None, Some(&root.id))
2630 .await
2631 .unwrap();
2632 store.create_task(&root).await.unwrap();
2633 store
2634 .claim_task_with_lease(&root.id, "lead", Some("profile-task-lead"), 180)
2635 .await
2636 .unwrap()
2637 .expect("lead claims its root");
2638 let mut child = task(&goal.id, "publish one post", None);
2639 child.status = "completed".to_string();
2640 child.completed_at = Some(chrono::Utc::now().to_rfc3339());
2641 store.create_task(&child).await.unwrap();
2642
2643 assert!(
2646 store
2647 .finish_goal_run(&run.id, "completed", Some("published"))
2648 .await
2649 .expect("an active root lead must be able to complete its run")
2650 );
2651 }
2652
2653 #[tokio::test]
2654 async fn superseded_task_with_note_does_not_block_scheduled_completion() {
2655 let (store, _database) = test_store().await;
2656 let goal = Goal::new_continuous("synthetic daily publication", "session-a", None, None);
2657 store.create_goal(&goal).await.unwrap();
2658 let run = store
2659 .start_goal_run(&goal.id, "scheduled", None, None)
2660 .await
2661 .unwrap();
2662 let mut replaced = task(&goal.id, "specialist review", None);
2663 replaced.status = "superseded".to_string();
2664 replaced.error = Some("timed out; the lead reviewed directly".to_string());
2665 store.create_task(&replaced).await.unwrap();
2666 let mut done = task(&goal.id, "publish one post", None);
2667 done.status = "completed".to_string();
2668 store.create_task(&done).await.unwrap();
2669
2670 assert!(
2671 store
2672 .finish_goal_run(&run.id, "completed", Some("published"))
2673 .await
2674 .expect("superseded work is resolved, as Task::satisfies_run_completion says")
2675 );
2676 }
2677
2678 #[tokio::test]
2679 async fn failed_root_still_blocks_scheduled_run_completion() {
2680 let (store, _database) = test_store().await;
2681 let goal = Goal::new_continuous("synthetic daily publication", "session-a", None, None);
2682 store.create_goal(&goal).await.unwrap();
2683 let mut root = task(&goal.id, "scheduled lead", None);
2684 root.status = "failed".to_string();
2685 root.error = Some("lead crashed".to_string());
2686 let run = store
2687 .start_goal_run(&goal.id, "scheduled", None, Some(&root.id))
2688 .await
2689 .unwrap();
2690 store.create_task(&root).await.unwrap();
2691
2692 assert!(
2693 store
2694 .finish_goal_run(&run.id, "completed", Some("premature"))
2695 .await
2696 .is_err()
2697 );
2698 }
2699
2700 #[tokio::test]
2701 async fn claims_are_dependency_aware_fenced_and_handed_off() {
2702 let (store, _database) = test_store().await;
2703 let goal = Goal::new_finite("coordinate a release", "session-a");
2704 store.create_goal(&goal).await.unwrap();
2705 let first = task(&goal.id, "prepare", None);
2706 let second = task(&goal.id, "verify", Some(vec![first.id.clone()]));
2707 store.create_task(&first).await.unwrap();
2708 store.create_task(&second).await.unwrap();
2709
2710 assert!(
2711 store
2712 .claim_task_with_lease(&second.id, "worker-b", Some("profile-review"), 180)
2713 .await
2714 .unwrap()
2715 .is_none()
2716 );
2717 let first_attempt = store
2718 .claim_task_with_lease(&first.id, "worker-a", Some("profile-code"), 180)
2719 .await
2720 .unwrap()
2721 .unwrap();
2722 let patch = TaskAttemptPatch {
2723 status: "completed".to_string(),
2724 result: Some("prepared".to_string()),
2725 handoff: Some(handoff(
2726 &first.id,
2727 &first_attempt.id,
2728 "Preparation complete",
2729 )),
2730 ..Default::default()
2731 };
2732 assert!(
2733 store
2734 .patch_task_from_attempt(&first_attempt.id, &first_attempt.lease_token, &patch,)
2735 .await
2736 .unwrap()
2737 );
2738 assert_eq!(
2739 store
2740 .get_latest_task_handoff(&first.id)
2741 .await
2742 .unwrap()
2743 .unwrap()
2744 .verification,
2745 vec!["check passed"]
2746 );
2747 assert!(
2748 store
2749 .claim_task_with_lease(&second.id, "worker-b", Some("profile-review"), 180)
2750 .await
2751 .unwrap()
2752 .is_some()
2753 );
2754 assert!(
2755 !store
2756 .patch_task_from_attempt(
2757 &first_attempt.id,
2758 &first_attempt.lease_token,
2759 &TaskAttemptPatch {
2760 status: "failed".to_string(),
2761 error: Some("late write".to_string()),
2762 ..Default::default()
2763 },
2764 )
2765 .await
2766 .unwrap()
2767 );
2768 }
2769
2770 #[tokio::test]
2771 async fn normalized_dependency_edges_are_atomic_and_reject_cycles() {
2772 let (store, _database) = test_store().await;
2773 let goal = Goal::new_finite("dependency graph", "session-a");
2774 store.create_goal(&goal).await.unwrap();
2775 let first = task(&goal.id, "first", None);
2776 let second = task(&goal.id, "second", Some(vec![first.id.clone()]));
2777 store.create_task(&first).await.unwrap();
2778 store.create_task(&second).await.unwrap();
2779
2780 let edge_count = sqlx::query_scalar::<_, i64>(
2781 "SELECT COUNT(*) FROM task_dependencies WHERE task_id = ?",
2782 )
2783 .bind(&second.id)
2784 .fetch_one(&store.pool)
2785 .await
2786 .unwrap();
2787 assert_eq!(edge_count, 1);
2788
2789 let mut cyclic = first.clone();
2790 cyclic.depends_on = Some(serde_json::json!([second.id]).to_string());
2791 let error = store.update_task(&cyclic).await.unwrap_err();
2792 assert!(error.to_string().contains("task dependency cycle"));
2793
2794 let unchanged = store.get_task(&first.id).await.unwrap().unwrap();
2795 assert!(unchanged.depends_on.is_none());
2796 assert_eq!(
2797 sqlx::query_scalar::<_, i64>(
2798 "SELECT COUNT(*) FROM task_dependencies WHERE task_id = ?",
2799 )
2800 .bind(&first.id)
2801 .fetch_one(&store.pool)
2802 .await
2803 .unwrap(),
2804 0
2805 );
2806 }
2807
2808 #[tokio::test]
2809 async fn retries_and_claims_clear_stale_task_outcomes() {
2810 let (store, _database) = test_store().await;
2811 let goal = Goal::new_finite("retry cleanly", "session-a");
2812 store.create_goal(&goal).await.unwrap();
2813
2814 let failed = task(&goal.id, "failed once", None);
2815 store.create_task(&failed).await.unwrap();
2816 sqlx::query(
2817 "UPDATE tasks
2818 SET status = 'failed', result = 'old result', error = 'old error',
2819 blocker = 'old blocker', completed_at = datetime('now')
2820 WHERE id = ?",
2821 )
2822 .bind(&failed.id)
2823 .execute(&store.pool)
2824 .await
2825 .unwrap();
2826 assert!(
2827 store
2828 .retry_work_task(&failed.id, "owner", Some("telegram"))
2829 .await
2830 .unwrap()
2831 );
2832 let retried = store.get_task(&failed.id).await.unwrap().unwrap();
2833 assert_eq!(retried.status, "pending");
2834 assert!(retried.result.is_none());
2835 assert!(retried.error.is_none());
2836 assert!(retried.blocker.is_none());
2837 assert!(retried.completed_at.is_none());
2838
2839 let stale_pending = task(&goal.id, "legacy pending", None);
2840 store.create_task(&stale_pending).await.unwrap();
2841 sqlx::query(
2842 "UPDATE tasks
2843 SET result = 'stale result', error = 'stale error',
2844 blocker = 'stale blocker', completed_at = datetime('now')
2845 WHERE id = ?",
2846 )
2847 .bind(&stale_pending.id)
2848 .execute(&store.pool)
2849 .await
2850 .unwrap();
2851 assert!(
2852 store
2853 .claim_task_with_lease(&stale_pending.id, "worker-a", None, 180)
2854 .await
2855 .unwrap()
2856 .is_some()
2857 );
2858 let claimed = store.get_task(&stale_pending.id).await.unwrap().unwrap();
2859 assert_eq!(claimed.status, "claimed");
2860 assert!(claimed.result.is_none());
2861 assert!(claimed.error.is_none());
2862 assert!(claimed.blocker.is_none());
2863 assert!(claimed.completed_at.is_none());
2864 }
2865
2866 #[tokio::test]
2867 async fn expired_leases_retry_safe_work_and_block_ambiguous_work() {
2868 let (store, _database) = test_store().await;
2869 let goal = Goal::new_finite("recover work", "session-a");
2870 store.create_goal(&goal).await.unwrap();
2871 let safe = task(&goal.id, "safe read", None);
2872 let mut ambiguous = task(&goal.id, "external write", None);
2873 ambiguous.idempotent = false;
2874 ambiguous.max_retries = 0;
2875 store.create_task(&safe).await.unwrap();
2876 store.create_task(&ambiguous).await.unwrap();
2877 let safe_attempt = store
2878 .claim_task_with_lease(&safe.id, "worker-a", None, 180)
2879 .await
2880 .unwrap()
2881 .unwrap();
2882 let ambiguous_attempt = store
2883 .claim_task_with_lease(&ambiguous.id, "worker-b", None, 180)
2884 .await
2885 .unwrap()
2886 .unwrap();
2887 sqlx::query(
2888 "UPDATE task_attempts
2889 SET lease_expires_at = datetime('now', '-1 second')
2890 WHERE id IN (?, ?)",
2891 )
2892 .bind(&safe_attempt.id)
2893 .bind(&ambiguous_attempt.id)
2894 .execute(&store.pool)
2895 .await
2896 .unwrap();
2897
2898 let affected = store.recover_expired_task_attempts().await.unwrap();
2899 assert_eq!(affected.len(), 2);
2900 let safe_after = store.get_task(&safe.id).await.unwrap().unwrap();
2901 assert_eq!(safe_after.status, "pending");
2902 assert_eq!(safe_after.retry_count, 1);
2903 let ambiguous_after = store.get_task(&ambiguous.id).await.unwrap().unwrap();
2904 assert_eq!(ambiguous_after.status, "blocked");
2905 assert!(
2906 ambiguous_after
2907 .blocker
2908 .unwrap()
2909 .contains("Verify external side effects")
2910 );
2911 assert!(
2912 !store
2913 .heartbeat_task_attempt(&safe_attempt.id, &safe_attempt.lease_token, 180,)
2914 .await
2915 .unwrap()
2916 );
2917 }
2918
2919 #[tokio::test]
2920 async fn worker_profile_capacity_is_enforced() {
2921 let (store, _database) = test_store().await;
2922 let goal = Goal::new_finite("bounded workers", "session-a");
2923 store.create_goal(&goal).await.unwrap();
2924 let first = task(&goal.id, "one", None);
2925 let second = task(&goal.id, "two", None);
2926 let third = task(&goal.id, "three", None);
2927 store.create_task(&first).await.unwrap();
2928 store.create_task(&second).await.unwrap();
2929 store.create_task(&third).await.unwrap();
2930 assert!(
2931 store
2932 .claim_task_with_lease(&first.id, "one", Some("profile-code"), 180)
2933 .await
2934 .unwrap()
2935 .is_some()
2936 );
2937 assert!(
2938 store
2939 .claim_task_with_lease(&second.id, "two", Some("profile-code"), 180)
2940 .await
2941 .unwrap()
2942 .is_some()
2943 );
2944 assert!(
2945 store
2946 .claim_task_with_lease(&third.id, "three", Some("profile-code"), 180)
2947 .await
2948 .unwrap()
2949 .is_none()
2950 );
2951 let generic_attempt = store
2952 .claim_task_with_lease(&third.id, "three", Some("profile-executor"), 180)
2953 .await
2954 .unwrap()
2955 .unwrap();
2956 assert!(
2957 !store
2958 .bind_task_attempt_worker(
2959 &generic_attempt.id,
2960 &generic_attempt.lease_token,
2961 "three",
2962 Some("profile-code"),
2963 )
2964 .await
2965 .unwrap()
2966 );
2967 }
2968
2969 #[tokio::test]
2970 async fn starting_a_run_waits_out_a_competing_writer() {
2971 let (store, _database) = test_store().await;
2972 let mode: String = sqlx::query_scalar("PRAGMA journal_mode = WAL")
2973 .fetch_one(&store.pool)
2974 .await
2975 .unwrap();
2976 assert_eq!(mode.to_ascii_lowercase(), "wal");
2977
2978 let goal = Goal::new_finite("start after contention", "session-a");
2979 store.create_goal(&goal).await.unwrap();
2980
2981 let mut competing_writer = store.pool.begin_with("BEGIN IMMEDIATE").await.unwrap();
2982 sqlx::query("UPDATE goals SET updated_at = datetime('now') WHERE id = ?")
2983 .bind(&goal.id)
2984 .execute(&mut *competing_writer)
2985 .await
2986 .unwrap();
2987
2988 let store = Arc::new(store);
2989 let starting = store.clone();
2990 let goal_id = goal.id.clone();
2991 let started = tokio::spawn(async move {
2992 starting
2993 .start_goal_run(&goal_id, "scheduled", None, None)
2994 .await
2995 });
2996
2997 tokio::time::sleep(std::time::Duration::from_millis(50)).await;
2998 competing_writer.commit().await.unwrap();
2999 tokio::time::timeout(std::time::Duration::from_secs(2), started)
3000 .await
3001 .expect("the start should resume after the competing writer commits")
3002 .unwrap()
3003 .expect("a competing write must not fail the start");
3004 }
3005
3006 #[tokio::test]
3007 async fn worker_binding_waits_for_a_wal_writer_instead_of_losing_its_snapshot() {
3008 let (store, _database) = test_store().await;
3009 let mode: String = sqlx::query_scalar("PRAGMA journal_mode = WAL")
3010 .fetch_one(&store.pool)
3011 .await
3012 .unwrap();
3013 assert_eq!(mode.to_ascii_lowercase(), "wal");
3014
3015 let goal = Goal::new_finite("bind after contention", "session-a");
3016 store.create_goal(&goal).await.unwrap();
3017 let work = task(&goal.id, "scheduled root", None);
3018 store.create_task(&work).await.unwrap();
3019 let attempt = store
3020 .claim_task_with_lease(&work.id, "heartbeat-dispatch", None, 180)
3021 .await
3022 .unwrap()
3023 .unwrap();
3024
3025 let mut competing_writer = store.pool.begin_with("BEGIN IMMEDIATE").await.unwrap();
3026 sqlx::query("UPDATE goals SET updated_at = datetime('now') WHERE id = ?")
3027 .bind(&goal.id)
3028 .execute(&mut *competing_writer)
3029 .await
3030 .unwrap();
3031
3032 let store = Arc::new(store);
3033 let binding_store = store.clone();
3034 let attempt_id = attempt.id.clone();
3035 let lease_token = attempt.lease_token.clone();
3036 let binding = tokio::spawn(async move {
3037 binding_store
3038 .bind_task_attempt_worker(
3039 &attempt_id,
3040 &lease_token,
3041 "specialist:task-lead:test",
3042 None,
3043 )
3044 .await
3045 });
3046
3047 tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3048 competing_writer.commit().await.unwrap();
3049 assert!(
3050 tokio::time::timeout(std::time::Duration::from_secs(2), binding)
3051 .await
3052 .expect("binding should resume after the competing writer commits")
3053 .unwrap()
3054 .unwrap()
3055 );
3056
3057 let rebound = store
3058 .get_current_task_attempt(&work.id)
3059 .await
3060 .unwrap()
3061 .unwrap();
3062 assert_eq!(rebound.worker_instance_id, "specialist:task-lead:test");
3063 }
3064
3065 #[tokio::test]
3069 async fn container_scope_is_the_explicit_shared_policy_not_the_task_words() {
3070 let (store, _database) = test_store().await;
3071 let workspace_root = tempfile::TempDir::new().unwrap();
3072 let backend =
3073 aidaemon_tools::execution::local_backend(&aidaemon_tools::execution::ExecutionConfig {
3074 workspace_root: Some(workspace_root.path().to_string_lossy().into_owned()),
3075 allow_outside_workspace: Some(false),
3076 ..Default::default()
3077 })
3078 .await
3079 .unwrap();
3080 let goal = Goal::new_finite("synthetic workspace scope", "session-a");
3081 store.create_goal(&goal).await.unwrap();
3082 let worded = task(
3083 &goal.id,
3084 "Inspect all my projects in the projects folder",
3085 None,
3086 );
3087 let explicit = task(&goal.id, "Update one synthetic dependency", None);
3088 store.create_task(&worded).await.unwrap();
3089 store.create_task(&explicit).await.unwrap();
3090 assert!(
3091 store
3092 .set_task_workspace_policy(&explicit.id, "shared")
3093 .await
3094 .unwrap()
3095 );
3096
3097 let mut policies = Vec::new();
3098 for task in [&worded, &explicit] {
3099 let attempt = store
3100 .claim_task_with_lease(&task.id, "worker-a", None, 180)
3101 .await
3102 .unwrap()
3103 .unwrap();
3104 let workspace = crate::task_workspaces::provision_task_workspace(
3105 &backend, &store, &task.id, &attempt, None,
3106 )
3107 .await
3108 .unwrap();
3109 policies.push((workspace.policy, workspace.root_path));
3110 }
3111 let container = aidaemon_tools::ExecutionBackend::workspace_root(&backend).to_string();
3112 assert_eq!(policies[0].0, "isolated");
3113 assert_ne!(policies[0].1, container);
3114 assert_eq!(policies[1], ("shared".to_string(), container));
3115 }
3116
3117 #[tokio::test]
3118 async fn explicit_profile_and_workspace_choices_override_fallbacks() {
3119 let (store, _database) = test_store().await;
3120 let goal = Goal::new_finite("honor task policy", "session-a");
3121 store.create_goal(&goal).await.unwrap();
3122 let assigned = task(&goal.id, "review this", None);
3123 let workspace = task(&goal.id, "edit safely", None);
3124 store.create_task(&assigned).await.unwrap();
3125 store.create_task(&workspace).await.unwrap();
3126
3127 assert!(
3128 store
3129 .assign_task_worker_profile(
3130 &assigned.id,
3131 "profile-review",
3132 "owner",
3133 Some("telegram")
3134 )
3135 .await
3136 .unwrap()
3137 );
3138 let attempt = store
3139 .claim_task_with_lease(&assigned.id, "worker-a", Some("profile-code"), 180)
3140 .await
3141 .unwrap()
3142 .unwrap();
3143 assert_eq!(attempt.worker_profile_id.as_deref(), Some("profile-review"));
3144
3145 let mut code_profile = store
3146 .get_worker_profile("profile-code")
3147 .await
3148 .unwrap()
3149 .unwrap();
3150 code_profile.workspace_policy = "worktree".to_string();
3151 code_profile.version += 1;
3152 code_profile.updated_at = chrono::Utc::now().to_rfc3339();
3153 store.upsert_worker_profile(&code_profile).await.unwrap();
3154 assert!(
3155 store
3156 .assign_task_worker_profile(
3157 &workspace.id,
3158 "profile-code",
3159 "owner",
3160 Some("telegram")
3161 )
3162 .await
3163 .unwrap()
3164 );
3165 assert_eq!(
3166 store
3167 .get_task_workspace_policy(&workspace.id)
3168 .await
3169 .unwrap(),
3170 "worktree"
3171 );
3172 assert!(
3173 store
3174 .set_task_workspace_policy(&workspace.id, "shared")
3175 .await
3176 .unwrap()
3177 );
3178 assert_eq!(
3179 store
3180 .get_task_workspace_policy(&workspace.id)
3181 .await
3182 .unwrap(),
3183 "shared"
3184 );
3185 }
3186
3187 #[tokio::test]
3188 async fn projects_runs_profiles_and_human_unblocks_are_isolated() {
3189 let (store, _database) = test_store().await;
3190 let project = store
3191 .create_work_project("Operations", Some("production work"))
3192 .await
3193 .unwrap();
3194 assert!(
3195 store
3196 .set_session_work_project("session-ops", &project.id)
3197 .await
3198 .unwrap()
3199 );
3200 let goal = Goal::new_finite("operate service", "session-ops");
3201 store.create_goal(&goal).await.unwrap();
3202 let first_run = store.get_current_goal_run(&goal.id).await.unwrap().unwrap();
3203 assert_eq!(first_run.project_id, project.id);
3204 let blocked = task(&goal.id, "needs input", None);
3205 store.create_task(&blocked).await.unwrap();
3206 let attempt = store
3207 .claim_task_with_lease(&blocked.id, "worker-a", None, 180)
3208 .await
3209 .unwrap()
3210 .unwrap();
3211 assert!(
3212 store
3213 .patch_task_from_attempt(
3214 &attempt.id,
3215 &attempt.lease_token,
3216 &TaskAttemptPatch {
3217 status: "blocked".to_string(),
3218 blocker: Some("Need approval".to_string()),
3219 handoff: Some(handoff(&blocked.id, &attempt.id, "Waiting for approval")),
3220 ..Default::default()
3221 },
3222 )
3223 .await
3224 .unwrap()
3225 );
3226 let escalation = crate::traits::NotificationEntry::new(
3227 &goal.id,
3228 &goal.session_id,
3229 "escalation",
3230 "Approval required",
3231 )
3232 .with_task(&blocked.id);
3233 store.enqueue_notification(&escalation).await.unwrap();
3234 assert!(
3235 store
3236 .get_pending_notifications(20)
3237 .await
3238 .unwrap()
3239 .iter()
3240 .any(|entry| entry.id == escalation.id)
3241 );
3242 assert!(
3243 store
3244 .unblock_task(&blocked.id, "Approved by owner", "owner", Some("telegram"))
3245 .await
3246 .unwrap()
3247 );
3248 assert!(
3249 !store
3250 .get_pending_notifications(20)
3251 .await
3252 .unwrap()
3253 .iter()
3254 .any(|entry| entry.id == escalation.id)
3255 );
3256 let journal = store.get_task_journal(&blocked.id, 20).await.unwrap();
3257 assert!(journal.iter().any(|entry| entry.entry_type == "unblocked"));
3258
3259 store
3260 .cancel_work_task(&blocked.id, "owner", Some("telegram"))
3261 .await
3262 .unwrap();
3263 store
3264 .finish_goal_run(&first_run.id, "cancelled", Some("closed"))
3265 .await
3266 .unwrap();
3267 let second_run = store
3268 .start_goal_run(&goal.id, "manual", None, None)
3269 .await
3270 .unwrap();
3271 let current = task(&goal.id, "current run", None);
3272 store.create_task(¤t).await.unwrap();
3273 let current_tasks = store.get_tasks_for_goal_run(&second_run.id).await.unwrap();
3274 assert_eq!(current_tasks.len(), 1);
3275 assert_eq!(current_tasks[0].id, current.id);
3276 let board = store.list_work_tasks(&project.id, None, 100).await.unwrap();
3277 assert_eq!(board.len(), 1);
3278 assert_eq!(board[0].task_id, current.id);
3279
3280 let terminal_goal = Goal::new_finite("archived work", "session-ops");
3281 store.create_goal(&terminal_goal).await.unwrap();
3282 let terminal_task = task(&terminal_goal.id, "old completed task", None);
3283 store.create_task(&terminal_task).await.unwrap();
3284 sqlx::query(
3285 "UPDATE goals
3286 SET status = 'completed', completed_at = datetime('now'),
3287 updated_at = datetime('now')
3288 WHERE id = ?",
3289 )
3290 .bind(&terminal_goal.id)
3291 .execute(&store.pool)
3292 .await
3293 .unwrap();
3294 let terminal_run = store
3295 .get_current_goal_run(&terminal_goal.id)
3296 .await
3297 .unwrap()
3298 .unwrap();
3299 store
3300 .finish_goal_run(&terminal_run.id, "completed", Some("archived"))
3301 .await
3302 .unwrap();
3303 let active_board = store.list_work_tasks(&project.id, None, 100).await.unwrap();
3304 assert_eq!(active_board.len(), 1);
3305 assert_eq!(active_board[0].task_id, current.id);
3306 }
3307
3308 #[tokio::test]
3309 async fn board_projection_includes_every_active_scheduled_run() {
3310 let (store, _database) = test_store().await;
3311 let goal = Goal::new_finite("process every trigger", "session-a");
3312 store.create_goal(&goal).await.unwrap();
3313 let initial = task(&goal.id, "initial work", None);
3314 store.create_task(&initial).await.unwrap();
3315
3316 let first_scheduled = store
3317 .start_goal_run(&goal.id, "scheduled", None, None)
3318 .await
3319 .unwrap();
3320 let first_task = task(&goal.id, "first scheduled work", None);
3321 store.create_task(&first_task).await.unwrap();
3322 assert_eq!(
3323 store
3324 .get_current_goal_run(&goal.id)
3325 .await
3326 .unwrap()
3327 .unwrap()
3328 .id,
3329 first_scheduled.id
3330 );
3331
3332 let second_scheduled = store
3333 .start_goal_run(&goal.id, "scheduled", None, None)
3334 .await
3335 .unwrap();
3336 let second_task = task(&goal.id, "second scheduled work", None);
3337 store.create_task(&second_task).await.unwrap();
3338
3339 let tasks = store
3340 .list_work_tasks(DEFAULT_PROJECT_ID, None, 100)
3341 .await
3342 .unwrap();
3343 assert!(tasks.iter().any(|item| item.task_id == initial.id));
3344 assert!(tasks.iter().any(|item| item.task_id == first_task.id));
3345 assert!(tasks.iter().any(|item| item.task_id == second_task.id));
3346 let goals = store
3347 .list_work_goals(DEFAULT_PROJECT_ID, false, 100)
3348 .await
3349 .unwrap();
3350 assert!(
3351 goals
3352 .iter()
3353 .any(|item| item.run_id.as_deref() == Some(first_scheduled.id.as_str()))
3354 );
3355 assert!(
3356 goals
3357 .iter()
3358 .any(|item| item.run_id.as_deref() == Some(second_scheduled.id.as_str()))
3359 );
3360 }
3361
3362 #[tokio::test]
3363 async fn cancelled_tasks_are_archived_in_the_done_lane() {
3364 let (store, _database) = test_store().await;
3365 let goal = Goal::new_finite("cancel safely", "session-a");
3366 store.create_goal(&goal).await.unwrap();
3367 let cancelled = task(&goal.id, "no longer needed", None);
3368 store.create_task(&cancelled).await.unwrap();
3369 assert!(
3370 store
3371 .cancel_work_task(&cancelled.id, "owner", Some("telegram"))
3372 .await
3373 .unwrap()
3374 );
3375
3376 let done = store
3377 .list_work_tasks(DEFAULT_PROJECT_ID, Some("done"), 100)
3378 .await
3379 .unwrap();
3380 assert_eq!(done.len(), 1);
3381 assert_eq!(done[0].task_id, cancelled.id);
3382 assert_eq!(done[0].lane, "done");
3383 assert!(
3384 store
3385 .list_work_tasks(DEFAULT_PROJECT_ID, Some("needs_attention"), 100)
3386 .await
3387 .unwrap()
3388 .is_empty()
3389 );
3390 }
3391
3392 #[tokio::test]
3393 async fn terminal_legacy_history_is_not_the_current_continuous_run() {
3394 let (store, _database) = test_store().await;
3395 let goal = Goal::new_continuous("run every day", "session-a", None, None);
3396 store.create_goal(&goal).await.unwrap();
3397 let legacy = store
3398 .start_goal_run(&goal.id, "legacy", None, None)
3399 .await
3400 .unwrap();
3401 let historical = task(&goal.id, "old cycle", None);
3402 store.create_task(&historical).await.unwrap();
3403 sqlx::query("UPDATE tasks SET status='completed', completed_at=datetime('now') WHERE id=?")
3404 .bind(&historical.id)
3405 .execute(&store.pool)
3406 .await
3407 .unwrap();
3408 store
3409 .finish_goal_run(&legacy.id, "completed", Some("legacy history"))
3410 .await
3411 .unwrap();
3412
3413 assert!(
3414 store
3415 .list_work_tasks(DEFAULT_PROJECT_ID, None, 100)
3416 .await
3417 .unwrap()
3418 .is_empty()
3419 );
3420 let goals = store
3421 .list_work_goals(DEFAULT_PROJECT_ID, false, 100)
3422 .await
3423 .unwrap();
3424 assert_eq!(goals.len(), 1);
3425 assert!(goals[0].run_id.is_none());
3426 assert_eq!(goals[0].done, 0);
3427 }
3428
3429 #[tokio::test]
3430 async fn scheduled_failure_budget_escalates_and_resumes_only_owned_pauses() {
3431 let (store, _database) = test_store().await;
3432 let goal = Goal::new_continuous("publish synthetic report", "session-a", None, None);
3433 store.create_goal(&goal).await.unwrap();
3434 let now = chrono::Utc::now().to_rfc3339();
3435 let active_schedule = GoalSchedule {
3436 id: uuid::Uuid::new_v4().to_string(),
3437 goal_id: goal.id.clone(),
3438 cron_expr: "0 6 * * *".to_string(),
3439 tz: "local".to_string(),
3440 original_schedule: Some("daily".to_string()),
3441 fire_policy: "coalesce".to_string(),
3442 is_one_shot: false,
3443 is_paused: false,
3444 last_run_at: None,
3445 next_run_at: now.clone(),
3446 created_at: now.clone(),
3447 updated_at: now.clone(),
3448 };
3449 let owner_paused_schedule = GoalSchedule {
3450 id: uuid::Uuid::new_v4().to_string(),
3451 is_paused: true,
3452 ..active_schedule.clone()
3453 };
3454 store.create_goal_schedule(&active_schedule).await.unwrap();
3455 store
3456 .create_goal_schedule(&owner_paused_schedule)
3457 .await
3458 .unwrap();
3459
3460 for expected_failures in 1..=3 {
3461 let run = store
3462 .start_goal_run(&goal.id, "scheduled", Some(&active_schedule.id), None)
3463 .await
3464 .unwrap();
3465 assert!(
3466 store
3467 .finish_goal_run(&run.id, "failed", Some("synthetic failed run"))
3468 .await
3469 .unwrap()
3470 );
3471 let recovery = store
3472 .get_scheduled_recovery_state(&goal.id)
3473 .await
3474 .unwrap()
3475 .unwrap();
3476 assert_eq!(recovery.consecutive_failures, expected_failures);
3477 assert_eq!(
3478 recovery.latest_failure_kind,
3479 Some(crate::traits::ScheduledFailureKind::OutcomeUnproven)
3480 );
3481 }
3482
3483 let escalated = store
3484 .get_scheduled_recovery_state(&goal.id)
3485 .await
3486 .unwrap()
3487 .unwrap();
3488 assert_eq!(
3489 escalated.disposition,
3490 crate::traits::ScheduledRecoveryDisposition::Escalated
3491 );
3492 let schedules = store.get_schedules_for_goal(&goal.id).await.unwrap();
3493 assert!(schedules.iter().all(|schedule| schedule.is_paused));
3494 assert_eq!(
3495 store.get_goal(&goal.id).await.unwrap().unwrap().status,
3496 "active"
3497 );
3498 assert!(
3499 store
3500 .get_pending_notifications(20)
3501 .await
3502 .unwrap()
3503 .iter()
3504 .any(|notification| {
3505 notification.goal_id == goal.id
3506 && notification.notification_type == "escalation"
3507 })
3508 );
3509
3510 let recovery_run = store
3511 .start_goal_run(&goal.id, "scheduled", Some(&active_schedule.id), None)
3512 .await
3513 .unwrap();
3514 let mut recovery_task = task(&goal.id, "verify synthetic recovery", None);
3515 recovery_task.context = Some(
3516 serde_json::json!({
3517 "recovery_for_run": escalated.last_failed_run_id,
3518 "terminal_recovery": true
3519 })
3520 .to_string(),
3521 );
3522 store.create_task(&recovery_task).await.unwrap();
3523 sqlx::query("UPDATE goal_runs SET root_task_id = ? WHERE id = ?")
3524 .bind(&recovery_task.id)
3525 .bind(&recovery_run.id)
3526 .execute(&store.pool)
3527 .await
3528 .unwrap();
3529 let proof_receipt_id = "synthetic-recovery-proof";
3530 sqlx::query(
3531 "INSERT INTO events
3532 (session_id, event_type, data, created_at, task_id, tool_name)
3533 VALUES (?, 'tool_result', ?, ?, ?, 'http_request')",
3534 )
3535 .bind(&goal.session_id)
3536 .bind(
3537 serde_json::json!({
3538 "task_id": recovery_task.id,
3539 "tool_call_id": proof_receipt_id,
3540 "receipt": {
3541 "schema_version": aidaemon_events::ToolReceiptV1::SCHEMA_VERSION,
3542 "outcome_status": "succeeded",
3543 "outcome_evidence": "structured_metadata"
3544 }
3545 })
3546 .to_string(),
3547 )
3548 .bind(chrono::Utc::now().to_rfc3339())
3549 .bind(&recovery_task.id)
3550 .execute(&store.pool)
3551 .await
3552 .unwrap();
3553 recovery_task.status = "completed".to_string();
3554 recovery_task.result = Some("synthetic recovery verified".to_string());
3555 recovery_task.completed_at = Some(chrono::Utc::now().to_rfc3339());
3556 store.update_task(&recovery_task).await.unwrap();
3557 assert!(
3558 store
3559 .finish_goal_run(
3560 &recovery_run.id,
3561 "completed",
3562 Some("synthetic verified recovery"),
3563 )
3564 .await
3565 .unwrap()
3566 );
3567 let healthy = store
3568 .get_scheduled_recovery_state(&goal.id)
3569 .await
3570 .unwrap()
3571 .unwrap();
3572 assert_eq!(healthy.consecutive_failures, 0);
3573 assert_eq!(
3574 healthy.disposition,
3575 crate::traits::ScheduledRecoveryDisposition::Healthy
3576 );
3577 let recovery_link: (String, String) = sqlx::query_as(
3578 "SELECT outcome_status, proof_receipt_ids_json
3579 FROM goal_run_recovery_links WHERE recovery_run_id = ?",
3580 )
3581 .bind(&recovery_run.id)
3582 .fetch_one(&store.pool)
3583 .await
3584 .unwrap();
3585 assert_eq!(recovery_link.0, "verified");
3586 assert_eq!(
3587 serde_json::from_str::<Vec<String>>(&recovery_link.1).unwrap(),
3588 vec![proof_receipt_id]
3589 );
3590 let schedules = store.get_schedules_for_goal(&goal.id).await.unwrap();
3591 assert!(
3592 !schedules
3593 .iter()
3594 .find(|schedule| schedule.id == active_schedule.id)
3595 .unwrap()
3596 .is_paused
3597 );
3598 assert!(
3599 schedules
3600 .iter()
3601 .find(|schedule| schedule.id == owner_paused_schedule.id)
3602 .unwrap()
3603 .is_paused
3604 );
3605 }
3606
3607 #[tokio::test]
3608 async fn recovery_proof_matches_receipts_emitted_under_the_bound_worker_session() {
3609 let (store, _database) = test_store().await;
3617 let goal = Goal::new_continuous("publish synthetic report", "session-a", None, None);
3618 store.create_goal(&goal).await.unwrap();
3619 let now = chrono::Utc::now().to_rfc3339();
3620 let schedule = GoalSchedule {
3621 id: uuid::Uuid::new_v4().to_string(),
3622 goal_id: goal.id.clone(),
3623 cron_expr: "0 6 * * *".to_string(),
3624 tz: "local".to_string(),
3625 original_schedule: Some("daily".to_string()),
3626 fire_policy: "coalesce".to_string(),
3627 is_one_shot: false,
3628 is_paused: false,
3629 last_run_at: None,
3630 next_run_at: now.clone(),
3631 created_at: now.clone(),
3632 updated_at: now.clone(),
3633 };
3634 store.create_goal_schedule(&schedule).await.unwrap();
3635 for _ in 0..3 {
3636 let run = store
3637 .start_goal_run(&goal.id, "scheduled", Some(&schedule.id), None)
3638 .await
3639 .unwrap();
3640 assert!(
3641 store
3642 .finish_goal_run(&run.id, "failed", Some("synthetic failed run"))
3643 .await
3644 .unwrap()
3645 );
3646 }
3647 let escalated = store
3648 .get_scheduled_recovery_state(&goal.id)
3649 .await
3650 .unwrap()
3651 .unwrap();
3652 assert_eq!(
3653 escalated.disposition,
3654 crate::traits::ScheduledRecoveryDisposition::Escalated
3655 );
3656
3657 let recovery_run = store
3658 .start_goal_run(&goal.id, "recovery", None, None)
3659 .await
3660 .unwrap();
3661 let mut recovery_task = task(&goal.id, "recover the synthetic objective", None);
3662 recovery_task.context = Some(
3663 serde_json::json!({
3664 "recovery_for_run": escalated.last_failed_run_id,
3665 "terminal_recovery": true
3666 })
3667 .to_string(),
3668 );
3669 store.create_task(&recovery_task).await.unwrap();
3670 sqlx::query("UPDATE goal_runs SET root_task_id = ? WHERE id = ?")
3671 .bind(&recovery_task.id)
3672 .bind(&recovery_run.id)
3673 .execute(&store.pool)
3674 .await
3675 .unwrap();
3676 sqlx::query("UPDATE tasks SET goal_run_id = ? WHERE id = ?")
3677 .bind(&recovery_run.id)
3678 .bind(&recovery_task.id)
3679 .execute(&store.pool)
3680 .await
3681 .unwrap();
3682
3683 let worker_session = "specialist:task_lead:synthetic-recovery";
3686 let attempt = store
3687 .claim_task_with_lease(&recovery_task.id, "heartbeat-dispatch", None, 180)
3688 .await
3689 .unwrap()
3690 .unwrap();
3691 assert!(
3692 store
3693 .bind_task_attempt_worker(&attempt.id, &attempt.lease_token, worker_session, None)
3694 .await
3695 .unwrap()
3696 );
3697
3698 let proof_receipt_id = "session-edge-recovery-proof";
3701 sqlx::query(
3702 "INSERT INTO events
3703 (session_id, event_type, data, created_at, task_id, tool_name)
3704 VALUES (?, 'tool_result', ?, ?, ?, 'terminal')",
3705 )
3706 .bind(worker_session)
3707 .bind(
3708 serde_json::json!({
3709 "task_id": uuid::Uuid::new_v4().to_string(),
3710 "tool_call_id": proof_receipt_id,
3711 "receipt": {
3712 "schema_version": aidaemon_events::ToolReceiptV1::SCHEMA_VERSION,
3713 "outcome_status": "succeeded",
3714 "outcome_evidence": "tool_reported"
3715 }
3716 })
3717 .to_string(),
3718 )
3719 .bind(chrono::Utc::now().to_rfc3339())
3720 .bind(Option::<String>::None)
3721 .execute(&store.pool)
3722 .await
3723 .unwrap();
3724
3725 recovery_task.status = "completed".to_string();
3726 recovery_task.result = Some("synthetic recovery verified".to_string());
3727 recovery_task.completed_at = Some(chrono::Utc::now().to_rfc3339());
3728 store.update_task(&recovery_task).await.unwrap();
3729 assert!(
3730 store
3731 .finish_goal_run(
3732 &recovery_run.id,
3733 "completed",
3734 Some("verified via session edge")
3735 )
3736 .await
3737 .unwrap()
3738 );
3739
3740 let healthy = store
3741 .get_scheduled_recovery_state(&goal.id)
3742 .await
3743 .unwrap()
3744 .unwrap();
3745 assert_eq!(
3746 healthy.disposition,
3747 crate::traits::ScheduledRecoveryDisposition::Healthy,
3748 "a recovery proven by receipts under the bound worker session must heal the objective"
3749 );
3750 assert_eq!(healthy.consecutive_failures, 0);
3751 }
3752
3753 #[tokio::test]
3758 async fn a_missed_run_is_history_and_does_not_count_toward_the_failure_budget() {
3759 let (store, _database) = test_store().await;
3760 let goal = Goal::new_continuous("synthetic daily digest", "session-a", None, None);
3761 store.create_goal(&goal).await.unwrap();
3762 let now = chrono::Utc::now().to_rfc3339();
3763 let schedule = GoalSchedule {
3764 id: uuid::Uuid::new_v4().to_string(),
3765 goal_id: goal.id.clone(),
3766 cron_expr: "0 9 * * *".to_string(),
3767 tz: "local".to_string(),
3768 original_schedule: Some("daily at 9am".to_string()),
3769 fire_policy: "coalesce".to_string(),
3770 is_one_shot: false,
3771 is_paused: false,
3772 last_run_at: None,
3773 next_run_at: now.clone(),
3774 created_at: now.clone(),
3775 updated_at: now.clone(),
3776 };
3777 store.create_goal_schedule(&schedule).await.unwrap();
3778 for _ in 0..2 {
3780 let run = store
3781 .start_goal_run(&goal.id, "scheduled", Some(&schedule.id), None)
3782 .await
3783 .unwrap();
3784 assert!(
3785 store
3786 .finish_goal_run(&run.id, "failed", Some("synthetic failure"))
3787 .await
3788 .unwrap()
3789 );
3790 }
3791 let due = (chrono::Utc::now() - chrono::Duration::hours(30)).to_rfc3339();
3793 for _ in 0..3 {
3794 let missed = store
3795 .record_missed_goal_run(
3796 &goal.id,
3797 Some(&schedule.id),
3798 &due,
3799 "The daemon wasn't running when this was due.",
3800 )
3801 .await
3802 .unwrap();
3803 assert_eq!(missed.status, GOAL_RUN_MISSED);
3804 assert_eq!(missed.started_at, due, "a miss is dated when it was due");
3805 assert!(missed.completed_at.is_some(), "a miss is closed");
3806 }
3807 let recovery = store
3808 .get_scheduled_recovery_state(&goal.id)
3809 .await
3810 .unwrap()
3811 .unwrap();
3812 assert_eq!(recovery.consecutive_failures, 2, "misses are not failures");
3813 assert_eq!(
3814 recovery.disposition,
3815 crate::traits::ScheduledRecoveryDisposition::Recovering
3816 );
3817 assert!(
3818 !store.get_schedules_for_goal(&goal.id).await.unwrap()[0].is_paused,
3819 "misses never pause an automation"
3820 );
3821 let runs = store.get_goal_runs(&goal.id).await.unwrap();
3823 assert_eq!(
3824 runs.iter().filter(|r| r.status == GOAL_RUN_MISSED).count(),
3825 3
3826 );
3827 assert!(
3828 store
3829 .get_current_goal_run(&goal.id)
3830 .await
3831 .unwrap()
3832 .is_none()
3833 );
3834 let run = store
3837 .start_goal_run(&goal.id, "scheduled", Some(&schedule.id), None)
3838 .await
3839 .unwrap();
3840 assert!(runs.iter().all(|r| r.id != run.id));
3841 store
3842 .finish_goal_run(&run.id, "failed", Some("synthetic failure"))
3843 .await
3844 .unwrap();
3845 let recovery = store
3846 .get_scheduled_recovery_state(&goal.id)
3847 .await
3848 .unwrap()
3849 .unwrap();
3850 assert_eq!(recovery.consecutive_failures, 3);
3851 }
3852}
3853
3854fn paused_notice(
3857 name: &str,
3858 failures: i64,
3859 kind: crate::traits::ScheduledFailureKind,
3860 latest: Option<&str>,
3861) -> String {
3862 use crate::traits::ScheduledFailureKind as Kind;
3863 let why = latest
3864 .map(|text| text.trim().trim_end_matches('.'))
3865 .filter(|text| !text.is_empty())
3866 .map(str::to_string)
3867 .unwrap_or_else(|| {
3868 match kind {
3869 Kind::AuthorizationBlocked => "a step it needed was not allowed",
3870 Kind::RetryableTool => "a tool kept failing",
3871 Kind::PermanentTool => "a tool it needs failed",
3872 Kind::TaskFailed => "the run could not finish its work",
3873 Kind::OutcomeUnproven => "it could not show the work was done",
3874 }
3875 .to_string()
3876 });
3877 format!(
3878 "Paused \"{name}\" after {failures} failed runs in a row, so it stops retrying. \
3879 Latest problem: {why}. Fix the cause, then resume it in Automations, or ask me to look into it."
3880 )
3881}
3882
3883#[cfg(test)]
3884mod paused_notice_tests {
3885 use super::paused_notice;
3886 use crate::traits::ScheduledFailureKind;
3887
3888 #[test]
3889 fn the_pause_notice_names_the_automation_the_cause_and_what_to_do() {
3890 let text = paused_notice(
3891 "Daily report",
3892 3,
3893 ScheduledFailureKind::TaskFailed,
3894 Some("The report file was missing."),
3895 );
3896 assert_eq!(
3897 text,
3898 "Paused \"Daily report\" after 3 failed runs in a row, so it stops retrying. \
3899 Latest problem: The report file was missing. Fix the cause, then resume it in \
3900 Automations, or ask me to look into it."
3901 );
3902 let text = paused_notice("Daily report", 3, ScheduledFailureKind::RetryableTool, None);
3903 assert!(
3904 text.contains("Latest problem: a tool kept failing."),
3905 "{text}"
3906 );
3907 assert!(
3908 !text.contains("objective") && !text.contains("budget"),
3909 "{text}"
3910 );
3911 }
3912}