Skip to main content

aidaemon_work/sqlite/
work.rs

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