1pub 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::github::http::has_status;
24use crate::store::TaskStore;
25use crate::store::{JobState, TaskStatus};
26use crate::sys::cmd as cmd_mod;
27use crate::sys::home;
28use ::cron::Schedule;
29use anyhow::Context;
30use dashmap::DashSet;
31use serde::{Deserialize, Serialize};
32use std::collections::HashSet;
33use std::fs;
34use std::path::{Path, PathBuf};
35use std::process::{Output, Stdio};
36use std::result;
37use std::str::FromStr;
38use std::sync::{Arc, LazyLock};
39use std::time::Duration;
40use tokio::process::Command;
41use tokio::task;
42use tokio::time;
43
44#[derive(Debug, Clone, Serialize, Deserialize)]
50pub struct Job {
51 pub id: String,
52 #[serde(default = "default_job_type")]
53 pub r#type: String,
54 pub schedule: String,
55 #[serde(default)]
56 pub task: Option<TaskTemplate>,
57 #[serde(default)]
58 pub command: Option<String>,
59 #[serde(default)]
60 pub dir: Option<String>,
61 #[serde(default = "default_enabled")]
62 pub enabled: bool,
63 #[serde(default = "default_external")]
64 pub external: bool, #[serde(default)]
68 pub notify: bool,
69 #[serde(default)]
72 pub notify_target: Option<String>,
73 #[serde(skip)]
79 pub prompt_file: Option<PathBuf>,
80}
81
82#[derive(Debug, Clone, Serialize, Deserialize)]
84pub struct TaskTemplate {
85 pub title: String,
86 #[serde(default)]
87 pub body: String,
88 #[serde(default, skip_serializing_if = "Option::is_none")]
92 pub prompt: Option<String>,
93 #[serde(default)]
94 pub labels: Vec<String>,
95 #[serde(default)]
96 pub agent: Option<String>,
97}
98
99pub fn resolve_template_body(template: &TaskTemplate, base_dir: &Path) -> anyhow::Result<String> {
104 match template.prompt.as_deref() {
105 Some(rel) => {
106 let path = Path::new(rel);
107 let full = if path.is_absolute() {
108 path.to_path_buf()
109 } else {
110 base_dir.join(path)
111 };
112 fs::read_to_string(&full)
113 .with_context(|| format!("reading prompt file {}", full.display()))
114 }
115 None => Ok(template.body.clone()),
116 }
117}
118
119fn resolve_job_dir(job: &Job, base_dir: &Path) -> PathBuf {
121 match job.dir.as_deref().map(Path::new) {
122 None => base_dir.to_path_buf(),
123 Some(path) if path.is_absolute() => path.to_path_buf(),
124 Some(path) => base_dir.join(path),
125 }
126}
127
128fn default_job_type() -> String {
129 "task".to_string()
130}
131
132fn default_enabled() -> bool {
133 true
134}
135
136fn default_external() -> bool {
137 false }
139
140#[derive(Debug, Serialize, Deserialize)]
142struct ConfigFile {
143 #[serde(default)]
144 jobs: Vec<Job>,
145 #[serde(flatten)]
147 other: serde_norway::Mapping,
148}
149
150pub fn resolve_jobs_path() -> PathBuf {
157 let project = PathBuf::from(".orch.yml");
159 if project.exists() {
160 return project;
161 }
162
163 if let Ok(paths) = config::get_project_paths() {
165 for path_str in &paths {
166 let candidate = PathBuf::from(path_str).join(".orch.yml");
167 if candidate.exists() {
168 return candidate;
169 }
170 }
171 }
172
173 home::config_path().unwrap_or_else(|_| PathBuf::from(".orch/config.yml"))
175}
176
177pub fn load_jobs(path: &PathBuf) -> anyhow::Result<Vec<Job>> {
183 let base_dir = path
184 .parent()
185 .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
186 let mut jobs: Vec<Job> = if path.exists() {
187 let content =
188 fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
189 let file: ConfigFile = serde_norway::from_str(&content)
190 .with_context(|| format!("parsing {}", path.display()))?;
191 file.jobs
192 } else {
193 vec![]
194 };
195
196 let scanned = scan_prompt_jobs(&base_dir)?;
197 let mut seen: HashSet<String> = jobs.iter().map(|j| j.id.clone()).collect();
198 for job in scanned {
199 if !seen.insert(job.id.clone()) {
200 anyhow::bail!(
201 "duplicate job id '{}' — defined in both '{}' and prompts/jobs/",
202 job.id,
203 path.display()
204 );
205 }
206 jobs.push(job);
207 }
208
209 for job in &jobs {
210 validate_job(job, &base_dir)?;
211 }
212 Ok(jobs)
213}
214
215fn validate_job(job: &Job, base_dir: &Path) -> anyhow::Result<()> {
216 let expanded = crate_cron::expand_alias(&job.schedule)
217 .with_context(|| format!("job '{}': invalid cron schedule '{}'", job.id, job.schedule))?;
218 let normalized = crate_cron::normalize_dow(&expanded);
219 let full_expr = format!("0 {normalized} *");
220 Schedule::from_str(&full_expr)
221 .with_context(|| format!("job '{}': invalid cron schedule '{}'", job.id, job.schedule))?;
222 if let Some(template) = job.task.as_ref() {
223 if template.prompt.is_some() && !template.body.is_empty() {
224 anyhow::bail!(
225 "job '{}': set either 'task.body' or 'task.prompt', not both",
226 job.id
227 );
228 }
229 if let Some(rel) = template.prompt.as_deref() {
230 let candidate = Path::new(rel);
231 let full = if candidate.is_absolute() {
232 candidate.to_path_buf()
233 } else {
234 base_dir.join(candidate)
235 };
236 if !full.exists() {
237 anyhow::bail!(
238 "job '{}': prompt file not found: {}",
239 job.id,
240 full.display()
241 );
242 }
243 }
244 }
245 Ok(())
246}
247
248#[derive(Debug, Deserialize)]
250struct JobFrontmatter {
251 id: String,
252 schedule: String,
253 title: String,
254 #[serde(default = "default_job_type")]
255 r#type: String,
256 #[serde(default = "default_enabled")]
257 enabled: bool,
258 #[serde(default = "default_external")]
259 external: bool,
260 #[serde(default)]
261 labels: Vec<String>,
262 #[serde(default)]
263 agent: Option<String>,
264 #[serde(default)]
265 notify: bool,
266 #[serde(default)]
267 notify_target: Option<String>,
268 #[serde(default)]
269 command: Option<String>,
270 #[serde(default)]
271 dir: Option<String>,
272}
273
274fn split_frontmatter(content: &str) -> Option<(&str, &str)> {
277 let rest = content
278 .strip_prefix("---\n")
279 .or_else(|| content.strip_prefix("---\r\n"))?;
280 let end = rest.find("\n---\n").or_else(|| rest.find("\n---\r\n"))?;
281 let fm = &rest[..end];
282 let after = &rest[end..];
283 let body = after
284 .strip_prefix("\n---\n")
285 .or_else(|| after.strip_prefix("\n---\r\n"))
286 .unwrap_or(after);
287 Some((fm, body.trim_start_matches('\n')))
288}
289
290pub fn scan_prompt_jobs(base_dir: &Path) -> anyhow::Result<Vec<Job>> {
292 let dir = base_dir.join("prompts").join("jobs");
293 if !dir.is_dir() {
294 return Ok(vec![]);
295 }
296 let mut entries: Vec<PathBuf> = fs::read_dir(&dir)
297 .with_context(|| format!("reading {}", dir.display()))?
298 .filter_map(result::Result::ok)
299 .map(|e| e.path())
300 .filter(|p| p.extension().and_then(|s| s.to_str()) == Some("md"))
301 .collect();
302 entries.sort();
303
304 let mut jobs = Vec::with_capacity(entries.len());
305 for path in entries {
306 let content =
307 fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;
308 let Some((fm, body)) = split_frontmatter(&content) else {
309 continue; };
311 let meta: JobFrontmatter = serde_norway::from_str(fm)
312 .with_context(|| format!("parsing frontmatter in {}", path.display()))?;
313 jobs.push(Job {
314 id: meta.id,
315 r#type: meta.r#type,
316 schedule: meta.schedule,
317 task: Some(TaskTemplate {
318 title: meta.title,
319 body: body.to_string(),
320 prompt: None,
321 labels: meta.labels,
322 agent: meta.agent,
323 }),
324 command: meta.command,
325 dir: meta.dir,
326 enabled: meta.enabled,
327 external: meta.external,
328 notify: meta.notify,
329 notify_target: meta.notify_target,
330 prompt_file: Some(path.clone()),
331 });
332 }
333 Ok(jobs)
334}
335
336pub fn save_jobs(path: &PathBuf, jobs: &[Job]) -> anyhow::Result<()> {
338 let mut file: ConfigFile = if path.exists() {
340 let content =
341 fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
342 serde_norway::from_str(&content).with_context(|| format!("parsing {}", path.display()))?
343 } else {
344 ConfigFile {
345 jobs: vec![],
346 other: serde_norway::Mapping::new(),
347 }
348 };
349
350 file.jobs = jobs
355 .iter()
356 .filter(|j| j.prompt_file.is_none())
357 .cloned()
358 .collect();
359 let content = serde_norway::to_string(&file)?;
360 fs::write(path, content).with_context(|| format!("writing {}", path.display()))?;
361 Ok(())
362}
363
364pub fn set_frontmatter_enabled(path: &Path, enabled: bool) -> anyhow::Result<()> {
370 let original =
371 fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
372
373 let value = if enabled { "true" } else { "false" };
374
375 let rewritten = rewrite_frontmatter_enabled(&original, value);
379 fs::write(path, rewritten).with_context(|| format!("writing {}", path.display()))?;
380 Ok(())
381}
382
383fn rewrite_frontmatter_enabled(content: &str, value: &str) -> String {
388 let Some(rest) = content
390 .strip_prefix("---\n")
391 .or_else(|| content.strip_prefix("---\r\n"))
392 else {
393 return content.to_string();
395 };
396
397 let Some(close_pos) = rest.find("\n---\n").or_else(|| rest.find("\n---\r\n")) else {
399 return content.to_string();
400 };
401
402 let fm = &rest[..close_pos];
403 let after_close = &rest[close_pos..]; let new_line = format!("enabled: {value}");
407 let mut found = false;
408 let new_fm: String = fm
409 .lines()
410 .map(|line| {
411 if line == "enabled: true" || line == "enabled: false" || line.starts_with("enabled: ")
412 {
413 found = true;
414 new_line.clone()
415 } else {
416 line.to_string()
417 }
418 })
419 .collect::<Vec<_>>()
420 .join("\n");
421
422 let new_fm = if found {
423 new_fm
424 } else {
425 format!("{new_fm}\n{new_line}")
426 };
427
428 format!("---\n{new_fm}{after_close}")
429}
430
431fn is_not_found_error(e: &anyhow::Error) -> bool {
437 e.chain().any(|cause| has_status(&cause.to_string(), 404))
439}
440
441pub async fn tick(
446 jobs_path: &Path,
447 backend: &Arc<dyn ExternalBackend>,
448 store: Option<&Arc<TaskStore>>,
449 repo: &str,
450 transport: Option<&Arc<Transport>>,
451) -> anyhow::Result<()> {
452 let jobs_path_clone = jobs_path.to_path_buf();
453 let jobs = match task::spawn_blocking(move || load_jobs(&jobs_path_clone))
454 .await
455 .map_err(|e| anyhow::anyhow!("load_jobs panicked: {e}"))
456 .and_then(|r| r)
457 {
458 Ok(j) => j,
459 Err(e) => {
460 tracing::error!(
461 path = %jobs_path.display(),
462 repo = %repo,
463 ?e,
464 "job config invalid — skipping scheduler tick for this project"
465 );
466 return Ok(());
467 }
468 };
469 let now = chrono::Utc::now();
470
471 for job in &jobs {
472 if !job.enabled {
473 continue;
474 }
475
476 let mut state = if let Some(s) = store {
478 match s.get_job_state(repo, &job.id).await {
479 Ok(Some(st)) => st,
480 Ok(None) => JobState::new(repo, &job.id),
481 Err(e) => {
482 tracing::error!(job_id = job.id, ?e, "failed to load job state, skipping");
483 continue;
484 }
485 }
486 } else {
487 JobState::new(repo, &job.id)
488 };
489
490 let is_due = match &state.last_run {
492 Some(last) => match crate_cron::check(&job.schedule, Some(last)) {
493 Ok(v) => v,
494 Err(e) => {
495 tracing::error!(
496 job_id = job.id,
497 schedule = job.schedule,
498 ?e,
499 "invalid cron expression, skipping"
500 );
501 continue;
502 }
503 },
504 None => match crate_cron::check(&job.schedule, None) {
505 Ok(v) => v,
506 Err(e) => {
507 tracing::error!(
508 job_id = job.id,
509 schedule = job.schedule,
510 ?e,
511 "invalid cron expression, skipping"
512 );
513 continue;
514 }
515 },
516 };
517
518 if !is_due {
519 continue;
520 }
521
522 let mut should_clear_task_id = false;
524 let mut should_skip = false;
525
526 if let Some(ref task_id) = state.active_task_id
527 && task_id.is_empty()
528 {
529 state.active_task_id = None;
530 }
531
532 if let Some(ref task_id) = state.active_task_id {
533 let task_id_clone = task_id.clone();
534 let is_active = if job.external {
535 match backend.get_task(&ExternalId(task_id_clone.clone())).await {
537 Ok(task) => {
538 let status = task.labels.iter().find(|l| l.starts_with("status:"));
539 match status.map(String::as_str) {
540 Some(
541 "status:in_progress"
542 | "status:routed"
543 | "status:new"
544 | "status:needs_review"
545 | "status:in_review"
546 | "status:approved"
547 | "status:waiting",
548 )
549 | None => true, Some(_) => false, }
552 }
553 Err(e) => {
554 if is_not_found_error(&e) {
555 tracing::warn!(
556 job_id = job.id,
557 task_id = task_id_clone,
558 "active task not found (404), clearing active_task_id"
559 );
560 should_clear_task_id = true;
561 state.last_task_status = Some("error".to_string());
562 } else {
563 tracing::warn!(
564 job_id = job.id,
565 task_id = task_id_clone,
566 ?e,
567 "transient error fetching active task, skipping tick (active_task_id preserved)"
568 );
569 should_skip = true;
570 }
571 false
572 }
573 }
574 } else {
575 if let Some(s) = store {
577 match s.resolve_task_id(repo, &task_id_clone).await {
578 Ok(Some(store_id)) => match s.get(store_id).await {
579 Ok(task) => match task.status {
580 TaskStatus::New
581 | TaskStatus::Routed
582 | TaskStatus::InProgress
583 | TaskStatus::NeedsReview
584 | TaskStatus::InReview
585 | TaskStatus::Approved
586 | TaskStatus::Waiting => true,
587 _ => false, },
589 Err(e) => {
590 tracing::warn!(
591 job_id = job.id,
592 task_id = task_id_clone,
593 ?e,
594 "transient error fetching internal task, skipping tick (active_task_id preserved)"
595 );
596 should_skip = true;
597 false
598 }
599 },
600 Ok(None) => {
601 tracing::warn!(
602 job_id = job.id,
603 task_id = task_id_clone,
604 "internal task not found in store, clearing active_task_id"
605 );
606 should_clear_task_id = true;
607 false
608 }
609 Err(e) => {
610 tracing::warn!(
611 job_id = job.id,
612 task_id = task_id_clone,
613 ?e,
614 "store error resolving internal task, skipping tick (active_task_id preserved)"
615 );
616 should_skip = true;
617 false
618 }
619 }
620 } else {
621 should_clear_task_id = true;
622 false
623 }
624 };
625
626 if is_active {
627 tracing::debug!(
628 job_id = job.id,
629 task_id = task_id_clone,
630 external = job.external,
631 "skipping: previous task still active"
632 );
633 should_skip = true;
634 }
635 }
636
637 if should_clear_task_id {
639 state.active_task_id = None;
640 }
641
642 if should_skip {
643 continue;
644 }
645
646 let bash_guard = if job.r#type == "bash" {
649 let Some(guard) = RunningBash::try_acquire(repo, &job.id) else {
650 tracing::debug!(job_id = job.id, "skipping: bash job still running");
651 continue;
652 };
653 Some(guard)
654 } else {
655 None
656 };
657
658 tracing::info!(job_id = job.id, r#type = job.r#type, "job due, executing");
659
660 state.last_run = Some(now.format("%Y-%m-%dT%H:%M:%SZ").to_string());
665 if let Some(s) = store
666 && let Err(e) = s.upsert_job_state(&state).await
667 {
668 tracing::error!(
669 job_id = job.id,
670 ?e,
671 "failed to persist job state before execution — skipping this tick to preserve restart safety"
672 );
673 continue; }
675
676 let base_dir = jobs_path.parent().unwrap_or_else(|| Path::new("."));
677 if let Some(guard) = bash_guard {
678 spawn_bash_job(
679 guard,
680 job.clone(),
681 state,
682 store.cloned(),
683 repo.to_string(),
684 transport.cloned(),
685 base_dir.to_path_buf(),
686 );
687 continue;
688 }
689
690 execute_job(job, &mut state, backend, store, repo, transport, base_dir).await;
692
693 if let Some(s) = store
695 && let Err(e) = s.upsert_job_state(&state).await
696 {
697 tracing::error!(
698 job_id = job.id,
699 ?e,
700 "failed to persist job state after execution"
701 );
702 }
703 }
704
705 Ok(())
706}
707
708static RUNNING_BASH: LazyLock<DashSet<(String, String)>> = LazyLock::new(DashSet::new);
710
711struct RunningBash {
713 key: (String, String),
714}
715
716impl RunningBash {
717 fn try_acquire(repo: &str, job_id: &str) -> Option<Self> {
718 let key = (repo.to_string(), job_id.to_string());
719 if RUNNING_BASH.insert(key.clone()) {
720 Some(Self { key })
721 } else {
722 None
723 }
724 }
725}
726
727impl Drop for RunningBash {
728 fn drop(&mut self) {
729 RUNNING_BASH.remove(&self.key);
730 }
731}
732
733fn spawn_bash_job(
734 guard: RunningBash,
735 job: Job,
736 mut state: JobState,
737 store: Option<Arc<TaskStore>>,
738 repo: String,
739 transport: Option<Arc<Transport>>,
740 base_dir: PathBuf,
741) {
742 tokio::spawn(async move {
743 let _guard = guard;
744 apply_bash_result(&job, &mut state, &base_dir).await;
745 if let Some(s) = &store
746 && let Err(e) = s.upsert_job_state(&state).await
747 {
748 tracing::error!(
749 job_id = job.id,
750 ?e,
751 "failed to persist job state after execution"
752 );
753 }
754 notify_job_result(&job, &state, &repo, transport.as_ref());
755 });
756}
757
758async fn apply_bash_result(job: &Job, state: &mut JobState, base_dir: &Path) {
759 let Some(cmd) = job.command.as_deref() else {
760 return;
761 };
762 let dir = resolve_job_dir(job, base_dir);
765 tracing::info!(job_id = job.id, cmd, dir = %dir.display(), "running bash command");
766
767 let timeout_secs: u64 = config::get("jobs.bash_timeout_seconds")
770 .ok()
771 .and_then(|s| s.parse().ok())
772 .unwrap_or(300);
773 let timeout = Duration::from_secs(timeout_secs);
774
775 match run_bash(cmd, &dir, timeout).await {
776 Ok(Ok(o)) if o.status.success() => {
777 state.last_task_status = Some("done".to_string());
778 }
779 Ok(Ok(o)) => {
780 let stderr = String::from_utf8_lossy(&o.stderr);
781 tracing::warn!(
782 job_id = job.id,
783 code = o.status.code(),
784 %stderr,
785 "bash command failed"
786 );
787 state.last_task_status = Some("failed".to_string());
788 }
789 Ok(Err(e)) => {
790 tracing::error!(job_id = job.id, ?e, "bash command error");
791 state.last_task_status = Some("failed".to_string());
792 }
793 Err(_) => {
794 tracing::error!(
795 job_id = job.id,
796 secs = timeout_secs,
797 "bash job timed out after {}s, child killed",
798 timeout_secs
799 );
800 state.last_task_status = Some("timeout".to_string());
801 }
802 }
803}
804
805async fn run_bash(
808 cmd: &str,
809 dir: &Path,
810 timeout: Duration,
811) -> result::Result<anyhow::Result<Output>, time::error::Elapsed> {
812 let mut command = Command::new("bash");
813 command
814 .arg("-c")
815 .arg(cmd)
816 .current_dir(dir)
817 .stdin(Stdio::null())
818 .stdout(Stdio::piped())
819 .stderr(Stdio::piped())
820 .kill_on_drop(true);
821 #[cfg(unix)]
822 command.process_group(0);
823
824 let child = match command.spawn() {
825 Ok(child) => child,
826 Err(e) => return Ok(Err(anyhow::anyhow!("failed to execute `bash`: {e}"))),
827 };
828 let pgid = child.id();
829 let out = time::timeout(timeout, child.wait_with_output()).await;
830
831 #[cfg(unix)]
832 if out.is_err()
833 && let Some(pgid) = pgid
834 {
835 cmd_mod::kill_process_group(pgid);
836 }
837
838 out.map(|r| r.map_err(|e| anyhow::anyhow!("failed to execute `bash`: {e}")))
839}
840
841pub async fn execute_job(
846 job: &Job,
847 state: &mut JobState,
848 backend: &Arc<dyn ExternalBackend>,
849 store: Option<&Arc<TaskStore>>,
850 repo: &str,
851 transport: Option<&Arc<Transport>>,
852 base_dir: &Path,
853) {
854 match job.r#type.as_str() {
855 "task" => {
856 if let Some(ref template) = job.task {
857 let body = match resolve_template_body(template, base_dir) {
858 Ok(b) => b,
859 Err(e) => {
860 tracing::error!(job_id = job.id, ?e, "failed to resolve task body");
861 state.last_task_status = Some("failed".to_string());
862 return;
863 }
864 };
865
866 if job.external {
867 let mut labels = template.labels.clone();
868 labels.push("scheduled".to_string());
869 labels.push(format!("job:{}", job.id));
870
871 if let Some(ref agent) = template.agent
872 && !agent.is_empty()
873 {
874 labels.push(format!("agent:{agent}"));
875 }
876
877 match backend.create_task(&template.title, &body, &labels).await {
878 Ok(ext_id) => {
879 tracing::info!(
880 job_id = job.id,
881 task_id = ext_id.0,
882 "created external task"
883 );
884 state.active_task_id = Some(ext_id.0);
885 state.last_task_status = Some("new".to_string());
886 }
887 Err(e) => {
888 tracing::error!(job_id = job.id, ?e, "failed to create external task");
889 state.last_task_status = Some("failed".to_string());
890 }
891 }
892 } else if let Some(s) = store {
893 match s
894 .create_internal(repo, &template.title, &body, "cron", &job.id, None)
895 .await
896 {
897 Ok(internal_id) => {
898 let task_id = format!("internal:{internal_id}");
899 tracing::info!(job_id = job.id, task_id, "created internal task");
900 state.active_task_id = Some(task_id);
901 state.last_task_status = Some("new".to_string());
902 }
903 Err(e) => {
904 tracing::error!(job_id = job.id, ?e, "failed to create internal task");
905 state.last_task_status = Some("failed".to_string());
906 }
907 }
908 } else {
909 tracing::error!(
910 job_id = job.id,
911 "no store available for internal task creation"
912 );
913 state.last_task_status = Some("failed".to_string());
914 }
915 }
916 }
917 "bash" => {
918 apply_bash_result(job, state, base_dir).await;
919 }
920 other => {
926 tracing::warn!(job_id = job.id, r#type = other, "unknown job type");
927 }
928 }
929
930 notify_job_result(job, state, repo, transport);
931}
932
933fn notify_job_result(job: &Job, state: &JobState, repo: &str, transport: Option<&Arc<Transport>>) {
934 if job.notify
935 && let Some(t) = transport
936 {
937 let status = state
938 .last_task_status
939 .as_deref()
940 .unwrap_or("unknown")
941 .to_string();
942 let summary = match status.as_str() {
943 "done" => format!("Job `{}` completed successfully.", job.id),
944 "failed" => format!("Job `{}` failed.", job.id),
945 "new" => format!("Job `{}` created a new task.", job.id),
946 other => format!("Job `{}` finished with status: {other}.", job.id),
947 };
948 let target = job
950 .notify_target
951 .clone()
952 .or_else(|| config::get("channels.telegram.chat_id").ok());
953 let notification = TaskNotification {
954 task_id: job.id.clone(),
955 title: format!("Job: {}", job.id),
956 status,
957 agent: "scheduler".to_string(),
958 duration_seconds: 0.0,
959 summary,
960 repo: Some(repo.to_string()),
961 notify_target: target,
962 pr_number: None,
963 };
964 t.push_notification(notification);
965 }
966}
967
968#[cfg(test)]
973mod tests {
974 use super::*;
975 use crate::backends::test_helpers::NoopBackend;
976 use std::env;
977 use std::fs;
978 use tempfile::tempdir;
979
980 fn write_config(dir: &Path, content: &str) -> PathBuf {
981 let path = dir.join(".orch.yml");
982 fs::write(&path, content).unwrap();
983 path
984 }
985
986 #[tokio::test]
987 async fn run_bash_timeout_kills_the_child() {
988 let tmp = tempdir().unwrap();
989 let pid_file = tmp.path().join("pid");
990 let cmd = format!("sleep 60 & echo $! > {}; wait", pid_file.display());
991
992 let out = run_bash(&cmd, Path::new("."), Duration::from_secs(1)).await;
993 assert!(out.is_err(), "expected a timeout");
994
995 let pid: i32 = fs::read_to_string(&pid_file)
996 .unwrap()
997 .trim()
998 .parse()
999 .unwrap();
1000 let mut gone = false;
1001 for _ in 0..20 {
1002 if cmd_mod::raw_kill(pid, 0) != 0 {
1003 gone = true;
1004 break;
1005 }
1006 time::sleep(Duration::from_millis(100)).await;
1007 }
1008 assert!(gone, "grandchild {pid} still running after timeout");
1009 }
1010
1011 fn bash_job(id: &str, command: String, dir: Option<&str>) -> Job {
1012 Job {
1013 id: id.to_string(),
1014 r#type: "bash".to_string(),
1015 schedule: "* * * * *".to_string(),
1016 task: None,
1017 command: Some(command),
1018 dir: dir.map(str::to_string),
1019 enabled: true,
1020 external: false,
1021 notify: false,
1022 notify_target: None,
1023 prompt_file: None,
1024 }
1025 }
1026
1027 async fn execute_bash(job: &Job, base_dir: &Path) -> JobState {
1028 let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
1029 let mut state = JobState::new("owner/repo", &job.id);
1030 execute_job(
1031 job,
1032 &mut state,
1033 &backend,
1034 None,
1035 "owner/repo",
1036 None,
1037 base_dir,
1038 )
1039 .await;
1040 state
1041 }
1042
1043 fn read_recorded_cwd(path: &Path) -> PathBuf {
1044 let raw = fs::read_to_string(path).expect("bash command should have written cwd.txt");
1045 fs::canonicalize(raw.trim()).unwrap()
1046 }
1047
1048 #[tokio::test]
1049 async fn bash_job_runs_in_project_dir_not_process_cwd() {
1050 let project = tempdir().unwrap();
1051 let process_cwd = fs::canonicalize(env::current_dir().unwrap()).unwrap();
1052 let project_dir = fs::canonicalize(project.path()).unwrap();
1053 assert_ne!(
1054 process_cwd, project_dir,
1055 "setup: process cwd must differ from the project dir"
1056 );
1057
1058 let out_default = project.path().join("cwd-default.txt");
1059 let job = bash_job(
1060 "default-dir",
1061 format!("pwd > '{}'", out_default.display()),
1062 None,
1063 );
1064 let state = execute_bash(&job, project.path()).await;
1065 assert_eq!(
1066 state.last_task_status.as_deref(),
1067 Some("done"),
1068 "bash job with no dir should succeed in the project dir"
1069 );
1070 assert_eq!(
1071 read_recorded_cwd(&out_default),
1072 project_dir,
1073 "bash job with no dir must run in the project dir"
1074 );
1075
1076 let scripts = project.path().join("scripts");
1077 fs::create_dir(&scripts).unwrap();
1078 let out_relative = project.path().join("cwd-relative.txt");
1079 let job = bash_job(
1080 "relative-dir",
1081 format!("pwd > '{}'", out_relative.display()),
1082 Some("scripts"),
1083 );
1084 let state = execute_bash(&job, project.path()).await;
1085 assert_eq!(
1086 state.last_task_status.as_deref(),
1087 Some("done"),
1088 "bash job should succeed when relative dir resolves to an existing path"
1089 );
1090 assert_eq!(
1091 read_recorded_cwd(&out_relative),
1092 fs::canonicalize(&scripts).unwrap(),
1093 "relative dir must resolve against the project dir"
1094 );
1095
1096 let abs = tempdir().unwrap();
1097 let out_abs = project.path().join("cwd-absolute.txt");
1098 let job = bash_job(
1099 "absolute-dir",
1100 format!("pwd > '{}'", out_abs.display()),
1101 Some(abs.path().to_str().unwrap()),
1102 );
1103 let state = execute_bash(&job, project.path()).await;
1104 assert_eq!(
1105 state.last_task_status.as_deref(),
1106 Some("done"),
1107 "bash job should succeed when dir is an absolute path"
1108 );
1109 assert_eq!(
1110 read_recorded_cwd(&out_abs),
1111 fs::canonicalize(abs.path()).unwrap(),
1112 "absolute dir must be used as-is"
1113 );
1114 }
1115
1116 async fn tick_with_store(path: &Path, store: &Arc<TaskStore>, repo: &str) {
1117 let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
1118 tick(path, &backend, Some(store), repo, None).await.unwrap();
1119 }
1120
1121 async fn wait_for_job_status(
1122 store: &TaskStore,
1123 repo: &str,
1124 job_id: &str,
1125 want: &str,
1126 ) -> Option<String> {
1127 for _ in 0..300 {
1128 let status = store
1129 .get_job_state(repo, job_id)
1130 .await
1131 .unwrap()
1132 .and_then(|s| s.last_task_status);
1133 if status.as_deref() == Some(want) {
1134 return status;
1135 }
1136 time::sleep(Duration::from_millis(50)).await;
1137 }
1138 store
1139 .get_job_state(repo, job_id)
1140 .await
1141 .unwrap()
1142 .and_then(|s| s.last_task_status)
1143 }
1144
1145 #[tokio::test]
1146 async fn bash_job_tick_returns_before_the_command_ends() {
1147 let tmp = tempdir().unwrap();
1148 let cfg = write_config(
1149 tmp.path(),
1150 r#"
1151jobs:
1152 - id: slow
1153 type: bash
1154 schedule: "* * * * *"
1155 command: "sleep 5"
1156"#,
1157 );
1158 let store = Arc::new(TaskStore::open_memory().await.unwrap());
1159 let repo = "tick-returns/repo";
1160 let started = time::Instant::now();
1161 tick_with_store(&cfg, &store, repo).await;
1162 assert!(
1163 started.elapsed() < Duration::from_secs(2),
1164 "tick waited for the bash command, elapsed {:?}",
1165 started.elapsed()
1166 );
1167 let early = store.get_job_state(repo, "slow").await.unwrap().unwrap();
1168 assert!(
1169 early.last_run.is_some(),
1170 "last_run must be written before the command ends"
1171 );
1172 assert_ne!(
1173 early.last_task_status.as_deref(),
1174 Some("done"),
1175 "job state must not already be done when tick returns"
1176 );
1177 let status = wait_for_job_status(&store, repo, "slow", "done").await;
1178 assert_eq!(status.as_deref(), Some("done"));
1179 }
1180
1181 #[tokio::test]
1182 async fn bash_job_tick_starts_only_one_run() {
1183 let tmp = tempdir().unwrap();
1184 let log = tmp.path().join("runs.log");
1185 let go = tmp.path().join("go");
1186 let cfg = write_config(
1187 tmp.path(),
1188 &format!(
1189 r#"
1190jobs:
1191 - id: once
1192 type: bash
1193 schedule: "* * * * *"
1194 command: "echo x >> '{log}'; while [ ! -f '{go}' ]; do sleep 0.05; done"
1195"#,
1196 log = log.display(),
1197 go = go.display(),
1198 ),
1199 );
1200 let store = Arc::new(TaskStore::open_memory().await.unwrap());
1201 let repo = "tick-one-run/repo";
1202 tick_with_store(&cfg, &store, repo).await;
1203
1204 for _ in 0..100 {
1205 if log.exists() {
1206 break;
1207 }
1208 time::sleep(Duration::from_millis(20)).await;
1209 }
1210 assert!(log.exists(), "first bash job never started");
1211
1212 let mut state = store
1213 .get_job_state(repo, "once")
1214 .await
1215 .unwrap()
1216 .expect("last_run written before spawn");
1217 let past = chrono::Utc::now() - chrono::Duration::minutes(2);
1218 state.last_run = Some(past.format("%Y-%m-%dT%H:%M:%SZ").to_string());
1219 store.upsert_job_state(&state).await.unwrap();
1220
1221 tick_with_store(&cfg, &store, repo).await;
1222 fs::write(&go, "").unwrap();
1223 let status = wait_for_job_status(&store, repo, "once", "done").await;
1224 assert_eq!(status.as_deref(), Some("done"));
1225 let body = fs::read_to_string(&log).unwrap();
1226 assert_eq!(
1227 body.matches('x').count(),
1228 1,
1229 "started a second copy: {body:?}"
1230 );
1231 }
1232
1233 #[test]
1234 fn load_jobs_reads_prompt_from_file() {
1235 let tmp = tempdir().unwrap();
1236 fs::create_dir(tmp.path().join("prompts")).unwrap();
1237 fs::write(tmp.path().join("prompts/hello.md"), "hello from file").unwrap();
1238 let cfg = write_config(
1239 tmp.path(),
1240 r#"
1241jobs:
1242 - id: with-prompt
1243 schedule: "0 9 * * *"
1244 task:
1245 title: "Daily"
1246 prompt: prompts/hello.md
1247"#,
1248 );
1249
1250 let jobs = load_jobs(&cfg).unwrap();
1251 assert_eq!(jobs.len(), 1);
1252 let body = resolve_template_body(jobs[0].task.as_ref().unwrap(), tmp.path()).unwrap();
1253 assert_eq!(body, "hello from file");
1254 }
1255
1256 #[test]
1257 fn load_jobs_rejects_both_body_and_prompt() {
1258 let tmp = tempdir().unwrap();
1259 fs::write(tmp.path().join("p.md"), "x").unwrap();
1260 let cfg = write_config(
1261 tmp.path(),
1262 r#"
1263jobs:
1264 - id: conflict
1265 schedule: "0 9 * * *"
1266 task:
1267 title: "x"
1268 body: "inline"
1269 prompt: p.md
1270"#,
1271 );
1272
1273 let err = load_jobs(&cfg).unwrap_err().to_string();
1274 assert!(err.contains("not both"), "unexpected error: {err}");
1275 }
1276
1277 #[test]
1278 fn load_jobs_rejects_missing_prompt_file() {
1279 let tmp = tempdir().unwrap();
1280 let cfg = write_config(
1281 tmp.path(),
1282 r#"
1283jobs:
1284 - id: missing
1285 schedule: "0 9 * * *"
1286 task:
1287 title: "x"
1288 prompt: does-not-exist.md
1289"#,
1290 );
1291
1292 let err = load_jobs(&cfg).unwrap_err().to_string();
1293 assert!(
1294 err.contains("prompt file not found"),
1295 "unexpected error: {err}"
1296 );
1297 }
1298
1299 #[test]
1300 fn resolve_template_body_falls_back_to_inline_body() {
1301 let tmp = tempdir().unwrap();
1302 let template = TaskTemplate {
1303 title: "t".to_string(),
1304 body: "inline body".to_string(),
1305 prompt: None,
1306 labels: vec![],
1307 agent: None,
1308 };
1309 assert_eq!(
1310 resolve_template_body(&template, tmp.path()).unwrap(),
1311 "inline body"
1312 );
1313 }
1314
1315 fn write_prompt_job(dir: &Path, name: &str, content: &str) {
1316 let jobs_dir = dir.join("prompts").join("jobs");
1317 fs::create_dir_all(&jobs_dir).unwrap();
1318 fs::write(jobs_dir.join(name), content).unwrap();
1319 }
1320
1321 #[test]
1322 fn scan_prompt_jobs_picks_up_frontmatter_files() {
1323 let tmp = tempdir().unwrap();
1324 write_prompt_job(
1325 tmp.path(),
1326 "morning.md",
1327 "---\nid: morning\nschedule: '0 9 * * *'\ntitle: Morning\nlabels: [daily]\nagent: claude\n---\n\nDo morning stuff.\n",
1328 );
1329 let jobs = scan_prompt_jobs(tmp.path()).unwrap();
1330 assert_eq!(jobs.len(), 1);
1331 assert_eq!(jobs[0].id, "morning");
1332 assert_eq!(jobs[0].schedule, "0 9 * * *");
1333 let task = jobs[0].task.as_ref().unwrap();
1334 assert_eq!(task.title, "Morning");
1335 assert_eq!(task.body, "Do morning stuff.\n");
1336 assert_eq!(task.labels, vec!["daily".to_string()]);
1337 assert_eq!(task.agent.as_deref(), Some("claude"));
1338 }
1339
1340 #[test]
1341 fn load_jobs_merges_inline_and_scanned() {
1342 let tmp = tempdir().unwrap();
1343 write_prompt_job(
1344 tmp.path(),
1345 "scanned.md",
1346 "---\nid: scanned\nschedule: '0 9 * * *'\ntitle: Scanned\n---\n\nbody\n",
1347 );
1348 let cfg = write_config(
1349 tmp.path(),
1350 r#"
1351jobs:
1352 - id: inline
1353 schedule: "0 10 * * *"
1354 task:
1355 title: "Inline"
1356 body: "x"
1357"#,
1358 );
1359 let jobs = load_jobs(&cfg).unwrap();
1360 let ids: Vec<&str> = jobs.iter().map(|j| j.id.as_str()).collect();
1361 assert!(ids.contains(&"inline"));
1362 assert!(ids.contains(&"scanned"));
1363 assert_eq!(jobs.len(), 2);
1364 }
1365
1366 #[test]
1367 fn load_jobs_rejects_duplicate_id_across_sources() {
1368 let tmp = tempdir().unwrap();
1369 write_prompt_job(
1370 tmp.path(),
1371 "dup.md",
1372 "---\nid: dup\nschedule: '0 9 * * *'\ntitle: Dup\n---\n\nbody\n",
1373 );
1374 let cfg = write_config(
1375 tmp.path(),
1376 r#"
1377jobs:
1378 - id: dup
1379 schedule: "0 10 * * *"
1380 task:
1381 title: "Dup inline"
1382 body: "x"
1383"#,
1384 );
1385 let err = load_jobs(&cfg).unwrap_err().to_string();
1386 assert!(err.contains("duplicate job id"), "unexpected error: {err}");
1387 }
1388
1389 #[test]
1390 fn scan_prompt_jobs_ignores_files_without_frontmatter() {
1391 let tmp = tempdir().unwrap();
1392 write_prompt_job(
1393 tmp.path(),
1394 "plain.md",
1395 "just a prompt body, no frontmatter\n",
1396 );
1397 let jobs = scan_prompt_jobs(tmp.path()).unwrap();
1398 assert_eq!(jobs.len(), 0);
1399 }
1400
1401 #[test]
1402 fn load_jobs_works_without_config_file_when_directory_present() {
1403 let tmp = tempdir().unwrap();
1404 write_prompt_job(
1405 tmp.path(),
1406 "solo.md",
1407 "---\nid: solo\nschedule: '0 9 * * *'\ntitle: Solo\n---\n\nbody\n",
1408 );
1409 let missing_cfg = tmp.path().join(".orch.yml");
1410 let jobs = load_jobs(&missing_cfg).unwrap();
1411 assert_eq!(jobs.len(), 1);
1412 assert_eq!(jobs[0].id, "solo");
1413 }
1414
1415 #[test]
1418 fn scan_prompt_jobs_respects_enabled_false() {
1419 let tmp = tempdir().unwrap();
1420 write_prompt_job(
1421 tmp.path(),
1422 "disabled.md",
1423 "---\nid: disabled\nschedule: '0 9 * * *'\ntitle: Disabled\nenabled: false\n---\n\nbody\n",
1424 );
1425 let jobs = scan_prompt_jobs(tmp.path()).unwrap();
1426 assert_eq!(jobs.len(), 1);
1427 assert!(!jobs[0].enabled, "job should be disabled via frontmatter");
1428 }
1429
1430 #[test]
1431 fn scan_prompt_jobs_sets_prompt_file() {
1432 let tmp = tempdir().unwrap();
1433 write_prompt_job(
1434 tmp.path(),
1435 "morning.md",
1436 "---\nid: morning\nschedule: '0 9 * * *'\ntitle: Morning\n---\n\nbody\n",
1437 );
1438 let jobs = scan_prompt_jobs(tmp.path()).unwrap();
1439 assert_eq!(jobs.len(), 1);
1440 assert!(
1441 jobs[0].prompt_file.is_some(),
1442 "prompt_file should be set for frontmatter jobs"
1443 );
1444 }
1445
1446 #[test]
1447 fn save_jobs_does_not_persist_prompt_based_jobs() {
1448 let tmp = tempdir().unwrap();
1449 write_prompt_job(
1451 tmp.path(),
1452 "prompt.md",
1453 "---\nid: from-prompt\nschedule: '0 9 * * *'\ntitle: Prompt Job\n---\n\nbody\n",
1454 );
1455 let cfg = write_config(
1457 tmp.path(),
1458 "jobs:\n - id: inline\n schedule: \"0 10 * * *\"\n task:\n title: Inline\n body: x\n",
1459 );
1460 let jobs = load_jobs(&cfg).unwrap();
1461 assert_eq!(jobs.len(), 2);
1462
1463 save_jobs(&cfg, &jobs).unwrap();
1465
1466 let saved = load_jobs(&cfg).unwrap();
1467 assert_eq!(saved.len(), 2, "both jobs should still be loadable");
1468 let ids: Vec<&str> = saved.iter().map(|j| j.id.as_str()).collect();
1469 assert!(ids.contains(&"inline"));
1470 assert!(ids.contains(&"from-prompt"));
1471 }
1472
1473 #[test]
1474 fn rewrite_frontmatter_enabled_replaces_existing_value() {
1475 let input = "---\nid: foo\nschedule: daily\nenabled: true\ntitle: Foo\n---\n\nbody\n";
1476 let out = rewrite_frontmatter_enabled(input, "false");
1477 assert!(
1478 out.contains("enabled: false"),
1479 "should replace enabled: true"
1480 );
1481 assert!(!out.contains("enabled: true"), "old value must be gone");
1482 assert!(out.contains("body"), "body must be preserved");
1483 }
1484
1485 #[test]
1486 fn rewrite_frontmatter_enabled_inserts_when_absent() {
1487 let input = "---\nid: foo\nschedule: daily\ntitle: Foo\n---\n\nbody\n";
1488 let out = rewrite_frontmatter_enabled(input, "false");
1489 assert!(
1490 out.contains("enabled: false"),
1491 "should insert enabled: false"
1492 );
1493 assert!(out.contains("body"), "body must be preserved");
1494 }
1495
1496 #[test]
1497 fn set_frontmatter_enabled_writes_file() {
1498 let tmp = tempdir().unwrap();
1499 let path = tmp.path().join("job.md");
1500 fs::write(
1501 &path,
1502 "---\nid: foo\nschedule: daily\ntitle: Foo\nenabled: true\n---\n\nbody\n",
1503 )
1504 .unwrap();
1505 set_frontmatter_enabled(&path, false).unwrap();
1506 let content = fs::read_to_string(&path).unwrap();
1507 assert!(content.contains("enabled: false"));
1508 assert!(!content.contains("enabled: true"));
1509 }
1510
1511 #[tokio::test]
1512 async fn tick_keeps_active_task_id_when_the_store_lookup_fails() {
1513 let tmp = tempdir().unwrap();
1514 let cfg = write_config(
1515 tmp.path(),
1516 r#"
1517jobs:
1518 - id: nightly
1519 type: bash
1520 schedule: "* * * * *"
1521 command: "true"
1522"#,
1523 );
1524 let store = Arc::new(TaskStore::open_memory().await.unwrap());
1525 let mut state = JobState::new("owner/repo", "nightly");
1526 state.active_task_id = Some("internal:1".to_string());
1527 store.upsert_job_state(&state).await.unwrap();
1528 sqlx::query("DROP TABLE tasks")
1530 .execute(store.pool())
1531 .await
1532 .unwrap();
1533
1534 let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
1535 tick(&cfg, &backend, Some(&store), "owner/repo", None)
1536 .await
1537 .unwrap();
1538
1539 let after = store
1540 .get_job_state("owner/repo", "nightly")
1541 .await
1542 .unwrap()
1543 .unwrap();
1544 assert_eq!(after.active_task_id.as_deref(), Some("internal:1"));
1545 assert_eq!(after.last_run, None, "the job must not run again");
1546 }
1547
1548 #[test]
1549 fn not_found_error_ignores_a_404_inside_the_issue_number() {
1550 let transient = anyhow::anyhow!(
1551 "GitHub API GET https://api.github.com/repos/o/r/issues/1404 failed (500 Internal Server Error): boom"
1552 );
1553 assert!(!is_not_found_error(&transient));
1554 let missing = anyhow::anyhow!(
1555 "GitHub API GET https://api.github.com/repos/o/r/issues/1404 failed (404 Not Found): Not Found"
1556 );
1557 assert!(is_not_found_error(&missing));
1558 }
1559}