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