1use crate::backends::{ExternalBackend, ExternalId};
17use crate::channels::notification::TaskNotification;
18use crate::channels::transport::Transport;
19use crate::cmd::CommandErrorContext;
20use crate::config;
21use crate::cron as crate_cron;
22use crate::home;
23use crate::store::TaskStore;
24use crate::store::{JobState, TaskStatus};
25use anyhow::Context;
26use cron::Schedule;
27use serde::{Deserialize, Serialize};
28use std::collections::HashSet;
29use std::fs;
30use std::path::{Path, PathBuf};
31use std::process::Output;
32use std::result;
33use std::str::FromStr;
34use std::sync::Arc;
35use std::time::Duration;
36use tokio::process::Command;
37use tokio::task;
38use tokio::time;
39
40#[derive(Debug, Clone, Serialize, Deserialize)]
46pub struct Job {
47 pub id: String,
48 #[serde(default = "default_job_type")]
49 pub r#type: String,
50 pub schedule: String,
51 #[serde(default)]
52 pub task: Option<TaskTemplate>,
53 #[serde(default)]
54 pub command: Option<String>,
55 #[serde(default)]
56 pub dir: Option<String>,
57 #[serde(default = "default_enabled")]
58 pub enabled: bool,
59 #[serde(default = "default_external")]
60 pub external: bool, #[serde(default)]
64 pub notify: bool,
65 #[serde(default)]
68 pub notify_target: Option<String>,
69 #[serde(skip)]
75 pub prompt_file: Option<PathBuf>,
76}
77
78#[derive(Debug, Clone, Serialize, Deserialize)]
80pub struct TaskTemplate {
81 pub title: String,
82 #[serde(default)]
83 pub body: String,
84 #[serde(default, skip_serializing_if = "Option::is_none")]
88 pub prompt: Option<String>,
89 #[serde(default)]
90 pub labels: Vec<String>,
91 #[serde(default)]
92 pub agent: Option<String>,
93}
94
95pub fn resolve_template_body(template: &TaskTemplate, base_dir: &Path) -> anyhow::Result<String> {
100 match template.prompt.as_deref() {
101 Some(rel) => {
102 let path = Path::new(rel);
103 let full = if path.is_absolute() {
104 path.to_path_buf()
105 } else {
106 base_dir.join(path)
107 };
108 fs::read_to_string(&full)
109 .with_context(|| format!("reading prompt file {}", full.display()))
110 }
111 None => Ok(template.body.clone()),
112 }
113}
114
115fn default_job_type() -> String {
116 "task".to_string()
117}
118
119fn default_enabled() -> bool {
120 true
121}
122
123fn default_external() -> bool {
124 false }
126
127#[derive(Debug, Serialize, Deserialize)]
129struct ConfigFile {
130 #[serde(default)]
131 jobs: Vec<Job>,
132 #[serde(flatten)]
134 other: serde_norway::Mapping,
135}
136
137pub fn resolve_jobs_path() -> PathBuf {
144 let project = PathBuf::from(".orch.yml");
146 if project.exists() {
147 return project;
148 }
149
150 if let Ok(paths) = config::get_project_paths() {
152 for path_str in &paths {
153 let candidate = PathBuf::from(path_str).join(".orch.yml");
154 if candidate.exists() {
155 return candidate;
156 }
157 }
158 }
159
160 home::config_path().unwrap_or_else(|_| PathBuf::from(".orch/config.yml"))
162}
163
164pub fn load_jobs(path: &PathBuf) -> anyhow::Result<Vec<Job>> {
170 let base_dir = path
171 .parent()
172 .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
173 let mut jobs: Vec<Job> = if path.exists() {
174 let content =
175 fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
176 let file: ConfigFile = serde_norway::from_str(&content)
177 .with_context(|| format!("parsing {}", path.display()))?;
178 file.jobs
179 } else {
180 vec![]
181 };
182
183 let scanned = scan_prompt_jobs(&base_dir)?;
184 let mut seen: HashSet<String> = jobs.iter().map(|j| j.id.clone()).collect();
185 for job in scanned {
186 if !seen.insert(job.id.clone()) {
187 anyhow::bail!(
188 "duplicate job id '{}' — defined in both '{}' and prompts/jobs/",
189 job.id,
190 path.display()
191 );
192 }
193 jobs.push(job);
194 }
195
196 for job in &jobs {
197 validate_job(job, &base_dir)?;
198 }
199 Ok(jobs)
200}
201
202fn validate_job(job: &Job, base_dir: &Path) -> anyhow::Result<()> {
203 let expanded = crate_cron::expand_alias(&job.schedule)
204 .with_context(|| format!("job '{}': invalid cron schedule '{}'", job.id, job.schedule))?;
205 let normalized = crate_cron::normalize_dow(&expanded);
206 let full_expr = format!("0 {normalized} *");
207 Schedule::from_str(&full_expr)
208 .with_context(|| format!("job '{}': invalid cron schedule '{}'", job.id, job.schedule))?;
209 if let Some(template) = job.task.as_ref() {
210 if template.prompt.is_some() && !template.body.is_empty() {
211 anyhow::bail!(
212 "job '{}': set either 'task.body' or 'task.prompt', not both",
213 job.id
214 );
215 }
216 if let Some(rel) = template.prompt.as_deref() {
217 let candidate = Path::new(rel);
218 let full = if candidate.is_absolute() {
219 candidate.to_path_buf()
220 } else {
221 base_dir.join(candidate)
222 };
223 if !full.exists() {
224 anyhow::bail!(
225 "job '{}': prompt file not found: {}",
226 job.id,
227 full.display()
228 );
229 }
230 }
231 }
232 Ok(())
233}
234
235#[derive(Debug, Deserialize)]
237struct JobFrontmatter {
238 id: String,
239 schedule: String,
240 title: String,
241 #[serde(default = "default_job_type")]
242 r#type: String,
243 #[serde(default = "default_enabled")]
244 enabled: bool,
245 #[serde(default = "default_external")]
246 external: bool,
247 #[serde(default)]
248 labels: Vec<String>,
249 #[serde(default)]
250 agent: Option<String>,
251 #[serde(default)]
252 notify: bool,
253 #[serde(default)]
254 notify_target: Option<String>,
255 #[serde(default)]
256 command: Option<String>,
257 #[serde(default)]
258 dir: Option<String>,
259}
260
261fn split_frontmatter(content: &str) -> Option<(&str, &str)> {
264 let rest = content
265 .strip_prefix("---\n")
266 .or_else(|| content.strip_prefix("---\r\n"))?;
267 let end = rest.find("\n---\n").or_else(|| rest.find("\n---\r\n"))?;
268 let fm = &rest[..end];
269 let after = &rest[end..];
270 let body = after
271 .strip_prefix("\n---\n")
272 .or_else(|| after.strip_prefix("\n---\r\n"))
273 .unwrap_or(after);
274 Some((fm, body.trim_start_matches('\n')))
275}
276
277pub fn scan_prompt_jobs(base_dir: &Path) -> anyhow::Result<Vec<Job>> {
279 let dir = base_dir.join("prompts").join("jobs");
280 if !dir.is_dir() {
281 return Ok(vec![]);
282 }
283 let mut entries: Vec<PathBuf> = fs::read_dir(&dir)
284 .with_context(|| format!("reading {}", dir.display()))?
285 .filter_map(result::Result::ok)
286 .map(|e| e.path())
287 .filter(|p| p.extension().and_then(|s| s.to_str()) == Some("md"))
288 .collect();
289 entries.sort();
290
291 let mut jobs = Vec::with_capacity(entries.len());
292 for path in entries {
293 let content =
294 fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;
295 let Some((fm, body)) = split_frontmatter(&content) else {
296 continue; };
298 let meta: JobFrontmatter = serde_norway::from_str(fm)
299 .with_context(|| format!("parsing frontmatter in {}", path.display()))?;
300 jobs.push(Job {
301 id: meta.id,
302 r#type: meta.r#type,
303 schedule: meta.schedule,
304 task: Some(TaskTemplate {
305 title: meta.title,
306 body: body.to_string(),
307 prompt: None,
308 labels: meta.labels,
309 agent: meta.agent,
310 }),
311 command: meta.command,
312 dir: meta.dir,
313 enabled: meta.enabled,
314 external: meta.external,
315 notify: meta.notify,
316 notify_target: meta.notify_target,
317 prompt_file: Some(path.clone()),
318 });
319 }
320 Ok(jobs)
321}
322
323pub fn save_jobs(path: &PathBuf, jobs: &[Job]) -> anyhow::Result<()> {
325 let mut file: ConfigFile = if path.exists() {
327 let content =
328 fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
329 serde_norway::from_str(&content).with_context(|| format!("parsing {}", path.display()))?
330 } else {
331 ConfigFile {
332 jobs: vec![],
333 other: serde_norway::Mapping::new(),
334 }
335 };
336
337 file.jobs = jobs
342 .iter()
343 .filter(|j| j.prompt_file.is_none())
344 .cloned()
345 .collect();
346 let content = serde_norway::to_string(&file)?;
347 fs::write(path, content).with_context(|| format!("writing {}", path.display()))?;
348 Ok(())
349}
350
351pub fn set_frontmatter_enabled(path: &Path, enabled: bool) -> anyhow::Result<()> {
357 let original =
358 fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
359
360 let value = if enabled { "true" } else { "false" };
361
362 let rewritten = rewrite_frontmatter_enabled(&original, value);
366 fs::write(path, rewritten).with_context(|| format!("writing {}", path.display()))?;
367 Ok(())
368}
369
370fn rewrite_frontmatter_enabled(content: &str, value: &str) -> String {
375 let Some(rest) = content
377 .strip_prefix("---\n")
378 .or_else(|| content.strip_prefix("---\r\n"))
379 else {
380 return content.to_string();
382 };
383
384 let Some(close_pos) = rest.find("\n---\n").or_else(|| rest.find("\n---\r\n")) else {
386 return content.to_string();
387 };
388
389 let fm = &rest[..close_pos];
390 let after_close = &rest[close_pos..]; let new_line = format!("enabled: {value}");
394 let mut found = false;
395 let new_fm: String = fm
396 .lines()
397 .map(|line| {
398 if line == "enabled: true" || line == "enabled: false" || line.starts_with("enabled: ")
399 {
400 found = true;
401 new_line.clone()
402 } else {
403 line.to_string()
404 }
405 })
406 .collect::<Vec<_>>()
407 .join("\n");
408
409 let new_fm = if found {
410 new_fm
411 } else {
412 format!("{new_fm}\n{new_line}")
413 };
414
415 format!("---\n{new_fm}{after_close}")
416}
417
418fn is_not_found_error(e: &anyhow::Error) -> bool {
424 e.chain().any(|cause| cause.to_string().contains("404"))
428}
429
430pub async fn tick(
435 jobs_path: &Path,
436 backend: &Arc<dyn ExternalBackend>,
437 store: Option<&Arc<TaskStore>>,
438 repo: &str,
439 transport: Option<&Arc<Transport>>,
440) -> anyhow::Result<()> {
441 let jobs_path_clone = jobs_path.to_path_buf();
442 let jobs = match task::spawn_blocking(move || load_jobs(&jobs_path_clone))
443 .await
444 .map_err(|e| anyhow::anyhow!("load_jobs panicked: {e}"))
445 .and_then(|r| r)
446 {
447 Ok(j) => j,
448 Err(e) => {
449 tracing::error!(
450 path = %jobs_path.display(),
451 repo = %repo,
452 ?e,
453 "job config invalid — skipping scheduler tick for this project"
454 );
455 return Ok(());
456 }
457 };
458 let now = chrono::Utc::now();
459
460 for job in &jobs {
461 if !job.enabled {
462 continue;
463 }
464
465 let mut state = if let Some(s) = store {
467 match s.get_job_state(repo, &job.id).await {
468 Ok(Some(st)) => st,
469 Ok(None) => JobState::new(repo, &job.id),
470 Err(e) => {
471 tracing::error!(job_id = job.id, ?e, "failed to load job state, skipping");
472 continue;
473 }
474 }
475 } else {
476 JobState::new(repo, &job.id)
477 };
478
479 let is_due = match &state.last_run {
481 Some(last) => match crate_cron::check(&job.schedule, Some(last)) {
482 Ok(v) => v,
483 Err(e) => {
484 tracing::error!(
485 job_id = job.id,
486 schedule = job.schedule,
487 ?e,
488 "invalid cron expression, skipping"
489 );
490 continue;
491 }
492 },
493 None => match crate_cron::check(&job.schedule, None) {
494 Ok(v) => v,
495 Err(e) => {
496 tracing::error!(
497 job_id = job.id,
498 schedule = job.schedule,
499 ?e,
500 "invalid cron expression, skipping"
501 );
502 continue;
503 }
504 },
505 };
506
507 if !is_due {
508 continue;
509 }
510
511 let mut should_clear_task_id = false;
513 let mut should_skip = false;
514
515 if let Some(ref task_id) = state.active_task_id
516 && task_id.is_empty()
517 {
518 state.active_task_id = None;
519 }
520
521 if let Some(ref task_id) = state.active_task_id {
522 let task_id_clone = task_id.clone();
523 let is_active = if job.external {
524 match backend.get_task(&ExternalId(task_id_clone.clone())).await {
526 Ok(task) => {
527 let status = task.labels.iter().find(|l| l.starts_with("status:"));
528 match status.map(String::as_str) {
529 Some(
530 "status:in_progress"
531 | "status:routed"
532 | "status:new"
533 | "status:needs_review"
534 | "status:in_review"
535 | "status:approved"
536 | "status:waiting",
537 )
538 | None => true, Some(_) => false, }
541 }
542 Err(e) => {
543 if is_not_found_error(&e) {
544 tracing::warn!(
545 job_id = job.id,
546 task_id = task_id_clone,
547 "active task not found (404), clearing active_task_id"
548 );
549 should_clear_task_id = true;
550 state.last_task_status = Some("error".to_string());
551 } else {
552 tracing::warn!(
553 job_id = job.id,
554 task_id = task_id_clone,
555 ?e,
556 "transient error fetching active task, skipping tick (active_task_id preserved)"
557 );
558 should_skip = true;
559 }
560 false
561 }
562 }
563 } else {
564 if let Some(s) = store {
566 if let Ok(Some(store_id)) = s.resolve_task_id(repo, &task_id_clone).await {
567 match s.get(store_id).await {
568 Ok(task) => match task.status {
569 TaskStatus::New
570 | TaskStatus::Routed
571 | TaskStatus::InProgress
572 | TaskStatus::NeedsReview
573 | TaskStatus::InReview
574 | TaskStatus::Approved
575 | TaskStatus::Waiting => true,
576 _ => false, },
578 Err(e) => {
579 tracing::warn!(
580 job_id = job.id,
581 task_id = task_id_clone,
582 ?e,
583 "cannot fetch internal task from store, clearing active_task_id"
584 );
585 should_clear_task_id = true;
586 false
587 }
588 }
589 } else {
590 tracing::warn!(
591 job_id = job.id,
592 task_id = task_id_clone,
593 "internal task not found in store, clearing active_task_id"
594 );
595 should_clear_task_id = true;
596 false
597 }
598 } else {
599 should_clear_task_id = true;
600 false
601 }
602 };
603
604 if is_active {
605 tracing::debug!(
606 job_id = job.id,
607 task_id = task_id_clone,
608 external = job.external,
609 "skipping: previous task still active"
610 );
611 should_skip = true;
612 }
613 }
614
615 if should_clear_task_id {
617 state.active_task_id = None;
618 }
619
620 if should_skip {
621 continue;
622 }
623
624 tracing::info!(job_id = job.id, r#type = job.r#type, "job due, executing");
625
626 state.last_run = Some(now.format("%Y-%m-%dT%H:%M:%SZ").to_string());
631 if let Some(s) = store
632 && let Err(e) = s.upsert_job_state(&state).await
633 {
634 tracing::error!(
635 job_id = job.id,
636 ?e,
637 "failed to persist job state before execution — skipping this tick to preserve restart safety"
638 );
639 continue; }
641
642 let base_dir = jobs_path.parent().unwrap_or_else(|| Path::new("."));
644 execute_job(job, &mut state, backend, store, repo, transport, base_dir).await;
645
646 if let Some(s) = store
648 && let Err(e) = s.upsert_job_state(&state).await
649 {
650 tracing::error!(
651 job_id = job.id,
652 ?e,
653 "failed to persist job state after execution"
654 );
655 }
656 }
657
658 Ok(())
659}
660
661async fn run_bash(
663 cmd: &str,
664 dir: &str,
665 timeout: Duration,
666) -> result::Result<anyhow::Result<Output>, time::error::Elapsed> {
667 time::timeout(
668 timeout,
669 Command::new("bash")
670 .arg("-c")
671 .arg(cmd)
672 .current_dir(dir)
673 .kill_on_drop(true)
674 .output_with_context(),
675 )
676 .await
677}
678
679pub async fn execute_job(
684 job: &Job,
685 state: &mut JobState,
686 backend: &Arc<dyn ExternalBackend>,
687 store: Option<&Arc<TaskStore>>,
688 repo: &str,
689 transport: Option<&Arc<Transport>>,
690 base_dir: &Path,
691) {
692 match job.r#type.as_str() {
693 "task" => {
694 if let Some(ref template) = job.task {
695 let body = match resolve_template_body(template, base_dir) {
696 Ok(b) => b,
697 Err(e) => {
698 tracing::error!(job_id = job.id, ?e, "failed to resolve task body");
699 state.last_task_status = Some("failed".to_string());
700 return;
701 }
702 };
703
704 if job.external {
705 let mut labels = template.labels.clone();
706 labels.push("scheduled".to_string());
707 labels.push(format!("job:{}", job.id));
708
709 if let Some(ref agent) = template.agent
710 && !agent.is_empty()
711 {
712 labels.push(format!("agent:{agent}"));
713 }
714
715 match backend.create_task(&template.title, &body, &labels).await {
716 Ok(ext_id) => {
717 tracing::info!(
718 job_id = job.id,
719 task_id = ext_id.0,
720 "created external task"
721 );
722 state.active_task_id = Some(ext_id.0);
723 state.last_task_status = Some("new".to_string());
724 }
725 Err(e) => {
726 tracing::error!(job_id = job.id, ?e, "failed to create external task");
727 state.last_task_status = Some("failed".to_string());
728 }
729 }
730 } else if let Some(s) = store {
731 match s
732 .create_internal(repo, &template.title, &body, "cron", &job.id, None)
733 .await
734 {
735 Ok(internal_id) => {
736 let task_id = format!("internal:{internal_id}");
737 tracing::info!(job_id = job.id, task_id, "created internal task");
738 state.active_task_id = Some(task_id);
739 state.last_task_status = Some("new".to_string());
740 }
741 Err(e) => {
742 tracing::error!(job_id = job.id, ?e, "failed to create internal task");
743 state.last_task_status = Some("failed".to_string());
744 }
745 }
746 } else {
747 tracing::error!(
748 job_id = job.id,
749 "no store available for internal task creation"
750 );
751 state.last_task_status = Some("failed".to_string());
752 }
753 }
754 }
755 "bash" => {
756 if let Some(ref cmd) = job.command {
757 let dir = job.dir.as_deref().unwrap_or(".");
758 tracing::info!(job_id = job.id, cmd, dir, "running bash command");
759
760 let timeout_secs: u64 = config::get("jobs.bash_timeout_seconds")
764 .ok()
765 .and_then(|s| s.parse().ok())
766 .unwrap_or(300);
767 let timeout = Duration::from_secs(timeout_secs);
768
769 let output = run_bash(cmd, dir, timeout).await;
770
771 match output {
772 Ok(Ok(o)) if o.status.success() => {
773 state.last_task_status = Some("done".to_string());
774 }
775 Ok(Ok(o)) => {
776 let stderr = String::from_utf8_lossy(&o.stderr);
777 tracing::warn!(
778 job_id = job.id,
779 code = o.status.code(),
780 %stderr,
781 "bash command failed"
782 );
783 state.last_task_status = Some("failed".to_string());
784 }
785 Ok(Err(e)) => {
786 tracing::error!(job_id = job.id, ?e, "bash command error");
787 state.last_task_status = Some("failed".to_string());
788 }
789 Err(_) => {
790 tracing::error!(
791 job_id = job.id,
792 secs = timeout_secs,
793 "bash job timed out after {}s, child killed",
794 timeout_secs
795 );
796 state.last_task_status = Some("timeout".to_string());
797 }
798 }
799 }
800 }
801 other => {
807 tracing::warn!(job_id = job.id, r#type = other, "unknown job type");
808 }
809 }
810
811 if job.notify
813 && let Some(t) = transport
814 {
815 let status = state
816 .last_task_status
817 .as_deref()
818 .unwrap_or("unknown")
819 .to_string();
820 let summary = match status.as_str() {
821 "done" => format!("Job `{}` completed successfully.", job.id),
822 "failed" => format!("Job `{}` failed.", job.id),
823 "new" => format!("Job `{}` created a new task.", job.id),
824 other => format!("Job `{}` finished with status: {other}.", job.id),
825 };
826 let target = job
828 .notify_target
829 .clone()
830 .or_else(|| config::get("channels.telegram.chat_id").ok());
831 let notification = TaskNotification {
832 task_id: job.id.clone(),
833 title: format!("Job: {}", job.id),
834 status,
835 agent: "scheduler".to_string(),
836 duration_seconds: 0.0,
837 summary,
838 repo: Some(repo.to_string()),
839 notify_target: target,
840 pr_number: None,
841 };
842 t.push_notification(notification);
843 }
844}
845
846#[cfg(test)]
851mod tests {
852 use super::*;
853 use std::fs;
854 use std::process::Command as StdCommand;
855 use tempfile::tempdir;
856
857 fn write_config(dir: &Path, content: &str) -> PathBuf {
858 let path = dir.join(".orch.yml");
859 fs::write(&path, content).unwrap();
860 path
861 }
862
863 #[tokio::test]
864 async fn run_bash_timeout_kills_the_child() {
865 let tmp = tempdir().unwrap();
866 let pid_file = tmp.path().join("pid");
867 let cmd = format!("echo $$ > {}; exec sleep 60", pid_file.display());
868
869 let out = run_bash(&cmd, ".", Duration::from_secs(1)).await;
870 assert!(out.is_err(), "expected a timeout");
871
872 let pid = fs::read_to_string(&pid_file).unwrap().trim().to_string();
873 let mut gone = false;
874 for _ in 0..20 {
875 let alive = StdCommand::new("kill")
876 .args(["-0", &pid])
877 .output()
878 .unwrap()
879 .status
880 .success();
881 if !alive {
882 gone = true;
883 break;
884 }
885 time::sleep(Duration::from_millis(100)).await;
886 }
887 assert!(gone, "child {pid} still running after timeout");
888 }
889
890 #[test]
891 fn load_jobs_reads_prompt_from_file() {
892 let tmp = tempdir().unwrap();
893 fs::create_dir(tmp.path().join("prompts")).unwrap();
894 fs::write(tmp.path().join("prompts/hello.md"), "hello from file").unwrap();
895 let cfg = write_config(
896 tmp.path(),
897 r#"
898jobs:
899 - id: with-prompt
900 schedule: "0 9 * * *"
901 task:
902 title: "Daily"
903 prompt: prompts/hello.md
904"#,
905 );
906
907 let jobs = load_jobs(&cfg).unwrap();
908 assert_eq!(jobs.len(), 1);
909 let body = resolve_template_body(jobs[0].task.as_ref().unwrap(), tmp.path()).unwrap();
910 assert_eq!(body, "hello from file");
911 }
912
913 #[test]
914 fn load_jobs_rejects_both_body_and_prompt() {
915 let tmp = tempdir().unwrap();
916 fs::write(tmp.path().join("p.md"), "x").unwrap();
917 let cfg = write_config(
918 tmp.path(),
919 r#"
920jobs:
921 - id: conflict
922 schedule: "0 9 * * *"
923 task:
924 title: "x"
925 body: "inline"
926 prompt: p.md
927"#,
928 );
929
930 let err = load_jobs(&cfg).unwrap_err().to_string();
931 assert!(err.contains("not both"), "unexpected error: {err}");
932 }
933
934 #[test]
935 fn load_jobs_rejects_missing_prompt_file() {
936 let tmp = tempdir().unwrap();
937 let cfg = write_config(
938 tmp.path(),
939 r#"
940jobs:
941 - id: missing
942 schedule: "0 9 * * *"
943 task:
944 title: "x"
945 prompt: does-not-exist.md
946"#,
947 );
948
949 let err = load_jobs(&cfg).unwrap_err().to_string();
950 assert!(
951 err.contains("prompt file not found"),
952 "unexpected error: {err}"
953 );
954 }
955
956 #[test]
957 fn resolve_template_body_falls_back_to_inline_body() {
958 let tmp = tempdir().unwrap();
959 let template = TaskTemplate {
960 title: "t".to_string(),
961 body: "inline body".to_string(),
962 prompt: None,
963 labels: vec![],
964 agent: None,
965 };
966 assert_eq!(
967 resolve_template_body(&template, tmp.path()).unwrap(),
968 "inline body"
969 );
970 }
971
972 fn write_prompt_job(dir: &Path, name: &str, content: &str) {
973 let jobs_dir = dir.join("prompts").join("jobs");
974 fs::create_dir_all(&jobs_dir).unwrap();
975 fs::write(jobs_dir.join(name), content).unwrap();
976 }
977
978 #[test]
979 fn scan_prompt_jobs_picks_up_frontmatter_files() {
980 let tmp = tempdir().unwrap();
981 write_prompt_job(
982 tmp.path(),
983 "morning.md",
984 "---\nid: morning\nschedule: '0 9 * * *'\ntitle: Morning\nlabels: [daily]\nagent: claude\n---\n\nDo morning stuff.\n",
985 );
986 let jobs = scan_prompt_jobs(tmp.path()).unwrap();
987 assert_eq!(jobs.len(), 1);
988 assert_eq!(jobs[0].id, "morning");
989 assert_eq!(jobs[0].schedule, "0 9 * * *");
990 let task = jobs[0].task.as_ref().unwrap();
991 assert_eq!(task.title, "Morning");
992 assert_eq!(task.body, "Do morning stuff.\n");
993 assert_eq!(task.labels, vec!["daily".to_string()]);
994 assert_eq!(task.agent.as_deref(), Some("claude"));
995 }
996
997 #[test]
998 fn load_jobs_merges_inline_and_scanned() {
999 let tmp = tempdir().unwrap();
1000 write_prompt_job(
1001 tmp.path(),
1002 "scanned.md",
1003 "---\nid: scanned\nschedule: '0 9 * * *'\ntitle: Scanned\n---\n\nbody\n",
1004 );
1005 let cfg = write_config(
1006 tmp.path(),
1007 r#"
1008jobs:
1009 - id: inline
1010 schedule: "0 10 * * *"
1011 task:
1012 title: "Inline"
1013 body: "x"
1014"#,
1015 );
1016 let jobs = load_jobs(&cfg).unwrap();
1017 let ids: Vec<&str> = jobs.iter().map(|j| j.id.as_str()).collect();
1018 assert!(ids.contains(&"inline"));
1019 assert!(ids.contains(&"scanned"));
1020 assert_eq!(jobs.len(), 2);
1021 }
1022
1023 #[test]
1024 fn load_jobs_rejects_duplicate_id_across_sources() {
1025 let tmp = tempdir().unwrap();
1026 write_prompt_job(
1027 tmp.path(),
1028 "dup.md",
1029 "---\nid: dup\nschedule: '0 9 * * *'\ntitle: Dup\n---\n\nbody\n",
1030 );
1031 let cfg = write_config(
1032 tmp.path(),
1033 r#"
1034jobs:
1035 - id: dup
1036 schedule: "0 10 * * *"
1037 task:
1038 title: "Dup inline"
1039 body: "x"
1040"#,
1041 );
1042 let err = load_jobs(&cfg).unwrap_err().to_string();
1043 assert!(err.contains("duplicate job id"), "unexpected error: {err}");
1044 }
1045
1046 #[test]
1047 fn scan_prompt_jobs_ignores_files_without_frontmatter() {
1048 let tmp = tempdir().unwrap();
1049 write_prompt_job(
1050 tmp.path(),
1051 "plain.md",
1052 "just a prompt body, no frontmatter\n",
1053 );
1054 let jobs = scan_prompt_jobs(tmp.path()).unwrap();
1055 assert_eq!(jobs.len(), 0);
1056 }
1057
1058 #[test]
1059 fn load_jobs_works_without_config_file_when_directory_present() {
1060 let tmp = tempdir().unwrap();
1061 write_prompt_job(
1062 tmp.path(),
1063 "solo.md",
1064 "---\nid: solo\nschedule: '0 9 * * *'\ntitle: Solo\n---\n\nbody\n",
1065 );
1066 let missing_cfg = tmp.path().join(".orch.yml");
1067 let jobs = load_jobs(&missing_cfg).unwrap();
1068 assert_eq!(jobs.len(), 1);
1069 assert_eq!(jobs[0].id, "solo");
1070 }
1071
1072 #[test]
1075 fn scan_prompt_jobs_respects_enabled_false() {
1076 let tmp = tempdir().unwrap();
1077 write_prompt_job(
1078 tmp.path(),
1079 "disabled.md",
1080 "---\nid: disabled\nschedule: '0 9 * * *'\ntitle: Disabled\nenabled: false\n---\n\nbody\n",
1081 );
1082 let jobs = scan_prompt_jobs(tmp.path()).unwrap();
1083 assert_eq!(jobs.len(), 1);
1084 assert!(!jobs[0].enabled, "job should be disabled via frontmatter");
1085 }
1086
1087 #[test]
1088 fn scan_prompt_jobs_sets_prompt_file() {
1089 let tmp = tempdir().unwrap();
1090 write_prompt_job(
1091 tmp.path(),
1092 "morning.md",
1093 "---\nid: morning\nschedule: '0 9 * * *'\ntitle: Morning\n---\n\nbody\n",
1094 );
1095 let jobs = scan_prompt_jobs(tmp.path()).unwrap();
1096 assert_eq!(jobs.len(), 1);
1097 assert!(
1098 jobs[0].prompt_file.is_some(),
1099 "prompt_file should be set for frontmatter jobs"
1100 );
1101 }
1102
1103 #[test]
1104 fn save_jobs_does_not_persist_prompt_based_jobs() {
1105 let tmp = tempdir().unwrap();
1106 write_prompt_job(
1108 tmp.path(),
1109 "prompt.md",
1110 "---\nid: from-prompt\nschedule: '0 9 * * *'\ntitle: Prompt Job\n---\n\nbody\n",
1111 );
1112 let cfg = write_config(
1114 tmp.path(),
1115 "jobs:\n - id: inline\n schedule: \"0 10 * * *\"\n task:\n title: Inline\n body: x\n",
1116 );
1117 let jobs = load_jobs(&cfg).unwrap();
1118 assert_eq!(jobs.len(), 2);
1119
1120 save_jobs(&cfg, &jobs).unwrap();
1122
1123 let saved = load_jobs(&cfg).unwrap();
1124 assert_eq!(saved.len(), 2, "both jobs should still be loadable");
1125 let ids: Vec<&str> = saved.iter().map(|j| j.id.as_str()).collect();
1126 assert!(ids.contains(&"inline"));
1127 assert!(ids.contains(&"from-prompt"));
1128 }
1129
1130 #[test]
1131 fn rewrite_frontmatter_enabled_replaces_existing_value() {
1132 let input = "---\nid: foo\nschedule: daily\nenabled: true\ntitle: Foo\n---\n\nbody\n";
1133 let out = rewrite_frontmatter_enabled(input, "false");
1134 assert!(
1135 out.contains("enabled: false"),
1136 "should replace enabled: true"
1137 );
1138 assert!(!out.contains("enabled: true"), "old value must be gone");
1139 assert!(out.contains("body"), "body must be preserved");
1140 }
1141
1142 #[test]
1143 fn rewrite_frontmatter_enabled_inserts_when_absent() {
1144 let input = "---\nid: foo\nschedule: daily\ntitle: Foo\n---\n\nbody\n";
1145 let out = rewrite_frontmatter_enabled(input, "false");
1146 assert!(
1147 out.contains("enabled: false"),
1148 "should insert enabled: false"
1149 );
1150 assert!(out.contains("body"), "body must be preserved");
1151 }
1152
1153 #[test]
1154 fn set_frontmatter_enabled_writes_file() {
1155 let tmp = tempdir().unwrap();
1156 let path = tmp.path().join("job.md");
1157 fs::write(
1158 &path,
1159 "---\nid: foo\nschedule: daily\ntitle: Foo\nenabled: true\n---\n\nbody\n",
1160 )
1161 .unwrap();
1162 set_frontmatter_enabled(&path, false).unwrap();
1163 let content = fs::read_to_string(&path).unwrap();
1164 assert!(content.contains("enabled: false"));
1165 assert!(!content.contains("enabled: true"));
1166 }
1167}