Skip to main content

orch/engine/tasks/jobs/
mod.rs

1//! Job scheduler — replaces `jobs_tick.sh`.
2//!
3//! Reads job definitions from `jobs.yml`, checks cron schedules against
4//! the current time, and creates tasks for due jobs. Handles catch-up
5//! for missed schedules (capped at 24h).
6//!
7//! Job types:
8//! - `task`: creates a task (GitHub Issue or internal SQLite) and lets the engine dispatch it
9//! - `bash`: runs a shell command directly (no LLM)
10//! - `self-review`: analyzes task metrics and creates self-improvement issues
11//!
12//! For task jobs, the `external` field controls where the task is created:
13//! - `external: false` (default): Creates an internal SQLite task
14//! - `external: true`: Creates a GitHub Issue
15
16pub mod cron;
17
18use crate::backends::{ExternalBackend, ExternalId};
19use crate::channels::notification::TaskNotification;
20use crate::channels::transport::Transport;
21use crate::config;
22use crate::engine::chore;
23use crate::engine::tasks::jobs::cron as crate_cron;
24use crate::engine::tasks::unblock;
25use crate::engine::tasks::unblock::Unblocked;
26use crate::github::http::has_status;
27use crate::store::TaskStore;
28use crate::store::{JobState, TaskStatus};
29use crate::sys::cmd as cmd_mod;
30use crate::sys::home;
31use anyhow::Context;
32use dashmap::{DashMap, DashSet};
33use serde::{Deserialize, Serialize};
34use std::collections::HashSet;
35use std::fs;
36use std::path::{Path, PathBuf};
37use std::process::{Output, Stdio};
38use std::result;
39use std::sync::{Arc, LazyLock};
40use std::time::Duration;
41use tokio::process::Command;
42use tokio::task;
43use tokio::time;
44
45// Note: self-review analysis is now performed by scheduled tasks configured
46// in `.orch.yml` and executed as regular `task` jobs. Hardcoded self-review
47// logic was removed to keep this module a generic job dispatcher.
48
49/// A scheduled job definition (from jobs.yml).
50#[derive(Debug, Clone, Serialize, Deserialize)]
51pub struct Job {
52    pub id: String,
53    #[serde(default = "default_job_type")]
54    pub r#type: String,
55    pub schedule: String,
56    #[serde(default)]
57    pub task: Option<TaskTemplate>,
58    #[serde(default)]
59    pub command: Option<String>,
60    #[serde(default)]
61    pub dir: Option<String>,
62    #[serde(default = "default_enabled")]
63    pub enabled: bool,
64    #[serde(default = "default_external")]
65    pub external: bool, // true = GitHub Issue, false (default) = internal SQLite task
66    /// Send a Telegram notification when this job completes or fails.
67    /// Uses `channels.telegram.chat_id` from config unless `notify_target` overrides it.
68    #[serde(default)]
69    pub notify: bool,
70    /// Override the Telegram chat_id for this job's completion notification.
71    /// Only used when `notify: true`. Falls back to `channels.telegram.chat_id`.
72    #[serde(default)]
73    pub notify_target: Option<String>,
74    /// `Some(false)` runs this job's agent outside the OS sandbox, for a job that drives an app
75    /// over Apple Events, which no sandboxed process may send. Unset follows the project
76    #[serde(default, skip_serializing_if = "Option::is_none")]
77    pub sandbox: Option<bool>,
78    /// Path to the `prompts/jobs/*.md` file this job was loaded from, if any.
79    ///
80    /// `None` means the job was defined inline in `.orch.yml` / `config.yml`.
81    /// Set by `scan_prompt_jobs`; skipped during serialization so it never
82    /// leaks into config files.
83    #[serde(skip)]
84    pub prompt_file: Option<PathBuf>,
85}
86
87/// Template for creating a task from a job.
88#[derive(Debug, Clone, Serialize, Deserialize)]
89pub struct TaskTemplate {
90    pub title: String,
91    #[serde(default)]
92    pub body: String,
93    /// Path to a file (typically markdown) whose contents are used as the
94    /// task body. Resolved relative to the directory of the config file
95    /// that defines this job. Mutually exclusive with `body`.
96    #[serde(default, skip_serializing_if = "Option::is_none")]
97    pub prompt: Option<String>,
98    #[serde(default)]
99    pub labels: Vec<String>,
100    #[serde(default)]
101    pub agent: Option<String>,
102}
103
104/// Resolve the body for a task template, reading from `prompt` if set.
105///
106/// `base_dir` is the directory containing the jobs config file (used to
107/// resolve relative `prompt` paths).
108pub fn resolve_template_body(template: &TaskTemplate, base_dir: &Path) -> anyhow::Result<String> {
109    match template.prompt.as_deref() {
110        Some(rel) => {
111            let path = Path::new(rel);
112            let full = if path.is_absolute() {
113                path.to_path_buf()
114            } else {
115                base_dir.join(path)
116            };
117            fs::read_to_string(&full)
118                .with_context(|| format!("reading prompt file {}", full.display()))
119        }
120        None => Ok(template.body.clone()),
121    }
122}
123
124/// Working directory for a bash job, resolved against the project `base_dir`
125fn resolve_job_dir(job: &Job, base_dir: &Path) -> PathBuf {
126    match job.dir.as_deref().map(Path::new) {
127        None => base_dir.to_path_buf(),
128        Some(path) if path.is_absolute() => path.to_path_buf(),
129        Some(path) => base_dir.join(path),
130    }
131}
132
133fn default_job_type() -> String {
134    "task".to_string()
135}
136
137fn default_enabled() -> bool {
138    true
139}
140
141fn default_external() -> bool {
142    false // Default to internal (SQLite) tasks
143}
144
145/// Top-level config structure (for reading jobs from .orch.yml / config.yml).
146#[derive(Debug, Serialize, Deserialize)]
147struct ConfigFile {
148    #[serde(default)]
149    jobs: Vec<Job>,
150    // Capture all other fields so we can round-trip them
151    #[serde(flatten)]
152    other: serde_norway::Mapping,
153}
154
155/// Resolve the config file that contains jobs.
156///
157/// Priority:
158/// 1. `.orch.yml` in the current directory (project config)
159/// 2. `.orch.yml` in any registered project directory (from global config)
160/// 3. `~/.orch/config.yml` (global config)
161pub fn resolve_jobs_path() -> PathBuf {
162    // 1. Check cwd
163    let project = PathBuf::from(".orch.yml");
164    if project.exists() {
165        return project;
166    }
167
168    // 2. Check registered project directories (handles brew service running from /)
169    if let Ok(paths) = config::get_project_paths() {
170        for path_str in &paths {
171            let candidate = PathBuf::from(path_str).join(".orch.yml");
172            if candidate.exists() {
173                return candidate;
174            }
175        }
176    }
177
178    // 3. Fall back to global config
179    home::config_path().unwrap_or_else(|_| PathBuf::from(".orch/config.yml"))
180}
181
182/// Load jobs from the orch config file plus any markdown prompt files
183/// discovered under `<base_dir>/prompts/jobs/*.md`.
184///
185/// Inline `jobs:` in `.orch.yml` and discovered prompt files are merged;
186/// duplicate ids across the two sources are rejected.
187pub fn load_jobs(path: &PathBuf) -> anyhow::Result<Vec<Job>> {
188    let base_dir = path
189        .parent()
190        .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
191    let mut jobs: Vec<Job> = if path.exists() {
192        let content =
193            fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
194        let file: ConfigFile = serde_norway::from_str(&content)
195            .with_context(|| format!("parsing {}", path.display()))?;
196        file.jobs
197    } else {
198        vec![]
199    };
200
201    let scanned = scan_prompt_jobs(&base_dir)?;
202    let mut seen: HashSet<String> = jobs.iter().map(|j| j.id.clone()).collect();
203    for job in scanned {
204        if !seen.insert(job.id.clone()) {
205            anyhow::bail!(
206                "duplicate job id '{}' — defined in both '{}' and prompts/jobs/",
207                job.id,
208                path.display()
209            );
210        }
211        jobs.push(job);
212    }
213
214    for job in &jobs {
215        validate_job(job, &base_dir)?;
216    }
217    Ok(jobs)
218}
219
220fn validate_job(job: &Job, base_dir: &Path) -> anyhow::Result<()> {
221    crate_cron::schedule(&job.schedule)
222        .with_context(|| format!("job '{}': invalid cron schedule '{}'", job.id, job.schedule))?;
223    if let Some(template) = job.task.as_ref() {
224        if template.prompt.is_some() && !template.body.is_empty() {
225            anyhow::bail!(
226                "job '{}': set either 'task.body' or 'task.prompt', not both",
227                job.id
228            );
229        }
230        if let Some(rel) = template.prompt.as_deref() {
231            let candidate = Path::new(rel);
232            let full = if candidate.is_absolute() {
233                candidate.to_path_buf()
234            } else {
235                base_dir.join(candidate)
236            };
237            if !full.exists() {
238                anyhow::bail!(
239                    "job '{}': prompt file not found: {}",
240                    job.id,
241                    full.display()
242                );
243            }
244        }
245    }
246    Ok(())
247}
248
249/// Frontmatter schema for `prompts/jobs/*.md` files.
250#[derive(Debug, Deserialize)]
251struct JobFrontmatter {
252    id: String,
253    schedule: String,
254    title: String,
255    #[serde(default = "default_job_type")]
256    r#type: String,
257    #[serde(default = "default_enabled")]
258    enabled: bool,
259    #[serde(default = "default_external")]
260    external: bool,
261    #[serde(default)]
262    labels: Vec<String>,
263    #[serde(default)]
264    agent: Option<String>,
265    #[serde(default)]
266    notify: bool,
267    #[serde(default)]
268    notify_target: Option<String>,
269    #[serde(default)]
270    command: Option<String>,
271    #[serde(default)]
272    dir: Option<String>,
273    #[serde(default)]
274    sandbox: Option<bool>,
275}
276
277/// Split a markdown file into (frontmatter, body). Returns `None` if the file
278/// does not start with a `---` fence.
279fn split_frontmatter(content: &str) -> Option<(&str, &str)> {
280    let rest = content
281        .strip_prefix("---\n")
282        .or_else(|| content.strip_prefix("---\r\n"))?;
283    let end = rest.find("\n---\n").or_else(|| rest.find("\n---\r\n"))?;
284    let fm = &rest[..end];
285    let after = &rest[end..];
286    let body = after
287        .strip_prefix("\n---\n")
288        .or_else(|| after.strip_prefix("\n---\r\n"))
289        .unwrap_or(after);
290    Some((fm, body.trim_start_matches('\n')))
291}
292
293/// Scan `<base_dir>/prompts/jobs/*.md` for job-defining markdown files.
294pub fn scan_prompt_jobs(base_dir: &Path) -> anyhow::Result<Vec<Job>> {
295    let dir = base_dir.join("prompts").join("jobs");
296    if !dir.is_dir() {
297        return Ok(vec![]);
298    }
299    let mut entries: Vec<PathBuf> = fs::read_dir(&dir)
300        .with_context(|| format!("reading {}", dir.display()))?
301        .filter_map(result::Result::ok)
302        .map(|e| e.path())
303        .filter(|p| p.extension().and_then(|s| s.to_str()) == Some("md"))
304        .collect();
305    entries.sort();
306
307    let mut jobs = Vec::with_capacity(entries.len());
308    for path in entries {
309        let content =
310            fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;
311        let Some((fm, body)) = split_frontmatter(&content) else {
312            continue; // No frontmatter → treat as a plain prompt referenced from .orch.yml
313        };
314        let meta: JobFrontmatter = serde_norway::from_str(fm)
315            .with_context(|| format!("parsing frontmatter in {}", path.display()))?;
316        jobs.push(Job {
317            id: meta.id,
318            r#type: meta.r#type,
319            schedule: meta.schedule,
320            task: Some(TaskTemplate {
321                title: meta.title,
322                body: body.to_string(),
323                prompt: None,
324                labels: meta.labels,
325                agent: meta.agent,
326            }),
327            command: meta.command,
328            dir: meta.dir,
329            enabled: meta.enabled,
330            external: meta.external,
331            notify: meta.notify,
332            notify_target: meta.notify_target,
333            sandbox: meta.sandbox,
334            prompt_file: Some(path.clone()),
335        });
336    }
337    Ok(jobs)
338}
339
340/// Whether the job that started `task_id` turns the sandbox off. The jobs are read from the main
341/// checkout, which the agent cannot write, so only a merged change can turn it off
342pub async fn sandbox_off_for(
343    store: &TaskStore,
344    repo: &str,
345    project_dir: &Path,
346    task_id: &str,
347) -> bool {
348    let mut states = store.list_job_states(repo).await.unwrap_or_default();
349    overlay_pending_job_states(repo, &mut states);
350    let Some(job_id) = states
351        .into_iter()
352        .find(|s| s.active_task_id.as_deref() == Some(task_id))
353        .map(|s| s.job_id)
354    else {
355        return false;
356    };
357
358    let path = project_dir.join(".orch.yml");
359    let Ok(Ok(jobs)) = task::spawn_blocking(move || load_jobs(&path)).await else {
360        return false;
361    };
362
363    jobs.iter()
364        .any(|j| j.id == job_id && j.sandbox == Some(false))
365}
366
367/// Save jobs back to the config file, preserving all other keys.
368pub fn save_jobs(path: &PathBuf, jobs: &[Job]) -> anyhow::Result<()> {
369    // Read the existing file to preserve non-jobs keys
370    let mut file: ConfigFile = if path.exists() {
371        let content =
372            fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
373        serde_norway::from_str(&content).with_context(|| format!("parsing {}", path.display()))?
374    } else {
375        ConfigFile {
376            jobs: vec![],
377            other: serde_norway::Mapping::new(),
378        }
379    };
380
381    // Only persist inline jobs (those without a prompt_file source).
382    // Prompt-based jobs live in prompts/jobs/*.md and must not be duplicated
383    // into .orch.yml — doing so causes a "duplicate job id" error on the next
384    // load_jobs call.
385    file.jobs = jobs
386        .iter()
387        .filter(|j| j.prompt_file.is_none())
388        .cloned()
389        .collect();
390    let content = serde_norway::to_string(&file)?;
391    fs::write(path, content).with_context(|| format!("writing {}", path.display()))?;
392    Ok(())
393}
394
395/// Update the `enabled:` field in the YAML frontmatter of a prompt-based job
396/// file, preserving all other content unchanged.
397///
398/// The function rewrites only the `enabled:` line inside the opening `---`
399/// fence.  If the field is absent it is inserted before the closing `---`.
400pub fn set_frontmatter_enabled(path: &Path, enabled: bool) -> anyhow::Result<()> {
401    let original =
402        fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
403
404    let value = if enabled { "true" } else { "false" };
405
406    // Replace an existing `enabled: <anything>` line inside the frontmatter.
407    // We only touch the first YAML block (between the opening and first closing
408    // `---` fences) to avoid accidentally rewriting the body.
409    let rewritten = rewrite_frontmatter_enabled(&original, value);
410    fs::write(path, rewritten).with_context(|| format!("writing {}", path.display()))?;
411    Ok(())
412}
413
414/// Rewrite the `enabled:` key inside the first `---` fence block of `content`.
415///
416/// If the key is present, its value is replaced.  If absent, it is appended
417/// just before the closing `---` line.  The rest of the document is unchanged.
418fn rewrite_frontmatter_enabled(content: &str, value: &str) -> String {
419    // Locate the opening fence.
420    let Some(rest) = content
421        .strip_prefix("---\n")
422        .or_else(|| content.strip_prefix("---\r\n"))
423    else {
424        // No frontmatter: return unchanged.
425        return content.to_string();
426    };
427
428    // Find the closing fence.
429    let Some(close_pos) = rest.find("\n---\n").or_else(|| rest.find("\n---\r\n")) else {
430        return content.to_string();
431    };
432
433    let fm = &rest[..close_pos];
434    let after_close = &rest[close_pos..]; // starts with "\n---\n" or "\n---\r\n"
435
436    // Rebuild the frontmatter, replacing or inserting `enabled:`.
437    let new_line = format!("enabled: {value}");
438    let mut found = false;
439    let new_fm: String = fm
440        .lines()
441        .map(|line| {
442            if line == "enabled: true" || line == "enabled: false" || line.starts_with("enabled: ")
443            {
444                found = true;
445                new_line.clone()
446            } else {
447                line.to_string()
448            }
449        })
450        .collect::<Vec<_>>()
451        .join("\n");
452
453    let new_fm = if found {
454        new_fm
455    } else {
456        format!("{new_fm}\n{new_line}")
457    };
458
459    format!("---\n{new_fm}{after_close}")
460}
461
462/// Returns `true` if the error indicates a "not found" (404) response.
463///
464/// Used to distinguish permanent task deletion from transient API errors.
465/// A 404 should clear `active_task_id`; other errors (rate limit, 5xx,
466/// network timeout) should be retried next tick without losing the reference.
467fn is_not_found_error(e: &anyhow::Error) -> bool {
468    // The status is matched apart from the URL, which holds the issue number
469    e.chain().any(|cause| has_status(&cause.to_string(), 404))
470}
471
472/// Check all jobs and execute due ones.
473///
474/// Runtime state (last_run, active_task_id, last_task_status) is stored in
475/// SQLite via the `job_state` table, not in the YAML config file.
476pub async fn tick(
477    jobs_path: &Path,
478    backend: &Arc<dyn ExternalBackend>,
479    store: Option<&Arc<TaskStore>>,
480    repo: &str,
481    transport: Option<&Arc<Transport>>,
482) -> anyhow::Result<()> {
483    let jobs_path_clone = jobs_path.to_path_buf();
484    let jobs = match task::spawn_blocking(move || load_jobs(&jobs_path_clone))
485        .await
486        .map_err(|e| anyhow::anyhow!("load_jobs panicked: {e}"))
487        .and_then(|r| r)
488    {
489        Ok(j) => j,
490        Err(e) => {
491            tracing::error!(
492                path = %jobs_path.display(),
493                repo = %repo,
494                ?e,
495                "job config invalid — skipping scheduler tick for this project"
496            );
497            return Ok(());
498        }
499    };
500    let now = chrono::Utc::now();
501
502    for job in &jobs {
503        if !job.enabled {
504            continue;
505        }
506
507        // Load runtime state from SQLite
508        let mut state = if let Some(s) = store {
509            match s.get_job_state(repo, &job.id).await {
510                Ok(Some(st)) => st,
511                Ok(None) => JobState::new(repo, &job.id),
512                Err(e) => {
513                    tracing::error!(job_id = job.id, ?e, "failed to load job state, skipping");
514                    continue;
515                }
516            }
517        } else {
518            JobState::new(repo, &job.id)
519        };
520
521        // Retry a lost post-create write even when the job is not due
522        if let Some(pending) = pending_job_state(repo, &job.id) {
523            state.active_task_id.clone_from(&pending.active_task_id);
524            state.last_task_status.clone_from(&pending.last_task_status);
525            if let Some(s) = store
526                && persist_job_state(s, &pending).await.is_err()
527            {
528                continue;
529            }
530        }
531
532        // Collect a bash job another node ran, see `chore`
533        if job.r#type == "bash"
534            && let Some(s) = store
535        {
536            match chore::poll(s, &chore::bash_key(repo, &job.id)).await {
537                chore::Poll::Done(chore::Outcome::Bash { status }) => {
538                    tracing::info!(job_id = job.id, status, "bash job finished on another node");
539                    state.last_task_status = Some(status);
540                    if let Err(e) = s.upsert_job_state(&state).await {
541                        tracing::error!(
542                            job_id = job.id,
543                            ?e,
544                            "failed to persist job state after execution"
545                        );
546                    }
547                    notify_job_result(job, &state, repo, transport);
548                    continue;
549                }
550                chore::Poll::Pending(node) => {
551                    tracing::debug!(
552                        job_id = job.id,
553                        node,
554                        "skipping: bash job still running on another node"
555                    );
556                    continue;
557                }
558                _ => {}
559            }
560        }
561
562        // Check if schedule matches
563        let is_due = match &state.last_run {
564            Some(last) => match crate_cron::check(&job.schedule, Some(last)) {
565                Ok(v) => v,
566                Err(e) => {
567                    tracing::error!(
568                        job_id = job.id,
569                        schedule = job.schedule,
570                        ?e,
571                        "invalid cron expression, skipping"
572                    );
573                    continue;
574                }
575            },
576            None => match crate_cron::check(&job.schedule, None) {
577                Ok(v) => v,
578                Err(e) => {
579                    tracing::error!(
580                        job_id = job.id,
581                        schedule = job.schedule,
582                        ?e,
583                        "invalid cron expression, skipping"
584                    );
585                    continue;
586                }
587            },
588        };
589
590        if !is_due {
591            continue;
592        }
593
594        // Check if previous task is still active
595        let mut should_clear_task_id = false;
596        let mut should_skip = false;
597        let mut blocked = false;
598        let mut blocked_store_id = None;
599
600        if let Some(ref task_id) = state.active_task_id
601            && task_id.is_empty()
602        {
603            state.active_task_id = None;
604        }
605
606        if let Some(ref task_id) = state.active_task_id {
607            let task_id_clone = task_id.clone();
608            let is_active = if job.external {
609                // Check external (GitHub) task
610                match backend.get_task(&ExternalId(task_id_clone.clone())).await {
611                    Ok(task) => {
612                        let status = task.labels.iter().find(|l| l.starts_with("status:"));
613                        match status.map(String::as_str) {
614                            Some(
615                                "status:in_progress"
616                                | "status:routed"
617                                | "status:new"
618                                | "status:needs_review"
619                                | "status:in_review"
620                                | "status:approved"
621                                | "status:waiting",
622                            )
623                            | None => true, // no status label is treated as active
624                            Some("status:blocked") => {
625                                blocked = true;
626                                false
627                            }
628                            Some(_) => false, // Done
629                        }
630                    }
631                    Err(e) => {
632                        if is_not_found_error(&e) {
633                            tracing::warn!(
634                                job_id = job.id,
635                                task_id = task_id_clone,
636                                "active task not found (404), clearing active_task_id"
637                            );
638                            should_clear_task_id = true;
639                            state.last_task_status = Some("error".to_string());
640                        } else {
641                            tracing::warn!(
642                                job_id = job.id,
643                                task_id = task_id_clone,
644                                ?e,
645                                "transient error fetching active task, skipping tick (active_task_id preserved)"
646                            );
647                            should_skip = true;
648                        }
649                        false
650                    }
651                }
652            } else {
653                // Check internal task via store
654                if let Some(s) = store {
655                    match s.resolve_task_id(repo, &task_id_clone).await {
656                        Ok(Some(store_id)) => match s.get(store_id).await {
657                            Ok(task) => match task.status {
658                                TaskStatus::New
659                                | TaskStatus::Routed
660                                | TaskStatus::InProgress
661                                | TaskStatus::NeedsReview
662                                | TaskStatus::InReview
663                                | TaskStatus::Approved
664                                | TaskStatus::Waiting => true,
665                                TaskStatus::Blocked => {
666                                    blocked = true;
667                                    blocked_store_id = Some(store_id);
668                                    false
669                                }
670                                TaskStatus::Done => false,
671                            },
672                            Err(e) => {
673                                tracing::warn!(
674                                    job_id = job.id,
675                                    task_id = task_id_clone,
676                                    ?e,
677                                    "transient error fetching internal task, skipping tick (active_task_id preserved)"
678                                );
679                                should_skip = true;
680                                false
681                            }
682                        },
683                        Ok(None) => {
684                            tracing::warn!(
685                                job_id = job.id,
686                                task_id = task_id_clone,
687                                "internal task not found in store, clearing active_task_id"
688                            );
689                            should_clear_task_id = true;
690                            false
691                        }
692                        Err(e) => {
693                            tracing::warn!(
694                                job_id = job.id,
695                                task_id = task_id_clone,
696                                ?e,
697                                "store error resolving internal task, skipping tick (active_task_id preserved)"
698                            );
699                            should_skip = true;
700                            false
701                        }
702                    }
703                } else {
704                    should_clear_task_id = true;
705                    false
706                }
707            };
708
709            if is_active {
710                tracing::debug!(
711                    job_id = job.id,
712                    task_id = task_id_clone,
713                    external = job.external,
714                    "skipping: previous task still active"
715                );
716                should_skip = true;
717            }
718        }
719
720        // Apply deferred mutations
721        if should_clear_task_id {
722            state.active_task_id = None;
723        }
724
725        if should_skip {
726            continue;
727        }
728
729        if blocked
730            && job.r#type == "task"
731            && let Some(s) = store
732            && let Some(task_id) = state.active_task_id.clone()
733        {
734            let target = BlockedTask {
735                task_id: &task_id,
736                store_id: blocked_store_id,
737            };
738            match retry_blocked_task(job, &mut state, backend, s, repo, &target, now).await {
739                BlockedRetry::Retried | BlockedRetry::Skip => continue,
740                BlockedRetry::CreateNew => {}
741            }
742        }
743
744        // A bash job needs a checkout, so on a leader that does not host the repo it goes to a
745        // node that does. Waiting for one keeps last_run, so the next tick tries again
746        let host = match (job.r#type == "bash", store) {
747            (true, Some(s)) => chore::place(s, repo).await,
748            _ => chore::Where::Here,
749        };
750        if host == chore::Where::Waiting {
751            let note = chore::waiting_note(repo);
752            if state.last_task_status.as_deref() != Some(note.as_str()) {
753                tracing::info!(
754                    job_id = job.id,
755                    repo,
756                    "bash job waits for a node with the repo"
757                );
758                state.last_task_status = Some(note);
759                if let Some(s) = store
760                    && let Err(e) = s.upsert_job_state(&state).await
761                {
762                    tracing::warn!(job_id = job.id, ?e, "failed to record the wait for a node");
763                }
764            }
765            continue;
766        }
767
768        // Claim the slot before last_run so a still-running bash job is skipped
769        // without bumping last_run, and a failed last_run write drops the guard
770        let bash_guard = if job.r#type == "bash" && host == chore::Where::Here {
771            let Some(guard) = RunningBash::try_acquire(repo, &job.id) else {
772                tracing::debug!(job_id = job.id, "skipping: bash job still running");
773                continue;
774            };
775            Some(guard)
776        } else {
777            None
778        };
779
780        tracing::info!(job_id = job.id, r#type = job.r#type, "job due, executing");
781
782        // Persist last_run BEFORE execution to prevent catch-up on restart.
783        // On restart the runtime state is loaded from SQLite, so writing
784        // last_run here ensures a crash during execution won't cause the
785        // job to be considered due again immediately.
786        state.last_run = Some(now.format("%Y-%m-%dT%H:%M:%SZ").to_string());
787        if let Some(s) = store
788            && let Err(e) = s.upsert_job_state(&state).await
789        {
790            tracing::error!(
791                job_id = job.id,
792                ?e,
793                "failed to persist job state before execution — skipping this tick to preserve restart safety"
794            );
795            continue; // retry next tick instead of risking duplicate execution
796        }
797
798        if let (chore::Where::Node(node), Some(s)) = (&host, store) {
799            tracing::info!(
800                job_id = job.id,
801                node,
802                "bash job runs on a node that hosts the repo"
803            );
804            let request = chore::Request::Bash {
805                job: Box::new(job.clone()),
806            };
807            if let Err(e) = chore::assign(s, repo, node, request).await {
808                tracing::error!(job_id = job.id, ?e, "failed to hand the bash job to a node");
809            }
810            continue;
811        }
812
813        let base_dir = jobs_path.parent().unwrap_or_else(|| Path::new("."));
814        if let Some(guard) = bash_guard {
815            spawn_bash_job(
816                guard,
817                job.clone(),
818                state,
819                store.cloned(),
820                repo.to_string(),
821                transport.cloned(),
822                base_dir.to_path_buf(),
823            );
824            continue;
825        }
826
827        execute_and_save(job, &mut state, backend, store, repo, transport, base_dir).await;
828    }
829
830    Ok(())
831}
832
833/// What a due job does with its blocked task
834enum BlockedRetry {
835    Retried,
836    Skip,
837    CreateNew,
838}
839
840/// The job's active task, found blocked
841struct BlockedTask<'a> {
842    task_id: &'a str,
843    store_id: Option<i64>,
844}
845
846/// Unblock the job's blocked task instead of creating another. A PR closed unmerged means a
847/// person rejected the work, so that task stays blocked and the job creates a new one
848async fn retry_blocked_task(
849    job: &Job,
850    state: &mut JobState,
851    backend: &Arc<dyn ExternalBackend>,
852    store: &Arc<TaskStore>,
853    repo: &str,
854    blocked: &BlockedTask<'_>,
855    now: chrono::DateTime<chrono::Utc>,
856) -> BlockedRetry {
857    let task_id = blocked.task_id;
858    let store_id = match blocked.store_id {
859        Some(id) => Some(id),
860        None => match store.resolve_task_id(repo, task_id).await {
861            Ok(id) => id,
862            Err(e) => {
863                tracing::warn!(
864                    job_id = job.id,
865                    task_id,
866                    ?e,
867                    "store error resolving blocked task, skipping tick"
868                );
869                return BlockedRetry::Skip;
870            }
871        },
872    };
873
874    let pr_number = match store_id {
875        Some(id) => match store.get(id).await {
876            Ok(task) => task.pr_number,
877            Err(e) => {
878                tracing::warn!(
879                    job_id = job.id,
880                    task_id,
881                    ?e,
882                    "store error reading blocked task, skipping tick"
883                );
884                return BlockedRetry::Skip;
885            }
886        },
887        None => None,
888    };
889    if let Some(pr) = pr_number {
890        match backend.pull_request_completion(repo, i64::from(pr)).await {
891            Ok(Some(pr_state)) if pr_state.closed && !pr_state.merged => {
892                tracing::info!(
893                    job_id = job.id,
894                    task_id,
895                    pr_number = pr,
896                    "PR closed unmerged, leaving task blocked and creating a new one"
897                );
898                return BlockedRetry::CreateNew;
899            }
900            Ok(_) => {}
901            Err(e) => {
902                tracing::warn!(
903                    job_id = job.id,
904                    task_id,
905                    pr_number = pr,
906                    ?e,
907                    "failed to read PR state of blocked task, skipping tick"
908                );
909                return BlockedRetry::Skip;
910            }
911        }
912    }
913
914    // last_run first, so a failed unblock still waits for the next schedule slot
915    state.last_run = Some(now.format("%Y-%m-%dT%H:%M:%SZ").to_string());
916    if let Err(e) = store.upsert_job_state(state).await {
917        tracing::error!(
918            job_id = job.id,
919            ?e,
920            "failed to persist job state before retrying blocked task"
921        );
922        return BlockedRetry::Skip;
923    }
924
925    let task_backend = job.external.then_some(backend);
926    let status = match unblock::unblock_task(store, task_backend, repo, task_id, store_id).await {
927        Ok(Unblocked::New) => "new",
928        Ok(Unblocked::Waiting) => "waiting",
929        Err(e) => {
930            tracing::error!(
931                job_id = job.id,
932                task_id,
933                ?e,
934                "failed to unblock the job's blocked task"
935            );
936            "error"
937        }
938    };
939    tracing::info!(
940        job_id = job.id,
941        task_id,
942        status,
943        "job due, retrying its blocked task"
944    );
945    state.last_task_status = Some(status.to_string());
946    persist_job_state(store, state).await.ok();
947    BlockedRetry::Retried
948}
949
950/// Bash jobs this process has spawned and not yet finished, keyed by repo and job id
951static RUNNING_BASH: LazyLock<DashSet<(String, String)>> = LazyLock::new(DashSet::new);
952
953// Created task id waiting for a successful job_state upsert
954static PENDING_JOB_STATE: LazyLock<DashMap<(String, String), JobState>> =
955    LazyLock::new(DashMap::new);
956
957const JOB_STATE_PERSIST_ATTEMPTS: u32 = 2;
958
959/// Releases the in-process slot when the spawned bash job ends
960struct RunningBash {
961    key: (String, String),
962}
963
964impl RunningBash {
965    fn try_acquire(repo: &str, job_id: &str) -> Option<Self> {
966        let key = (repo.to_string(), job_id.to_string());
967        if RUNNING_BASH.insert(key.clone()) {
968            Some(Self { key })
969        } else {
970            None
971        }
972    }
973}
974
975impl Drop for RunningBash {
976    fn drop(&mut self) {
977        RUNNING_BASH.remove(&self.key);
978    }
979}
980
981fn spawn_bash_job(
982    guard: RunningBash,
983    job: Job,
984    mut state: JobState,
985    store: Option<Arc<TaskStore>>,
986    repo: String,
987    transport: Option<Arc<Transport>>,
988    base_dir: PathBuf,
989) {
990    tokio::spawn(async move {
991        let _guard = guard;
992        apply_bash_result(&job, &mut state, &base_dir).await;
993        if let Some(s) = &store
994            && let Err(e) = s.upsert_job_state(&state).await
995        {
996            tracing::error!(
997                job_id = job.id,
998                ?e,
999                "failed to persist job state after execution"
1000            );
1001        }
1002        notify_job_result(&job, &state, &repo, transport.as_ref());
1003    });
1004}
1005
1006async fn apply_bash_result(job: &Job, state: &mut JobState, base_dir: &Path) {
1007    if job.command.is_some() {
1008        state.last_task_status = Some(run_bash_job(job, base_dir).await);
1009    }
1010}
1011
1012/// Run a `bash` job's command in its directory under `base_dir`. Returns `done`, `failed` or
1013/// `timeout`, the value `job_state.last_task_status` holds
1014pub(crate) async fn run_bash_job(job: &Job, base_dir: &Path) -> String {
1015    let Some(cmd) = job.command.as_deref() else {
1016        return "failed".to_string();
1017    };
1018    // Unset `dir` and relative `dir` resolve against `base_dir`, the project dir.
1019    // The brew service cwd is `/`, so `"."` and `"scripts"` would otherwise run there
1020    let dir = resolve_job_dir(job, base_dir);
1021    tracing::info!(job_id = job.id, cmd, dir = %dir.display(), "running bash command");
1022
1023    // Configurable timeout with 5-minute default. A hung command is killed so
1024    // the next cron period can start a fresh run
1025    let timeout_secs: u64 = config::get("jobs.bash_timeout_seconds")
1026        .ok()
1027        .and_then(|s| s.parse().ok())
1028        .unwrap_or(300);
1029    let timeout = Duration::from_secs(timeout_secs);
1030
1031    match run_bash(cmd, &dir, timeout).await {
1032        Ok(Ok(o)) if o.status.success() => "done".to_string(),
1033        Ok(Ok(o)) => {
1034            let stderr = String::from_utf8_lossy(&o.stderr);
1035            tracing::warn!(
1036                job_id = job.id,
1037                code = o.status.code(),
1038                %stderr,
1039                "bash command failed"
1040            );
1041            "failed".to_string()
1042        }
1043        Ok(Err(e)) => {
1044            tracing::error!(job_id = job.id, ?e, "bash command error");
1045            "failed".to_string()
1046        }
1047        Err(_) => {
1048            tracing::error!(
1049                job_id = job.id,
1050                secs = timeout_secs,
1051                "bash job timed out after {}s, child killed",
1052                timeout_secs
1053            );
1054            "timeout".to_string()
1055        }
1056    }
1057}
1058
1059/// Runs `bash -c` under a timeout in its own process group, so a timeout kills the commands bash
1060/// forked too
1061async fn run_bash(
1062    cmd: &str,
1063    dir: &Path,
1064    timeout: Duration,
1065) -> result::Result<anyhow::Result<Output>, time::error::Elapsed> {
1066    let mut command = Command::new("bash");
1067    command
1068        .arg("-c")
1069        .arg(cmd)
1070        .current_dir(dir)
1071        .stdin(Stdio::null())
1072        .stdout(Stdio::piped())
1073        .stderr(Stdio::piped())
1074        .kill_on_drop(true);
1075    #[cfg(unix)]
1076    command.process_group(0);
1077
1078    let child = match command.spawn() {
1079        Ok(child) => child,
1080        Err(e) => return Ok(Err(anyhow::anyhow!("failed to execute `bash`: {e}"))),
1081    };
1082    let pgid = child.id();
1083    let out = time::timeout(timeout, child.wait_with_output()).await;
1084
1085    #[cfg(unix)]
1086    if out.is_err()
1087        && let Some(pgid) = pgid
1088    {
1089        cmd_mod::kill_process_group(pgid);
1090    }
1091
1092    out.map(|r| r.map_err(|e| anyhow::anyhow!("failed to execute `bash`: {e}")))
1093}
1094
1095fn job_state_key(repo: &str, job_id: &str) -> (String, String) {
1096    (repo.to_string(), job_id.to_string())
1097}
1098
1099fn pending_job_state(repo: &str, job_id: &str) -> Option<JobState> {
1100    PENDING_JOB_STATE
1101        .get(&job_state_key(repo, job_id))
1102        .map(|entry| (*entry).clone())
1103}
1104
1105fn overlay_pending_job_states(repo: &str, states: &mut Vec<JobState>) {
1106    for entry in PENDING_JOB_STATE.iter() {
1107        let (key, pending) = entry.pair();
1108        if key.0 != repo {
1109            continue;
1110        }
1111        if let Some(existing) = states.iter_mut().find(|s| s.job_id == key.1) {
1112            existing.active_task_id.clone_from(&pending.active_task_id);
1113            existing
1114                .last_task_status
1115                .clone_from(&pending.last_task_status);
1116        } else {
1117            states.push(pending.clone());
1118        }
1119    }
1120}
1121
1122async fn persist_job_state(store: &TaskStore, state: &JobState) -> anyhow::Result<()> {
1123    let mut last_err = None;
1124    for attempt in 1..=JOB_STATE_PERSIST_ATTEMPTS {
1125        match store.upsert_job_state(state).await {
1126            Ok(()) => {
1127                PENDING_JOB_STATE.remove(&job_state_key(&state.repo, &state.job_id));
1128                return Ok(());
1129            }
1130            Err(e) => {
1131                tracing::error!(
1132                    job_id = %state.job_id,
1133                    attempt,
1134                    ?e,
1135                    "failed to persist job state after execution"
1136                );
1137                last_err = Some(e);
1138            }
1139        }
1140    }
1141    if state.active_task_id.is_some() {
1142        PENDING_JOB_STATE.insert(job_state_key(&state.repo, &state.job_id), state.clone());
1143    }
1144    Err(last_err.expect("job state persist attempted at least once"))
1145}
1146
1147/// Run the job and save its state, whose `active_task_id` is how the runner finds the job
1148/// behind a task, for `sandbox: false`
1149pub async fn execute_and_save(
1150    job: &Job,
1151    state: &mut JobState,
1152    backend: &Arc<dyn ExternalBackend>,
1153    store: Option<&Arc<TaskStore>>,
1154    repo: &str,
1155    transport: Option<&Arc<Transport>>,
1156    base_dir: &Path,
1157) {
1158    execute_job(job, state, backend, store, repo, transport, base_dir).await;
1159
1160    if let Some(s) = store {
1161        persist_job_state(s, state).await.ok();
1162    }
1163}
1164
1165pub async fn execute_job(
1166    job: &Job,
1167    state: &mut JobState,
1168    backend: &Arc<dyn ExternalBackend>,
1169    store: Option<&Arc<TaskStore>>,
1170    repo: &str,
1171    transport: Option<&Arc<Transport>>,
1172    base_dir: &Path,
1173) {
1174    match job.r#type.as_str() {
1175        "task" => {
1176            if let Some(ref template) = job.task {
1177                let body = match resolve_template_body(template, base_dir) {
1178                    Ok(b) => b,
1179                    Err(e) => {
1180                        tracing::error!(job_id = job.id, ?e, "failed to resolve task body");
1181                        state.last_task_status = Some("failed".to_string());
1182                        return;
1183                    }
1184                };
1185
1186                if job.external {
1187                    let mut labels = template.labels.clone();
1188                    labels.push("scheduled".to_string());
1189                    labels.push(format!("job:{}", job.id));
1190
1191                    if let Some(ref agent) = template.agent
1192                        && !agent.is_empty()
1193                    {
1194                        labels.push(format!("agent:{agent}"));
1195                    }
1196
1197                    match backend.create_task(&template.title, &body, &labels).await {
1198                        Ok(ext_id) => {
1199                            tracing::info!(
1200                                job_id = job.id,
1201                                task_id = ext_id.0,
1202                                "created external task"
1203                            );
1204                            state.active_task_id = Some(ext_id.0);
1205                            state.last_task_status = Some("new".to_string());
1206                        }
1207                        Err(e) => {
1208                            tracing::error!(job_id = job.id, ?e, "failed to create external task");
1209                            state.last_task_status = Some("failed".to_string());
1210                        }
1211                    }
1212                } else if let Some(s) = store {
1213                    match s
1214                        .create_internal(repo, &template.title, &body, "cron", &job.id, None)
1215                        .await
1216                    {
1217                        Ok(internal_id) => {
1218                            let task_id = format!("internal:{internal_id}");
1219                            tracing::info!(job_id = job.id, task_id, "created internal task");
1220                            state.active_task_id = Some(task_id);
1221                            state.last_task_status = Some("new".to_string());
1222                        }
1223                        Err(e) => {
1224                            tracing::error!(job_id = job.id, ?e, "failed to create internal task");
1225                            state.last_task_status = Some("failed".to_string());
1226                        }
1227                    }
1228                } else {
1229                    tracing::error!(
1230                        job_id = job.id,
1231                        "no store available for internal task creation"
1232                    );
1233                    state.last_task_status = Some("failed".to_string());
1234                }
1235            }
1236        }
1237        "bash" => {
1238            apply_bash_result(job, state, base_dir).await;
1239        }
1240        // Note: previous versions supported a special-case "self-review"
1241        // job type with embedded analysis logic. That logic has been removed
1242        // — self-review work should be configured as a regular `task` job in
1243        // `.orch.yml` and executed by agents. Unknown job types fall through
1244        // to the warning handler below.
1245        other => {
1246            tracing::warn!(job_id = job.id, r#type = other, "unknown job type");
1247        }
1248    }
1249
1250    notify_job_result(job, state, repo, transport);
1251}
1252
1253fn notify_job_result(job: &Job, state: &JobState, repo: &str, transport: Option<&Arc<Transport>>) {
1254    if job.notify
1255        && let Some(t) = transport
1256    {
1257        let status = state
1258            .last_task_status
1259            .as_deref()
1260            .unwrap_or("unknown")
1261            .to_string();
1262        let summary = match status.as_str() {
1263            "done" => format!("Job `{}` completed successfully.", job.id),
1264            "failed" => format!("Job `{}` failed.", job.id),
1265            "new" => format!("Job `{}` created a new task.", job.id),
1266            other => format!("Job `{}` finished with status: {other}.", job.id),
1267        };
1268        // Resolve target chat_id: job override → config default
1269        let target = job
1270            .notify_target
1271            .clone()
1272            .or_else(|| config::get("channels.telegram.chat_id").ok());
1273        let notification = TaskNotification {
1274            task_id: job.id.clone(),
1275            title: format!("Job: {}", job.id),
1276            status,
1277            agent: "scheduler".to_string(),
1278            duration_seconds: 0.0,
1279            summary,
1280            repo: Some(repo.to_string()),
1281            notify_target: target,
1282            pr_number: None,
1283        };
1284        t.push_notification(notification);
1285    }
1286}
1287
1288// NOTE: self-review analysis is handled by scheduled `task` jobs configured
1289// in `.orch.yml` and executed by agents. There is no embedded Rust logic
1290// here — this module remains a generic job dispatcher.
1291
1292#[cfg(test)]
1293mod tests {
1294    use super::*;
1295    use crate::backends::test_helpers::NoopBackend;
1296    use crate::backends::{
1297        Conversation, ExternalTask, MergeState, PullRequestCompletion, Status, TaskReader,
1298        TaskWriter, Tracker,
1299    };
1300    use crate::store::{DepSource, NewDependency};
1301    use async_trait::async_trait;
1302    use std::env;
1303    use std::fs;
1304    use std::sync::Mutex;
1305    use tempfile::tempdir;
1306
1307    fn write_config(dir: &Path, content: &str) -> PathBuf {
1308        let path = dir.join(".orch.yml");
1309        fs::write(&path, content).unwrap();
1310        path
1311    }
1312
1313    #[tokio::test]
1314    async fn run_bash_timeout_kills_the_child() {
1315        let tmp = tempdir().unwrap();
1316        let pid_file = tmp.path().join("pid");
1317        let cmd = format!("sleep 60 & echo $! > {}; wait", pid_file.display());
1318
1319        let out = run_bash(&cmd, Path::new("."), Duration::from_secs(1)).await;
1320        assert!(out.is_err(), "expected a timeout");
1321
1322        let pid: i32 = fs::read_to_string(&pid_file)
1323            .unwrap()
1324            .trim()
1325            .parse()
1326            .unwrap();
1327        let mut gone = false;
1328        for _ in 0..20 {
1329            if cmd_mod::raw_kill(pid, 0) != 0 {
1330                gone = true;
1331                break;
1332            }
1333            time::sleep(Duration::from_millis(100)).await;
1334        }
1335        assert!(gone, "grandchild {pid} still running after timeout");
1336    }
1337
1338    fn bash_job(id: &str, command: String, dir: Option<&str>) -> Job {
1339        Job {
1340            id: id.to_string(),
1341            r#type: "bash".to_string(),
1342            schedule: "* * * * *".to_string(),
1343            task: None,
1344            command: Some(command),
1345            dir: dir.map(str::to_string),
1346            enabled: true,
1347            external: false,
1348            notify: false,
1349            notify_target: None,
1350            sandbox: None,
1351            prompt_file: None,
1352        }
1353    }
1354
1355    async fn execute_bash(job: &Job, base_dir: &Path) -> JobState {
1356        let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
1357        let mut state = JobState::new("owner/repo", &job.id);
1358        execute_job(
1359            job,
1360            &mut state,
1361            &backend,
1362            None,
1363            "owner/repo",
1364            None,
1365            base_dir,
1366        )
1367        .await;
1368        state
1369    }
1370
1371    fn read_recorded_cwd(path: &Path) -> PathBuf {
1372        let raw = fs::read_to_string(path).expect("bash command should have written cwd.txt");
1373        fs::canonicalize(raw.trim()).unwrap()
1374    }
1375
1376    #[tokio::test]
1377    async fn bash_job_runs_in_project_dir_not_process_cwd() {
1378        let project = tempdir().unwrap();
1379        let process_cwd = fs::canonicalize(env::current_dir().unwrap()).unwrap();
1380        let project_dir = fs::canonicalize(project.path()).unwrap();
1381        assert_ne!(
1382            process_cwd, project_dir,
1383            "setup: process cwd must differ from the project dir"
1384        );
1385
1386        let out_default = project.path().join("cwd-default.txt");
1387        let job = bash_job(
1388            "default-dir",
1389            format!("pwd > '{}'", out_default.display()),
1390            None,
1391        );
1392        let state = execute_bash(&job, project.path()).await;
1393        assert_eq!(
1394            state.last_task_status.as_deref(),
1395            Some("done"),
1396            "bash job with no dir should succeed in the project dir"
1397        );
1398        assert_eq!(
1399            read_recorded_cwd(&out_default),
1400            project_dir,
1401            "bash job with no dir must run in the project dir"
1402        );
1403
1404        let scripts = project.path().join("scripts");
1405        fs::create_dir(&scripts).unwrap();
1406        let out_relative = project.path().join("cwd-relative.txt");
1407        let job = bash_job(
1408            "relative-dir",
1409            format!("pwd > '{}'", out_relative.display()),
1410            Some("scripts"),
1411        );
1412        let state = execute_bash(&job, project.path()).await;
1413        assert_eq!(
1414            state.last_task_status.as_deref(),
1415            Some("done"),
1416            "bash job should succeed when relative dir resolves to an existing path"
1417        );
1418        assert_eq!(
1419            read_recorded_cwd(&out_relative),
1420            fs::canonicalize(&scripts).unwrap(),
1421            "relative dir must resolve against the project dir"
1422        );
1423
1424        let abs = tempdir().unwrap();
1425        let out_abs = project.path().join("cwd-absolute.txt");
1426        let job = bash_job(
1427            "absolute-dir",
1428            format!("pwd > '{}'", out_abs.display()),
1429            Some(abs.path().to_str().unwrap()),
1430        );
1431        let state = execute_bash(&job, project.path()).await;
1432        assert_eq!(
1433            state.last_task_status.as_deref(),
1434            Some("done"),
1435            "bash job should succeed when dir is an absolute path"
1436        );
1437        assert_eq!(
1438            read_recorded_cwd(&out_abs),
1439            fs::canonicalize(abs.path()).unwrap(),
1440            "absolute dir must be used as-is"
1441        );
1442    }
1443
1444    async fn tick_with_store(path: &Path, store: &Arc<TaskStore>, repo: &str) {
1445        let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
1446        tick(path, &backend, Some(store), repo, None).await.unwrap();
1447    }
1448
1449    async fn wait_for_job_status(
1450        store: &TaskStore,
1451        repo: &str,
1452        job_id: &str,
1453        want: &str,
1454    ) -> Option<String> {
1455        for _ in 0..300 {
1456            let status = store
1457                .get_job_state(repo, job_id)
1458                .await
1459                .unwrap()
1460                .and_then(|s| s.last_task_status);
1461            if status.as_deref() == Some(want) {
1462                return status;
1463            }
1464            time::sleep(Duration::from_millis(50)).await;
1465        }
1466        store
1467            .get_job_state(repo, job_id)
1468            .await
1469            .unwrap()
1470            .and_then(|s| s.last_task_status)
1471    }
1472
1473    #[tokio::test]
1474    async fn bash_job_tick_returns_before_the_command_ends() {
1475        let tmp = tempdir().unwrap();
1476        let cfg = write_config(
1477            tmp.path(),
1478            r#"
1479jobs:
1480  - id: slow
1481    type: bash
1482    schedule: "* * * * *"
1483    command: "sleep 5"
1484"#,
1485        );
1486        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1487        let repo = "tick-returns/repo";
1488        let started = time::Instant::now();
1489        tick_with_store(&cfg, &store, repo).await;
1490        assert!(
1491            started.elapsed() < Duration::from_secs(2),
1492            "tick waited for the bash command, elapsed {:?}",
1493            started.elapsed()
1494        );
1495        let early = store.get_job_state(repo, "slow").await.unwrap().unwrap();
1496        assert!(
1497            early.last_run.is_some(),
1498            "last_run must be written before the command ends"
1499        );
1500        assert_ne!(
1501            early.last_task_status.as_deref(),
1502            Some("done"),
1503            "job state must not already be done when tick returns"
1504        );
1505        let status = wait_for_job_status(&store, repo, "slow", "done").await;
1506        assert_eq!(status.as_deref(), Some("done"));
1507    }
1508
1509    #[tokio::test]
1510    async fn bash_job_tick_starts_only_one_run() {
1511        let tmp = tempdir().unwrap();
1512        let log = tmp.path().join("runs.log");
1513        let go = tmp.path().join("go");
1514        let cfg = write_config(
1515            tmp.path(),
1516            &format!(
1517                r#"
1518jobs:
1519  - id: once
1520    type: bash
1521    schedule: "* * * * *"
1522    command: "echo x >> '{log}'; while [ ! -f '{go}' ]; do sleep 0.05; done"
1523"#,
1524                log = log.display(),
1525                go = go.display(),
1526            ),
1527        );
1528        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1529        let repo = "tick-one-run/repo";
1530        tick_with_store(&cfg, &store, repo).await;
1531
1532        for _ in 0..100 {
1533            if log.exists() {
1534                break;
1535            }
1536            time::sleep(Duration::from_millis(20)).await;
1537        }
1538        assert!(log.exists(), "first bash job never started");
1539
1540        let mut state = store
1541            .get_job_state(repo, "once")
1542            .await
1543            .unwrap()
1544            .expect("last_run written before spawn");
1545        let past = chrono::Utc::now() - chrono::Duration::minutes(2);
1546        state.last_run = Some(past.format("%Y-%m-%dT%H:%M:%SZ").to_string());
1547        store.upsert_job_state(&state).await.unwrap();
1548
1549        tick_with_store(&cfg, &store, repo).await;
1550        fs::write(&go, "").unwrap();
1551        let status = wait_for_job_status(&store, repo, "once", "done").await;
1552        assert_eq!(status.as_deref(), Some("done"));
1553        let body = fs::read_to_string(&log).unwrap();
1554        assert_eq!(
1555            body.matches('x').count(),
1556            1,
1557            "started a second copy: {body:?}"
1558        );
1559    }
1560
1561    #[test]
1562    fn load_jobs_reads_prompt_from_file() {
1563        let tmp = tempdir().unwrap();
1564        fs::create_dir(tmp.path().join("prompts")).unwrap();
1565        fs::write(tmp.path().join("prompts/hello.md"), "hello from file").unwrap();
1566        let cfg = write_config(
1567            tmp.path(),
1568            r#"
1569jobs:
1570  - id: with-prompt
1571    schedule: "0 9 * * *"
1572    task:
1573      title: "Daily"
1574      prompt: prompts/hello.md
1575"#,
1576        );
1577
1578        let jobs = load_jobs(&cfg).unwrap();
1579        assert_eq!(jobs.len(), 1);
1580        let body = resolve_template_body(jobs[0].task.as_ref().unwrap(), tmp.path()).unwrap();
1581        assert_eq!(body, "hello from file");
1582    }
1583
1584    #[test]
1585    fn load_jobs_rejects_both_body_and_prompt() {
1586        let tmp = tempdir().unwrap();
1587        fs::write(tmp.path().join("p.md"), "x").unwrap();
1588        let cfg = write_config(
1589            tmp.path(),
1590            r#"
1591jobs:
1592  - id: conflict
1593    schedule: "0 9 * * *"
1594    task:
1595      title: "x"
1596      body: "inline"
1597      prompt: p.md
1598"#,
1599        );
1600
1601        let err = load_jobs(&cfg).unwrap_err().to_string();
1602        assert!(err.contains("not both"), "unexpected error: {err}");
1603    }
1604
1605    #[test]
1606    fn load_jobs_rejects_missing_prompt_file() {
1607        let tmp = tempdir().unwrap();
1608        let cfg = write_config(
1609            tmp.path(),
1610            r#"
1611jobs:
1612  - id: missing
1613    schedule: "0 9 * * *"
1614    task:
1615      title: "x"
1616      prompt: does-not-exist.md
1617"#,
1618        );
1619
1620        let err = load_jobs(&cfg).unwrap_err().to_string();
1621        assert!(
1622            err.contains("prompt file not found"),
1623            "unexpected error: {err}"
1624        );
1625    }
1626
1627    #[test]
1628    fn resolve_template_body_falls_back_to_inline_body() {
1629        let tmp = tempdir().unwrap();
1630        let template = TaskTemplate {
1631            title: "t".to_string(),
1632            body: "inline body".to_string(),
1633            prompt: None,
1634            labels: vec![],
1635            agent: None,
1636        };
1637        assert_eq!(
1638            resolve_template_body(&template, tmp.path()).unwrap(),
1639            "inline body"
1640        );
1641    }
1642
1643    fn write_prompt_job(dir: &Path, name: &str, content: &str) {
1644        let jobs_dir = dir.join("prompts").join("jobs");
1645        fs::create_dir_all(&jobs_dir).unwrap();
1646        fs::write(jobs_dir.join(name), content).unwrap();
1647    }
1648
1649    #[test]
1650    fn scan_prompt_jobs_picks_up_frontmatter_files() {
1651        let tmp = tempdir().unwrap();
1652        write_prompt_job(
1653            tmp.path(),
1654            "morning.md",
1655            "---\nid: morning\nschedule: '0 9 * * *'\ntitle: Morning\nlabels: [daily]\nagent: claude\n---\n\nDo morning stuff.\n",
1656        );
1657        let jobs = scan_prompt_jobs(tmp.path()).unwrap();
1658        assert_eq!(jobs.len(), 1);
1659        assert_eq!(jobs[0].id, "morning");
1660        assert_eq!(jobs[0].schedule, "0 9 * * *");
1661        let task = jobs[0].task.as_ref().unwrap();
1662        assert_eq!(task.title, "Morning");
1663        assert_eq!(task.body, "Do morning stuff.\n");
1664        assert_eq!(task.labels, vec!["daily".to_string()]);
1665        assert_eq!(task.agent.as_deref(), Some("claude"));
1666    }
1667
1668    #[test]
1669    fn load_jobs_merges_inline_and_scanned() {
1670        let tmp = tempdir().unwrap();
1671        write_prompt_job(
1672            tmp.path(),
1673            "scanned.md",
1674            "---\nid: scanned\nschedule: '0 9 * * *'\ntitle: Scanned\n---\n\nbody\n",
1675        );
1676        let cfg = write_config(
1677            tmp.path(),
1678            r#"
1679jobs:
1680  - id: inline
1681    schedule: "0 10 * * *"
1682    task:
1683      title: "Inline"
1684      body: "x"
1685"#,
1686        );
1687        let jobs = load_jobs(&cfg).unwrap();
1688        let ids: Vec<&str> = jobs.iter().map(|j| j.id.as_str()).collect();
1689        assert!(ids.contains(&"inline"));
1690        assert!(ids.contains(&"scanned"));
1691        assert_eq!(jobs.len(), 2);
1692    }
1693
1694    #[test]
1695    fn load_jobs_rejects_duplicate_id_across_sources() {
1696        let tmp = tempdir().unwrap();
1697        write_prompt_job(
1698            tmp.path(),
1699            "dup.md",
1700            "---\nid: dup\nschedule: '0 9 * * *'\ntitle: Dup\n---\n\nbody\n",
1701        );
1702        let cfg = write_config(
1703            tmp.path(),
1704            r#"
1705jobs:
1706  - id: dup
1707    schedule: "0 10 * * *"
1708    task:
1709      title: "Dup inline"
1710      body: "x"
1711"#,
1712        );
1713        let err = load_jobs(&cfg).unwrap_err().to_string();
1714        assert!(err.contains("duplicate job id"), "unexpected error: {err}");
1715    }
1716
1717    #[tokio::test]
1718    async fn a_job_run_by_hand_links_its_task_so_sandbox_false_applies() {
1719        let dir = tempfile::tempdir().unwrap();
1720        let jobs_dir = dir.path().join("prompts/jobs");
1721        fs::create_dir_all(&jobs_dir).unwrap();
1722        fs::write(
1723            jobs_dir.join("mail.md"),
1724            "---\nid: mail\nschedule: '0 8 * * *'\ntitle: Mail\nsandbox: false\n---\n\nbody\n",
1725        )
1726        .unwrap();
1727        let job = load_jobs(&dir.path().join(".orch.yml")).unwrap().remove(0);
1728        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1729        let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
1730        let mut state = JobState::new("owner/repo", "mail");
1731
1732        execute_and_save(
1733            &job,
1734            &mut state,
1735            &backend,
1736            Some(&store),
1737            "owner/repo",
1738            None,
1739            dir.path(),
1740        )
1741        .await;
1742
1743        let task = state
1744            .active_task_id
1745            .clone()
1746            .expect("the run creates a task");
1747        let saved = store
1748            .get_job_state("owner/repo", "mail")
1749            .await
1750            .unwrap()
1751            .unwrap();
1752        assert_eq!(saved.active_task_id.as_deref(), Some(task.as_str()));
1753        assert!(sandbox_off_for(&store, "owner/repo", dir.path(), &task).await);
1754    }
1755
1756    #[tokio::test]
1757    async fn a_job_with_sandbox_false_turns_it_off_for_its_task_only() {
1758        let dir = tempfile::tempdir().unwrap();
1759        let jobs_dir = dir.path().join("prompts/jobs");
1760        fs::create_dir_all(&jobs_dir).unwrap();
1761        fs::write(
1762            jobs_dir.join("mail.md"),
1763            "---\nid: mail\nschedule: '0 8 * * *'\ntitle: Mail\nsandbox: false\n---\n\nbody\n",
1764        )
1765        .unwrap();
1766        fs::write(
1767            jobs_dir.join("other.md"),
1768            "---\nid: other\nschedule: '0 8 * * *'\ntitle: Other\n---\n\nbody\n",
1769        )
1770        .unwrap();
1771        let store = TaskStore::open_memory().await.unwrap();
1772        for (job, task) in [("mail", "internal:1"), ("other", "internal:2")] {
1773            let mut state = JobState::new("owner/repo", job);
1774            state.active_task_id = Some(task.to_string());
1775            store.upsert_job_state(&state).await.unwrap();
1776        }
1777
1778        assert!(sandbox_off_for(&store, "owner/repo", dir.path(), "internal:1").await);
1779        assert!(!sandbox_off_for(&store, "owner/repo", dir.path(), "internal:2").await);
1780        assert!(!sandbox_off_for(&store, "owner/repo", dir.path(), "internal:3").await);
1781    }
1782
1783    #[test]
1784    fn scan_prompt_jobs_ignores_files_without_frontmatter() {
1785        let tmp = tempdir().unwrap();
1786        write_prompt_job(
1787            tmp.path(),
1788            "plain.md",
1789            "just a prompt body, no frontmatter\n",
1790        );
1791        let jobs = scan_prompt_jobs(tmp.path()).unwrap();
1792        assert_eq!(jobs.len(), 0);
1793    }
1794
1795    #[test]
1796    fn load_jobs_works_without_config_file_when_directory_present() {
1797        let tmp = tempdir().unwrap();
1798        write_prompt_job(
1799            tmp.path(),
1800            "solo.md",
1801            "---\nid: solo\nschedule: '0 9 * * *'\ntitle: Solo\n---\n\nbody\n",
1802        );
1803        let missing_cfg = tmp.path().join(".orch.yml");
1804        let jobs = load_jobs(&missing_cfg).unwrap();
1805        assert_eq!(jobs.len(), 1);
1806        assert_eq!(jobs[0].id, "solo");
1807    }
1808
1809    // ──── Issue #3193: frontmatter `enabled: false` must be respected ────────
1810
1811    #[test]
1812    fn scan_prompt_jobs_respects_enabled_false() {
1813        let tmp = tempdir().unwrap();
1814        write_prompt_job(
1815            tmp.path(),
1816            "disabled.md",
1817            "---\nid: disabled\nschedule: '0 9 * * *'\ntitle: Disabled\nenabled: false\n---\n\nbody\n",
1818        );
1819        let jobs = scan_prompt_jobs(tmp.path()).unwrap();
1820        assert_eq!(jobs.len(), 1);
1821        assert!(!jobs[0].enabled, "job should be disabled via frontmatter");
1822    }
1823
1824    #[test]
1825    fn scan_prompt_jobs_sets_prompt_file() {
1826        let tmp = tempdir().unwrap();
1827        write_prompt_job(
1828            tmp.path(),
1829            "morning.md",
1830            "---\nid: morning\nschedule: '0 9 * * *'\ntitle: Morning\n---\n\nbody\n",
1831        );
1832        let jobs = scan_prompt_jobs(tmp.path()).unwrap();
1833        assert_eq!(jobs.len(), 1);
1834        assert!(
1835            jobs[0].prompt_file.is_some(),
1836            "prompt_file should be set for frontmatter jobs"
1837        );
1838    }
1839
1840    #[test]
1841    fn save_jobs_does_not_persist_prompt_based_jobs() {
1842        let tmp = tempdir().unwrap();
1843        // A prompt-based job
1844        write_prompt_job(
1845            tmp.path(),
1846            "prompt.md",
1847            "---\nid: from-prompt\nschedule: '0 9 * * *'\ntitle: Prompt Job\n---\n\nbody\n",
1848        );
1849        // An inline job in .orch.yml
1850        let cfg = write_config(
1851            tmp.path(),
1852            "jobs:\n  - id: inline\n    schedule: \"0 10 * * *\"\n    task:\n      title: Inline\n      body: x\n",
1853        );
1854        let jobs = load_jobs(&cfg).unwrap();
1855        assert_eq!(jobs.len(), 2);
1856
1857        // save_jobs should only write the inline job, not the prompt-based one
1858        save_jobs(&cfg, &jobs).unwrap();
1859
1860        let saved = load_jobs(&cfg).unwrap();
1861        assert_eq!(saved.len(), 2, "both jobs should still be loadable");
1862        let ids: Vec<&str> = saved.iter().map(|j| j.id.as_str()).collect();
1863        assert!(ids.contains(&"inline"));
1864        assert!(ids.contains(&"from-prompt"));
1865    }
1866
1867    #[test]
1868    fn rewrite_frontmatter_enabled_replaces_existing_value() {
1869        let input = "---\nid: foo\nschedule: daily\nenabled: true\ntitle: Foo\n---\n\nbody\n";
1870        let out = rewrite_frontmatter_enabled(input, "false");
1871        assert!(
1872            out.contains("enabled: false"),
1873            "should replace enabled: true"
1874        );
1875        assert!(!out.contains("enabled: true"), "old value must be gone");
1876        assert!(out.contains("body"), "body must be preserved");
1877    }
1878
1879    #[test]
1880    fn rewrite_frontmatter_enabled_inserts_when_absent() {
1881        let input = "---\nid: foo\nschedule: daily\ntitle: Foo\n---\n\nbody\n";
1882        let out = rewrite_frontmatter_enabled(input, "false");
1883        assert!(
1884            out.contains("enabled: false"),
1885            "should insert enabled: false"
1886        );
1887        assert!(out.contains("body"), "body must be preserved");
1888    }
1889
1890    #[test]
1891    fn set_frontmatter_enabled_writes_file() {
1892        let tmp = tempdir().unwrap();
1893        let path = tmp.path().join("job.md");
1894        fs::write(
1895            &path,
1896            "---\nid: foo\nschedule: daily\ntitle: Foo\nenabled: true\n---\n\nbody\n",
1897        )
1898        .unwrap();
1899        set_frontmatter_enabled(&path, false).unwrap();
1900        let content = fs::read_to_string(&path).unwrap();
1901        assert!(content.contains("enabled: false"));
1902        assert!(!content.contains("enabled: true"));
1903    }
1904
1905    #[tokio::test]
1906    async fn tick_keeps_active_task_id_when_the_store_lookup_fails() {
1907        let tmp = tempdir().unwrap();
1908        let cfg = write_config(
1909            tmp.path(),
1910            r#"
1911jobs:
1912  - id: nightly
1913    type: bash
1914    schedule: "* * * * *"
1915    command: "true"
1916"#,
1917        );
1918        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1919        let mut state = JobState::new("owner/repo", "nightly");
1920        state.active_task_id = Some("internal:1".to_string());
1921        store.upsert_job_state(&state).await.unwrap();
1922        // Job state still reads, the task lookup now fails with a query error
1923        sqlx::query("DROP TABLE tasks")
1924            .execute(store.pool())
1925            .await
1926            .unwrap();
1927
1928        let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
1929        tick(&cfg, &backend, Some(&store), "owner/repo", None)
1930            .await
1931            .unwrap();
1932
1933        let after = store
1934            .get_job_state("owner/repo", "nightly")
1935            .await
1936            .unwrap()
1937            .unwrap();
1938        assert_eq!(after.active_task_id.as_deref(), Some("internal:1"));
1939        assert_eq!(after.last_run, None, "the job must not run again");
1940    }
1941
1942    #[tokio::test]
1943    async fn tick_does_not_create_another_task_when_job_state_write_fails() {
1944        let tmp = tempdir().unwrap();
1945        let cfg = write_config(
1946            tmp.path(),
1947            r#"
1948jobs:
1949  - id: mail
1950    schedule: "* * * * *"
1951    sandbox: false
1952    task:
1953      title: Mail
1954      body: body
1955"#,
1956        );
1957        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1958        let repo = "issue-4228/lost-persist";
1959        store.fail_next_job_state_writes(8);
1960
1961        tick_with_store(&cfg, &store, repo).await;
1962
1963        let tasks = store.list_all_internal(repo).await.unwrap();
1964        assert_eq!(tasks.len(), 1, "first tick should create one task");
1965        let task_id = format!("internal:{}", tasks[0].id);
1966        let saved = store
1967            .get_job_state(repo, "mail")
1968            .await
1969            .unwrap()
1970            .expect("last_run written before execute");
1971        assert_eq!(
1972            saved.active_task_id, None,
1973            "the created id must not be in SQLite after the upsert failed"
1974        );
1975        assert!(
1976            sandbox_off_for(&store, repo, tmp.path(), &task_id).await,
1977            "sandbox:false must still match the created task"
1978        );
1979
1980        let mut state = saved;
1981        let past = chrono::Utc::now() - chrono::Duration::minutes(2);
1982        state.last_run = Some(past.format("%Y-%m-%dT%H:%M:%SZ").to_string());
1983        store.upsert_job_state(&state).await.unwrap();
1984
1985        tick_with_store(&cfg, &store, repo).await;
1986
1987        let tasks = store.list_all_internal(repo).await.unwrap();
1988        assert_eq!(
1989            tasks.len(),
1990            1,
1991            "next period must not create another task while persist is outstanding"
1992        );
1993        assert!(sandbox_off_for(&store, repo, tmp.path(), &task_id).await);
1994    }
1995
1996    /// Backend whose task has fixed labels, recording status moves and creates
1997    #[derive(Default)]
1998    struct RecordingBackend {
1999        labels: Vec<String>,
2000        pull: Option<PullRequestCompletion>,
2001        moves: Mutex<Vec<(String, Status)>>,
2002        creates: Mutex<u32>,
2003    }
2004
2005    #[async_trait]
2006    impl TaskReader for RecordingBackend {
2007        async fn get_task(&self, id: &ExternalId) -> anyhow::Result<ExternalTask> {
2008            let mut task = NoopBackend.get_task(id).await?;
2009            task.labels.clone_from(&self.labels);
2010            Ok(task)
2011        }
2012
2013        async fn list_by_status(&self, _s: Status) -> anyhow::Result<Vec<ExternalTask>> {
2014            Ok(vec![])
2015        }
2016    }
2017
2018    #[async_trait]
2019    impl TaskWriter for RecordingBackend {
2020        async fn create_task(
2021            &self,
2022            _t: &str,
2023            _b: &str,
2024            _l: &[String],
2025        ) -> anyhow::Result<ExternalId> {
2026            *self.creates.lock().unwrap() += 1;
2027            Ok(ExternalId("99".into()))
2028        }
2029
2030        async fn set_labels(&self, _id: &ExternalId, _l: &[String]) -> anyhow::Result<()> {
2031            Ok(())
2032        }
2033
2034        async fn remove_label(&self, _id: &ExternalId, _l: &str) -> anyhow::Result<()> {
2035            Ok(())
2036        }
2037
2038        async fn get_sub_issues(&self, _id: &ExternalId) -> anyhow::Result<Vec<ExternalId>> {
2039            Ok(vec![])
2040        }
2041
2042        async fn update_status(&self, id: &ExternalId, status: Status) -> anyhow::Result<()> {
2043            self.moves.lock().unwrap().push((id.0.clone(), status));
2044            Ok(())
2045        }
2046    }
2047
2048    #[async_trait]
2049    impl Conversation for RecordingBackend {
2050        async fn post_comment(&self, _id: &ExternalId, _b: &str) -> anyhow::Result<()> {
2051            Ok(())
2052        }
2053    }
2054
2055    #[async_trait]
2056    impl MergeState for RecordingBackend {
2057        async fn pull_request_completion(
2058            &self,
2059            _repo: &str,
2060            _pr_number: i64,
2061        ) -> anyhow::Result<Option<PullRequestCompletion>> {
2062            Ok(self.pull.clone())
2063        }
2064    }
2065
2066    #[async_trait]
2067    impl Tracker for RecordingBackend {
2068        fn name(&self) -> &'static str {
2069            "recording"
2070        }
2071
2072        async fn health_check(&self) -> anyhow::Result<()> {
2073            Ok(())
2074        }
2075    }
2076
2077    const TASK_JOB: &str = r#"
2078jobs:
2079  - id: weekly
2080    schedule: "* * * * *"
2081    task:
2082      title: Weekly
2083      body: body
2084"#;
2085
2086    const EXTERNAL_TASK_JOB: &str = r#"
2087jobs:
2088  - id: weekly
2089    schedule: "* * * * *"
2090    external: true
2091    task:
2092      title: Weekly
2093      body: body
2094"#;
2095
2096    /// An internal task of the job in `status`, recorded as its active task
2097    async fn job_task(store: &TaskStore, repo: &str, status: TaskStatus) -> i64 {
2098        let id = store
2099            .create_internal(repo, "Weekly", "body", "cron", "weekly", None)
2100            .await
2101            .unwrap();
2102        store.update_status(id, status).await.unwrap();
2103        let mut state = JobState::new(repo, "weekly");
2104        state.active_task_id = Some(format!("internal:{id}"));
2105        store.upsert_job_state(&state).await.unwrap();
2106        id
2107    }
2108
2109    async fn job_state(store: &TaskStore, repo: &str) -> JobState {
2110        store.get_job_state(repo, "weekly").await.unwrap().unwrap()
2111    }
2112
2113    #[tokio::test]
2114    async fn due_job_unblocks_its_blocked_internal_task() {
2115        let tmp = tempdir().unwrap();
2116        let cfg = write_config(tmp.path(), TASK_JOB);
2117        let store = Arc::new(TaskStore::open_memory().await.unwrap());
2118        let repo = "owner/repo";
2119        let id = job_task(&store, repo, TaskStatus::Blocked).await;
2120        store.increment(id, "route_attempts").await.unwrap();
2121        store.increment(id, "attempts").await.unwrap();
2122
2123        tick_with_store(&cfg, &store, repo).await;
2124
2125        let task = store.get(id).await.unwrap();
2126        assert_eq!(task.status, TaskStatus::New);
2127        assert_eq!(task.route_attempts, 0);
2128        assert_eq!(task.attempts, 0);
2129        let state = job_state(&store, repo).await;
2130        assert_eq!(state.active_task_id, Some(format!("internal:{id}")));
2131        assert!(state.last_run.is_some());
2132        assert_eq!(state.last_task_status.as_deref(), Some("new"));
2133        assert_eq!(store.list_all_internal(repo).await.unwrap().len(), 1);
2134    }
2135
2136    #[tokio::test]
2137    async fn due_job_moves_its_blocked_external_task_to_new() {
2138        let tmp = tempdir().unwrap();
2139        let cfg = write_config(tmp.path(), EXTERNAL_TASK_JOB);
2140        let store = Arc::new(TaskStore::open_memory().await.unwrap());
2141        let repo = "owner/repo";
2142        let mut state = JobState::new(repo, "weekly");
2143        state.active_task_id = Some("42".to_string());
2144        store.upsert_job_state(&state).await.unwrap();
2145        let recording = Arc::new(RecordingBackend {
2146            labels: vec!["status:blocked".to_string()],
2147            ..RecordingBackend::default()
2148        });
2149        let backend: Arc<dyn ExternalBackend> = Arc::clone(&recording) as _;
2150
2151        tick(&cfg, &backend, Some(&store), repo, None)
2152            .await
2153            .unwrap();
2154
2155        assert_eq!(
2156            *recording.moves.lock().unwrap(),
2157            vec![("42".to_string(), Status::New)]
2158        );
2159        assert_eq!(*recording.creates.lock().unwrap(), 0);
2160        let state = job_state(&store, repo).await;
2161        assert_eq!(state.active_task_id.as_deref(), Some("42"));
2162        assert!(state.last_run.is_some());
2163    }
2164
2165    #[tokio::test]
2166    async fn due_job_creates_a_task_when_the_blocked_task_pr_was_closed_unmerged() {
2167        let tmp = tempdir().unwrap();
2168        let cfg = write_config(tmp.path(), TASK_JOB);
2169        let store = Arc::new(TaskStore::open_memory().await.unwrap());
2170        let repo = "owner/repo";
2171        let id = job_task(&store, repo, TaskStatus::Blocked).await;
2172        store
2173            .set_fields_silent(id, &[("pr_number", serde_json::json!(7))])
2174            .await
2175            .unwrap();
2176        let backend: Arc<dyn ExternalBackend> = Arc::new(RecordingBackend {
2177            pull: Some(PullRequestCompletion {
2178                merged: false,
2179                base_ref: "main".into(),
2180                default_branch: "main".into(),
2181                approved: false,
2182                closed: true,
2183            }),
2184            ..RecordingBackend::default()
2185        });
2186
2187        tick(&cfg, &backend, Some(&store), repo, None)
2188            .await
2189            .unwrap();
2190
2191        assert_eq!(store.get(id).await.unwrap().status, TaskStatus::Blocked);
2192        let tasks = store.list_all_internal(repo).await.unwrap();
2193        assert_eq!(tasks.len(), 2);
2194        let created = tasks.iter().find(|t| t.id != id).unwrap();
2195        assert_eq!(
2196            job_state(&store, repo).await.active_task_id,
2197            Some(format!("internal:{}", created.id))
2198        );
2199    }
2200
2201    #[tokio::test]
2202    async fn due_job_leaves_a_blocked_task_with_an_open_dependency_waiting() {
2203        let tmp = tempdir().unwrap();
2204        let cfg = write_config(tmp.path(), TASK_JOB);
2205        let store = Arc::new(TaskStore::open_memory().await.unwrap());
2206        let repo = "owner/repo";
2207        let id = job_task(&store, repo, TaskStatus::Blocked).await;
2208        store
2209            .replace_dependencies(
2210                id,
2211                &[NewDependency {
2212                    repo: repo.to_string(),
2213                    number: 9,
2214                    source: DepSource::Cli,
2215                }],
2216            )
2217            .await
2218            .unwrap();
2219
2220        tick_with_store(&cfg, &store, repo).await;
2221
2222        assert_eq!(store.get(id).await.unwrap().status, TaskStatus::Waiting);
2223        assert_eq!(store.list_all_internal(repo).await.unwrap().len(), 1);
2224        let state = job_state(&store, repo).await;
2225        assert_eq!(state.active_task_id, Some(format!("internal:{id}")));
2226        assert_eq!(state.last_task_status.as_deref(), Some("waiting"));
2227    }
2228
2229    #[tokio::test]
2230    async fn job_not_due_leaves_its_blocked_task_alone() {
2231        let tmp = tempdir().unwrap();
2232        let cfg = write_config(tmp.path(), TASK_JOB);
2233        let store = Arc::new(TaskStore::open_memory().await.unwrap());
2234        let repo = "owner/repo";
2235        let id = job_task(&store, repo, TaskStatus::Blocked).await;
2236        store.increment(id, "route_attempts").await.unwrap();
2237        let mut state = job_state(&store, repo).await;
2238        let ahead = chrono::Utc::now() + chrono::Duration::minutes(1);
2239        let last_run = ahead.format("%Y-%m-%dT%H:%M:%SZ").to_string();
2240        state.last_run = Some(last_run.clone());
2241        store.upsert_job_state(&state).await.unwrap();
2242
2243        tick_with_store(&cfg, &store, repo).await;
2244
2245        let task = store.get(id).await.unwrap();
2246        assert_eq!(task.status, TaskStatus::Blocked);
2247        assert_eq!(task.route_attempts, 1);
2248        assert_eq!(job_state(&store, repo).await.last_run, Some(last_run));
2249        assert_eq!(store.list_all_internal(repo).await.unwrap().len(), 1);
2250    }
2251
2252    #[tokio::test]
2253    async fn due_job_creates_a_task_after_its_task_is_done() {
2254        let tmp = tempdir().unwrap();
2255        let cfg = write_config(tmp.path(), TASK_JOB);
2256        let store = Arc::new(TaskStore::open_memory().await.unwrap());
2257        let repo = "owner/repo";
2258        let id = job_task(&store, repo, TaskStatus::Done).await;
2259
2260        tick_with_store(&cfg, &store, repo).await;
2261
2262        let tasks = store.list_all_internal(repo).await.unwrap();
2263        assert_eq!(tasks.len(), 2);
2264        let created = tasks.iter().find(|t| t.id != id).unwrap();
2265        assert_eq!(created.status, TaskStatus::New);
2266        assert_eq!(
2267            job_state(&store, repo).await.active_task_id,
2268            Some(format!("internal:{}", created.id))
2269        );
2270    }
2271
2272    #[test]
2273    fn not_found_error_ignores_a_404_inside_the_issue_number() {
2274        let transient = anyhow::anyhow!(
2275            "GitHub API GET https://api.github.com/repos/o/r/issues/1404 failed (500 Internal Server Error): boom"
2276        );
2277        assert!(!is_not_found_error(&transient));
2278        let missing = anyhow::anyhow!(
2279            "GitHub API GET https://api.github.com/repos/o/r/issues/1404 failed (404 Not Found): Not Found"
2280        );
2281        assert!(is_not_found_error(&missing));
2282    }
2283}