返回 CodeWhale
automation_manager.rs
根目录 / crates / engine / src / automation_manager.rs
1 //! Durable automation records and scheduler support.
2 //!
3 //! Automations are local-first recurring jobs that enqueue standard background
4 //! tasks. This module stores automation definitions and run history under
5 //! `~/.codewhale/automations` (or `DEEPSEEK_AUTOMATIONS_DIR` override).
6 //!
7 //! Deleting an automation keeps its terminal run history: terminal runs
8 //! (completed, failed, canceled) are moved under `<root>/archive/<id>/` before
9 //! the live paths are removed. The archive is bounded — it retains the most
10 //! recent [`ARCHIVE_RETAINED_TERMINAL_RUNS`] terminal runs per automation and
11 //! deletes older ones — and lives outside the `automations/`, `runs/`, and
12 //! `triggers/` trees, so live listings and scheduler scans never see it.
13
14 use std::collections::BTreeMap;
15 use std::fs;
16 use std::future::Future;
17 use std::path::{Path, PathBuf};
18 use std::sync::Arc;
19
20 use anyhow::{Context, Result, bail};
21 use chrono::{
22 DateTime, Datelike, Duration, Local, NaiveDateTime, TimeZone, Timelike, Utc, Weekday,
23 };
24 use serde::{Deserialize, Serialize};
25 use tokio::sync::{Mutex, Notify};
26 use tokio::time::sleep;
27 use tokio_util::sync::CancellationToken;
28 use uuid::Uuid;
29
30 use crate::task_manager::{NewTaskRequest, SharedTaskManager, TaskStatus};
31 use codewhale_util::utils::spawn_supervised;
32
33 #[derive(Clone)]
34 pub struct ThreadEventSink(pub Arc<dyn Fn(String, &'static str, serde_json::Value) + Send + Sync>);
35
36 impl std::fmt::Debug for ThreadEventSink {
37 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38 f.write_str("ThreadEventSink")
39 }
40 }
41
42 /// Current automation record schema. `pub` so the Operate keepalive
43 /// can build a fixed-id record directly (no create/delete id swap).
44 // v2 pins provider identity. Older runtimes must reject a pinned definition
45 // instead of silently sending its model through their current provider.
46 pub const CURRENT_AUTOMATION_SCHEMA_VERSION: u32 = 3;
47 const DENY_RULES_AUTOMATION_SCHEMA_VERSION: u32 = 4;
48 const MAX_SUPPORTED_AUTOMATION_SCHEMA_VERSION: u32 = DENY_RULES_AUTOMATION_SCHEMA_VERSION;
49 const CURRENT_RUN_SCHEMA_VERSION: u32 = 3;
50 const DENY_RULES_RUN_SCHEMA_VERSION: u32 = 4;
51 const MAX_SUPPORTED_RUN_SCHEMA_VERSION: u32 = DENY_RULES_RUN_SCHEMA_VERSION;
52 const CURRENT_TRIGGER_SCHEMA_VERSION: u32 = 3;
53 const DENY_RULES_TRIGGER_SCHEMA_VERSION: u32 = 4;
54 const MAX_SUPPORTED_TRIGGER_SCHEMA_VERSION: u32 = DENY_RULES_TRIGGER_SCHEMA_VERSION;
55
56 pub const fn required_automation_schema_version(disallowed_tools: &[String]) -> u32 {
57 if disallowed_tools.is_empty() {
58 CURRENT_AUTOMATION_SCHEMA_VERSION
59 } else {
60 DENY_RULES_AUTOMATION_SCHEMA_VERSION
61 }
62 }
63
64 const fn required_run_schema_version(dispatch: Option<&AutomationDispatch>) -> u32 {
65 match dispatch {
66 Some(dispatch) if !dispatch.request.disallowed_tools.is_empty() => {
67 DENY_RULES_RUN_SCHEMA_VERSION
68 }
69 _ => CURRENT_RUN_SCHEMA_VERSION,
70 }
71 }
72
73 const fn required_trigger_schema_version(record: &DelayedTriggerRecord) -> u32 {
74 let dispatch_denied = match &record.dispatch {
75 Some(dispatch) => !dispatch.request.disallowed_tools.is_empty(),
76 None => false,
77 };
78 if record.disallowed_tools.is_empty() && !dispatch_denied {
79 CURRENT_TRIGGER_SCHEMA_VERSION
80 } else {
81 DENY_RULES_TRIGGER_SCHEMA_VERSION
82 }
83 }
84 const DEFAULT_AUTOMATION_MODE: &str = "agent";
85 const DEFAULT_AUTOMATION_ALLOW_SHELL: bool = false;
86 const DEFAULT_AUTOMATION_TRUST_MODE: bool = false;
87 const DEFAULT_AUTOMATION_AUTO_APPROVE: bool = false;
88 const DEFAULT_AUTOMATION_DELIVERY_MODE: AutomationDeliveryMode = AutomationDeliveryMode::Task;
89 pub const ELEVATED_AUTOMATION_PAUSE_REASON: &str = "Scheduled automations cannot run with Full Access, trust or shell. Remove those settings, then resume it.";
90 const ELEVATED_AUTOMATION_RUN_REFUSAL: &str = "Refused by the scheduler: this automation has Full Access, trust or shell turned on, which scheduled automations cannot use. Remove those settings, then resume it.";
91 /// Terminal runs retained in `<root>/archive/<automation_id>/` when an
92 /// automation is deleted; older archived runs are removed (newest-first by
93 /// `ended_at`, falling back to `created_at`).
94 const ARCHIVE_RETAINED_TERMINAL_RUNS: usize = 50;
95 pub const AUTOMATION_WATCHER_NO_REPORT_SENTINEL: &str = "NOTHING_TO_REPORT";
96 const MAX_HOURLY_SEARCH_STEPS: usize = 24 * 21;
97 const MAX_CRON_SEARCH_MINUTES: usize = 60 * 24 * 366 * 5;
98 const fn default_automation_schema_version() -> u32 {
99 CURRENT_AUTOMATION_SCHEMA_VERSION
100 }
101
102 const fn default_run_schema_version() -> u32 {
103 CURRENT_RUN_SCHEMA_VERSION
104 }
105
106 const fn default_trigger_schema_version() -> u32 {
107 CURRENT_TRIGGER_SCHEMA_VERSION
108 }
109
110 // ── Delayed-trigger types ──────────────────────────────────────────────────
111
112 /// Status of a one-shot delayed trigger.
113 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
114 #[serde(rename_all = "snake_case")]
115 pub enum DelayedTriggerStatus {
116 /// Waiting to fire.
117 Pending,
118 /// Durable admission owns this trigger; task acceptance is being recovered.
119 Dispatching,
120 /// The trigger was fired and a task was enqueued.
121 Fired,
122 /// The trigger was explicitly canceled before it fired.
123 Canceled,
124 /// The trigger fired but failed to enqueue a task.
125 Failed,
126 }
127
128 /// A durable one-shot delayed continuation record.
129 ///
130 /// Stored under `~/.codewhale/automations/triggers/{trigger_id}.json`.
131 #[derive(Debug, Clone, Serialize, Deserialize)]
132 pub struct DelayedTriggerRecord {
133 #[serde(default = "default_trigger_schema_version")]
134 pub schema_version: u32,
135 pub trigger_id: String,
136 /// Absolute UTC time at which the trigger should fire.
137 pub fire_at: DateTime<Utc>,
138 /// The message that will be submitted as a new task when the trigger fires.
139 pub message: String,
140 /// Working directory for the task that fires when the trigger trips.
141 #[serde(skip_serializing_if = "Option::is_none")]
142 pub workspace: Option<PathBuf>,
143 /// Session that scheduled this trigger. Missing legacy ownership fails closed.
144 #[serde(default, skip_serializing_if = "Option::is_none")]
145 pub owner_session_id: Option<String>,
146 #[serde(default, skip_serializing_if = "Option::is_none")]
147 pub destination_thread_id: Option<String>,
148 #[serde(default, skip_serializing_if = "Vec::is_empty")]
149 pub disallowed_tools: Vec<String>,
150 pub status: DelayedTriggerStatus,
151 pub created_at: DateTime<Utc>,
152 #[serde(skip_serializing_if = "Option::is_none")]
153 pub fired_at: Option<DateTime<Utc>>,
154 #[serde(skip_serializing_if = "Option::is_none")]
155 pub task_id: Option<String>,
156 #[serde(skip_serializing_if = "Option::is_none")]
157 pub thread_id: Option<String>,
158 #[serde(skip_serializing_if = "Option::is_none")]
159 pub error: Option<String>,
160 /// Optional lineage: the trigger id that scheduled this one (for re-arm chains).
161 #[serde(skip_serializing_if = "Option::is_none")]
162 pub parent_trigger_id: Option<String>,
163 #[serde(default, skip_serializing_if = "Option::is_none")]
164 pub dispatch: Option<AutomationDispatch>,
165 /// Bound by the trusted service, independently of visibility ownership.
166 #[serde(default, skip_serializing_if = "Option::is_none")]
167 pub execution_scope: Option<String>,
168 }
169
170 /// Input for creating a new delayed trigger.
171 #[derive(Debug, Clone)]
172 pub struct CreateDelayedTriggerRequest {
173 /// Absolute fire time. Callers must resolve `delay_minutes` → `fire_at`
174 /// before calling this function.
175 pub fire_at: DateTime<Utc>,
176 /// Message to submit as a new task when the trigger fires.
177 pub message: String,
178 /// Optional workspace directory for the fired task.
179 pub workspace: Option<PathBuf>,
180 /// Session that owns controls and the task created when this trigger fires.
181 pub owner_session_id: Option<String>,
182 /// Optional parent trigger id for re-arm lineage tracking.
183 pub parent_trigger_id: Option<String>,
184 pub destination_thread_id: Option<String>,
185 pub disallowed_tools: Vec<String>,
186 }
187
188 // ── End delayed-trigger types ──────────────────────────────────────────────
189
190 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
191 #[serde(rename_all = "snake_case")]
192 pub enum AutomationStatus {
193 Active,
194 Paused,
195 }
196
197 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
198 #[serde(rename_all = "snake_case")]
199 pub enum AutomationRunStatus {
200 Queued,
201 Running,
202 Completed,
203 Failed,
204 Canceled,
205 }
206
207 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
208 #[serde(rename_all = "snake_case")]
209 pub enum AutomationDeliveryMode {
210 #[default]
211 Task,
212 Watcher,
213 }
214
215 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
216 #[serde(rename_all = "snake_case")]
217 pub enum AutomationMissedPolicy {
218 Ask,
219 RunOnce,
220 Skip,
221 }
222
223 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
224 #[serde(rename_all = "snake_case")]
225 pub enum MissedRunDecision {
226 RunNow,
227 Skip,
228 }
229
230 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
231 #[serde(rename_all = "snake_case")]
232 pub enum MissedRunOutcomeKind {
233 Ran,
234 Skipped,
235 }
236
237 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
238 #[serde(rename_all = "snake_case")]
239 pub enum MissedRunDecider {
240 Person,
241 Policy,
242 }
243
244 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
245 pub struct OwedOccurrence {
246 pub due_at: DateTime<Utc>,
247 pub detected_at: DateTime<Utc>,
248 }
249
250 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
251 pub struct MissedRunOutcome {
252 pub due_at: DateTime<Utc>,
253 pub decided_at: DateTime<Utc>,
254 pub outcome: MissedRunOutcomeKind,
255 pub decided_by: MissedRunDecider,
256 #[serde(default, skip_serializing_if = "Option::is_none")]
257 pub run_id: Option<String>,
258 }
259
260 #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
261 struct AutomationMissedState {
262 #[serde(default, skip_serializing_if = "Option::is_none")]
263 policy: Option<AutomationMissedPolicy>,
264 #[serde(default, skip_serializing_if = "Option::is_none")]
265 owed: Option<OwedOccurrence>,
266 #[serde(default)]
267 outcomes: Vec<MissedRunOutcome>,
268 }
269
270 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
271 pub struct AutomationMissedStatus {
272 pub automation_id: String,
273 pub name: String,
274 pub policy: AutomationMissedPolicy,
275 pub policy_is_default: bool,
276 #[serde(default, skip_serializing_if = "Option::is_none")]
277 pub owed: Option<OwedOccurrence>,
278 #[serde(default)]
279 pub outcomes: Vec<MissedRunOutcome>,
280 }
281
282 #[derive(Debug, Clone, Serialize)]
283 pub struct MissedRunResolution {
284 pub status: AutomationMissedStatus,
285 #[serde(skip_serializing_if = "Option::is_none")]
286 pub run: Option<AutomationRunRecord>,
287 }
288
289 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
290 struct SchedulerPresence {
291 awake_since: DateTime<Utc>,
292 last_tick: DateTime<Utc>,
293 }
294
295 const MISSED_OUTCOMES_RETAINED: usize = 20;
296 const SCHEDULER_PRESENCE_FILE: &str = "scheduler-presence.json";
297 const SCHEDULER_PRESENCE_MIN_GRACE_SECS: i64 = 120;
298
299 fn default_missed_policy(automation: &AutomationRecord) -> AutomationMissedPolicy {
300 if automation.task_mode() == "operate" {
301 AutomationMissedPolicy::RunOnce
302 } else {
303 AutomationMissedPolicy::Ask
304 }
305 }
306
307 enum DueDisposition {
308 Due,
309 Held,
310 }
311
312 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
313 pub struct AutomationRecord {
314 #[serde(default = "default_automation_schema_version")]
315 pub schema_version: u32,
316 pub id: String,
317 pub name: String,
318 pub prompt: String,
319 pub rrule: String,
320 #[serde(default)]
321 pub cwds: Vec<PathBuf>,
322 #[serde(default, skip_serializing_if = "Option::is_none")]
323 pub model: Option<String>,
324 /// Exact provider provenance for a pinned model; absent on legacy records.
325 #[serde(default, skip_serializing_if = "Option::is_none")]
326 pub model_provider: Option<String>,
327 #[serde(default, skip_serializing_if = "Option::is_none")]
328 pub model_provider_id: Option<String>,
329 #[serde(default, skip_serializing_if = "Option::is_none")]
330 pub mode: Option<String>,
331 #[serde(default, skip_serializing_if = "Option::is_none")]
332 pub allow_shell: Option<bool>,
333 #[serde(default, skip_serializing_if = "Option::is_none")]
334 pub trust_mode: Option<bool>,
335 #[serde(default, skip_serializing_if = "Option::is_none")]
336 pub auto_approve: Option<bool>,
337 #[serde(default, skip_serializing_if = "Option::is_none")]
338 pub delivery_mode: Option<AutomationDeliveryMode>,
339 #[serde(default, skip_serializing_if = "Option::is_none")]
340 pub destination_thread_id: Option<String>,
341 #[serde(default, skip_serializing_if = "Vec::is_empty")]
342 pub disallowed_tools: Vec<String>,
343 pub status: AutomationStatus,
344 pub created_at: DateTime<Utc>,
345 pub updated_at: DateTime<Utc>,
346 #[serde(skip_serializing_if = "Option::is_none")]
347 pub next_run_at: Option<DateTime<Utc>>,
348 #[serde(skip_serializing_if = "Option::is_none")]
349 pub last_run_at: Option<DateTime<Utc>>,
350 /// Bound by the trusted service, independently of visibility ownership.
351 #[serde(default, skip_serializing_if = "Option::is_none")]
352 pub execution_scope: Option<String>,
353 /// Increments on every definition mutation; absent on legacy records (0).
354 #[serde(default)]
355 pub revision: u64,
356 }
357
358 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
359 #[serde(rename_all = "snake_case")]
360 pub enum AutomationExecutionOwnership {
361 Owned,
362 OtherRuntime,
363 Unbound,
364 HostUnattached,
365 }
366
367 #[derive(Debug, Clone, Serialize)]
368 pub struct AutomationRecordView {
369 #[serde(flatten)]
370 pub record: AutomationRecord,
371 pub scheduled_here: bool,
372 pub execution_ownership: AutomationExecutionOwnership,
373 #[serde(skip_serializing_if = "Option::is_none")]
374 pub paused_reason: Option<&'static str>,
375 }
376
377 impl AutomationRecord {
378 fn task_mode(&self) -> String {
379 self.mode
380 .as_deref()
381 .map(str::trim)
382 .filter(|mode| !mode.is_empty())
383 .unwrap_or(DEFAULT_AUTOMATION_MODE)
384 .to_string()
385 }
386
387 fn task_allow_shell(&self) -> bool {
388 self.allow_shell.unwrap_or(DEFAULT_AUTOMATION_ALLOW_SHELL)
389 }
390
391 fn task_trust_mode(&self) -> bool {
392 self.trust_mode.unwrap_or(DEFAULT_AUTOMATION_TRUST_MODE)
393 }
394
395 fn task_auto_approve(&self) -> bool {
396 self.auto_approve.unwrap_or(DEFAULT_AUTOMATION_AUTO_APPROVE)
397 }
398
399 fn delivery_mode(&self) -> AutomationDeliveryMode {
400 self.delivery_mode
401 .unwrap_or(DEFAULT_AUTOMATION_DELIVERY_MODE)
402 }
403
404 pub fn elevated_pause_reason(&self) -> Option<&'static str> {
405 unattended_elevated(&automation_task_request(self))
406 .then_some(ELEVATED_AUTOMATION_PAUSE_REASON)
407 }
408
409 fn pause_for_elevated_permissions(&mut self) {
410 self.status = AutomationStatus::Paused;
411 self.next_run_at = None;
412 }
413 }
414
415 #[derive(Debug, Clone, Serialize, Deserialize)]
416 pub struct AutomationRunRecord {
417 #[serde(default = "default_run_schema_version")]
418 pub schema_version: u32,
419 pub id: String,
420 pub automation_id: String,
421 pub scheduled_for: DateTime<Utc>,
422 pub status: AutomationRunStatus,
423 pub created_at: DateTime<Utc>,
424 #[serde(skip_serializing_if = "Option::is_none")]
425 pub started_at: Option<DateTime<Utc>>,
426 #[serde(skip_serializing_if = "Option::is_none")]
427 pub ended_at: Option<DateTime<Utc>>,
428 #[serde(skip_serializing_if = "Option::is_none")]
429 pub task_id: Option<String>,
430 #[serde(skip_serializing_if = "Option::is_none")]
431 pub thread_id: Option<String>,
432 #[serde(skip_serializing_if = "Option::is_none")]
433 pub turn_id: Option<String>,
434 #[serde(skip_serializing_if = "Option::is_none")]
435 pub error: Option<String>,
436 #[serde(default, skip_serializing_if = "Option::is_none")]
437 pub dispatch: Option<AutomationDispatch>,
438 }
439
440 /// Immutable request and store bound to a durable occurrence before enqueue.
441 /// `accepted` records task promotion, not provider execution or completion.
442 #[derive(Debug, Clone, Serialize, Deserialize)]
443 pub struct AutomationDispatch {
444 #[serde(default, skip_serializing_if = "Option::is_none")]
445 execution_scope: Option<String>,
446 request: NewTaskRequest,
447 task_data_dir: PathBuf,
448 #[serde(default)]
449 accepted: bool,
450 #[serde(default)]
451 delivery_mode: AutomationDeliveryMode,
452 #[serde(default)]
453 suppress_report: bool,
454 #[serde(default, skip_serializing_if = "Option::is_none")]
455 schedule: Option<AdmittedSchedule>,
456 }
457
458 #[derive(Debug, Clone, Serialize, Deserialize)]
459 struct AdmittedSchedule {
460 updated_at: DateTime<Utc>,
461 rrule: String,
462 }
463
464 #[derive(Debug, Clone, Serialize, Deserialize)]
465 pub struct CreateAutomationRequest {
466 pub name: String,
467 pub prompt: String,
468 pub rrule: String,
469 #[serde(default)]
470 pub cwds: Vec<PathBuf>,
471 #[serde(default)]
472 pub model: Option<String>,
473 #[serde(default)]
474 pub model_provider: Option<String>,
475 #[serde(default)]
476 pub model_provider_id: Option<String>,
477 #[serde(default)]
478 pub mode: Option<String>,
479 #[serde(default)]
480 pub allow_shell: Option<bool>,
481 #[serde(default)]
482 pub trust_mode: Option<bool>,
483 #[serde(default)]
484 pub auto_approve: Option<bool>,
485 #[serde(default)]
486 pub delivery_mode: Option<AutomationDeliveryMode>,
487 #[serde(default, skip_serializing_if = "Option::is_none")]
488 pub destination_thread_id: Option<String>,
489 #[serde(default, skip_serializing_if = "Vec::is_empty")]
490 pub disallowed_tools: Vec<String>,
491 #[serde(default)]
492 pub status: Option<AutomationStatus>,
493 }
494
495 #[derive(Debug, Clone, Serialize, Deserialize, Default)]
496 pub struct UpdateAutomationRequest {
497 pub name: Option<String>,
498 pub prompt: Option<String>,
499 pub rrule: Option<String>,
500 pub cwds: Option<Vec<PathBuf>>,
501 pub model: Option<String>,
502 pub model_provider: Option<String>,
503 pub model_provider_id: Option<String>,
504 pub mode: Option<String>,
505 pub allow_shell: Option<bool>,
506 pub trust_mode: Option<bool>,
507 pub auto_approve: Option<bool>,
508 pub delivery_mode: Option<AutomationDeliveryMode>,
509 #[serde(default, skip_serializing_if = "Option::is_none")]
510 pub destination_thread_id: Option<String>,
511 pub status: Option<AutomationStatus>,
512 #[serde(default, skip_serializing_if = "Option::is_none")]
513 pub expected_revision: Option<u64>,
514 }
515
516 #[derive(Debug)]
517 pub struct RevisionConflict {
518 pub current: u64,
519 }
520
521 impl std::fmt::Display for RevisionConflict {
522 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
523 write!(
524 f,
525 "Automation revision conflict: current revision is {}",
526 self.current
527 )
528 }
529 }
530
531 impl std::error::Error for RevisionConflict {}
532
533 fn check_expected_revision(record: &AutomationRecord, expected: Option<u64>) -> Result<()> {
534 match expected {
535 Some(expected) if expected != record.revision => Err(RevisionConflict {
536 current: record.revision,
537 }
538 .into()),
539 _ => Ok(()),
540 }
541 }
542
543 pub const IDEMPOTENCY_TTL_HOURS: i64 = 24;
544 pub const IDEMPOTENCY_MAX_ENTRIES: usize = 1024;
545
546 #[derive(Debug, Clone, Serialize, Deserialize)]
547 struct IdempotencyEntry {
548 key: String,
549 fingerprint: String,
550 status: u16,
551 body: serde_json::Value,
552 created_at: DateTime<Utc>,
553 }
554
555 #[derive(Debug)]
556 pub enum IdempotencyLookup {
557 Miss,
558 Replay {
559 status: u16,
560 body: serde_json::Value,
561 },
562 KeyReused,
563 }
564
565 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
566 enum AutomationFrequency {
567 Hourly,
568 Weekly,
569 }
570
571 #[derive(Debug, Clone)]
572 pub enum AutomationSchedule {
573 Once {
574 at: DateTime<Utc>,
575 },
576 Hourly {
577 interval_hours: u32,
578 byday: Option<Vec<Weekday>>,
579 anchor_hour: Option<u32>,
580 anchor_minute: Option<u32>,
581 },
582 Weekly {
583 byday: Vec<Weekday>,
584 byhour: u32,
585 byminute: u32,
586 },
587 Cron {
588 expr: String,
589 },
590 }
591
592 impl AutomationSchedule {
593 pub fn parse_rrule(rrule: &str) -> Result<Self> {
594 let mut parts: BTreeMap<String, String> = BTreeMap::new();
595 for raw in rrule.split(';') {
596 let item = raw.trim();
597 if item.is_empty() {
598 continue;
599 }
600 let Some((k, v)) = item.split_once('=') else {
601 bail!("Invalid RRULE segment '{item}'");
602 };
603 parts.insert(k.trim().to_ascii_uppercase(), v.trim().to_string());
604 }
605
606 let freq = match parts
607 .get("FREQ")
608 .map(|value| value.trim().to_ascii_uppercase())
609 .as_deref()
610 {
611 Some("ONCE") => return parse_once_schedule(&parts),
612 Some("HOURLY") => AutomationFrequency::Hourly,
613 Some("WEEKLY") => AutomationFrequency::Weekly,
614 Some("CRON") => return parse_cron_schedule(&parts),
615 Some(other) => {
616 bail!("Unsupported RRULE FREQ '{other}'. Supported: ONCE, HOURLY, WEEKLY, and CRON")
617 }
618 None => bail!("RRULE must include FREQ"),
619 };
620
621 match freq {
622 AutomationFrequency::Hourly => {
623 for key in parts.keys() {
624 if key != "FREQ"
625 && key != "INTERVAL"
626 && key != "BYDAY"
627 && key != "BYHOUR"
628 && key != "BYMINUTE"
629 {
630 bail!(
631 "Unsupported RRULE field '{key}' for HOURLY. Allowed: FREQ,INTERVAL,BYDAY,BYHOUR,BYMINUTE"
632 );
633 }
634 }
635 let interval_hours = parts
636 .get("INTERVAL")
637 .map(|v| v.parse::<u32>())
638 .transpose()
639 .context("Failed to parse INTERVAL")?
640 .unwrap_or(1);
641 if interval_hours == 0 {
642 bail!("INTERVAL must be >= 1 for HOURLY schedules");
643 }
644 let byday = parts
645 .get("BYDAY")
646 .map(|value| parse_byday(&value.to_ascii_uppercase()))
647 .transpose()?;
648 let anchor_hour = parts
649 .get("BYHOUR")
650 .map(|value| value.parse::<u32>())
651 .transpose()
652 .context("Failed to parse BYHOUR")?;
653 let anchor_minute = parts
654 .get("BYMINUTE")
655 .map(|value| value.parse::<u32>())
656 .transpose()
657 .context("Failed to parse BYMINUTE")?;
658 if anchor_hour.is_some_and(|hour| hour > 23) {
659 bail!("BYHOUR must be between 0 and 23");
660 }
661 if anchor_minute.is_some_and(|minute| minute > 59) {
662 bail!("BYMINUTE must be between 0 and 59");
663 }
664 Ok(Self::Hourly {
665 interval_hours,
666 byday,
667 anchor_hour,
668 anchor_minute,
669 })
670 }
671 AutomationFrequency::Weekly => {
672 for key in parts.keys() {
673 if key != "FREQ" && key != "BYDAY" && key != "BYHOUR" && key != "BYMINUTE" {
674 bail!(
675 "Unsupported RRULE field '{key}' for WEEKLY. Allowed: FREQ,BYDAY,BYHOUR,BYMINUTE"
676 );
677 }
678 }
679 let byday_raw = parts
680 .get("BYDAY")
681 .ok_or_else(|| anyhow::anyhow!("WEEKLY schedules require BYDAY"))?;
682 let byday = parse_byday(&byday_raw.to_ascii_uppercase())?;
683 if byday.is_empty() {
684 bail!("BYDAY cannot be empty for WEEKLY schedules");
685 }
686 let byhour = parts
687 .get("BYHOUR")
688 .ok_or_else(|| anyhow::anyhow!("WEEKLY schedules require BYHOUR"))?
689 .parse::<u32>()
690 .context("Failed to parse BYHOUR")?;
691 let byminute = parts
692 .get("BYMINUTE")
693 .ok_or_else(|| anyhow::anyhow!("WEEKLY schedules require BYMINUTE"))?
694 .parse::<u32>()
695 .context("Failed to parse BYMINUTE")?;
696
697 if byhour > 23 {
698 bail!("BYHOUR must be between 0 and 23");
699 }
700 if byminute > 59 {
701 bail!("BYMINUTE must be between 0 and 59");
702 }
703
704 Ok(Self::Weekly {
705 byday,
706 byhour,
707 byminute,
708 })
709 }
710 }
711 }
712
713 pub fn next_after_with_anchor(
714 &self,
715 after: DateTime<Utc>,
716 anchor_reference: DateTime<Utc>,
717 ) -> Result<DateTime<Utc>> {
718 self.next_after_in_timezone(after, anchor_reference, &Local)
719 }
720
721 fn next_after_in_timezone<Tz: TimeZone>(
722 &self,
723 after: DateTime<Utc>,
724 anchor_reference: DateTime<Utc>,
725 timezone: &Tz,
726 ) -> Result<DateTime<Utc>> {
727 let local_after = after.with_timezone(timezone);
728 match self {
729 Self::Once { at } => {
730 if *at > after {
731 Ok(*at)
732 } else {
733 bail!(
734 "Once schedule has no future run after {}",
735 after.to_rfc3339()
736 )
737 }
738 }
739 Self::Hourly {
740 interval_hours,
741 byday,
742 anchor_hour,
743 anchor_minute,
744 } => {
745 if anchor_hour.is_some() || anchor_minute.is_some() {
746 let local_anchor_reference = anchor_reference.with_timezone(timezone);
747 let hour = anchor_hour.unwrap_or(local_anchor_reference.hour());
748 let minute = anchor_minute.unwrap_or(0);
749 let anchor_naive = local_anchor_reference
750 .date_naive()
751 .and_hms_opt(hour, minute, 0)
752 .ok_or_else(|| anyhow::anyhow!("Unable to construct HOURLY anchor"))?;
753 let interval_seconds = i64::from(*interval_hours) * 60 * 60;
754 let elapsed_seconds = local_after
755 .naive_local()
756 .signed_duration_since(anchor_naive)
757 .num_seconds();
758 let mut steps = if elapsed_seconds < 0 {
759 0
760 } else {
761 elapsed_seconds / interval_seconds + 1
762 };
763
764 for _ in 0..MAX_HOURLY_SEARCH_STEPS {
765 let hours = i64::from(*interval_hours)
766 .checked_mul(steps)
767 .ok_or_else(|| anyhow::anyhow!("HOURLY schedule exceeded its range"))?;
768 let delta = Duration::try_hours(hours)
769 .ok_or_else(|| anyhow::anyhow!("HOURLY schedule exceeded its range"))?;
770 let candidate_naive = anchor_naive
771 .checked_add_signed(delta)
772 .ok_or_else(|| anyhow::anyhow!("HOURLY schedule exceeded its range"))?;
773
774 if byday
775 .as_ref()
776 .is_none_or(|days| days.contains(&candidate_naive.weekday()))
777 && let Some(candidate) =
778 resolve_local_datetime(timezone, candidate_naive)
779 {
780 let candidate = candidate.with_timezone(&Utc);
781 if candidate > after {
782 return Ok(candidate);
783 }
784 }
785
786 steps = steps
787 .checked_add(1)
788 .ok_or_else(|| anyhow::anyhow!("HOURLY schedule exceeded its range"))?;
789 }
790 bail!("Unable to compute next anchored HOURLY run");
791 }
792
793 let after_second = local_after.second();
794 let after_nanosecond = local_after.nanosecond();
795 let mut candidate = local_after + Duration::hours(i64::from(*interval_hours))
796 - Duration::seconds(i64::from(after_second))
797 - Duration::nanoseconds(i64::from(after_nanosecond));
798
799 if let Some(days) = byday {
800 for _ in 0..(24 * 21) {
801 if days.contains(&candidate.weekday()) {
802 return Ok(candidate.with_timezone(&Utc));
803 }
804 candidate += Duration::hours(i64::from(*interval_hours));
805 }
806 bail!("Unable to compute next HOURLY run for BYDAY filter");
807 }
808
809 Ok(candidate.with_timezone(&Utc))
810 }
811 Self::Weekly {
812 byday,
813 byhour,
814 byminute,
815 } => {
816 for day_offset in 0..15 {
817 let date = local_after.date_naive() + Duration::days(i64::from(day_offset));
818 if !byday.contains(&date.weekday()) {
819 continue;
820 }
821 let Some(candidate_naive) = date.and_hms_opt(*byhour, *byminute, 0) else {
822 continue;
823 };
824 if let Some(candidate) = resolve_local_datetime(timezone, candidate_naive)
825 && candidate.with_timezone(&Utc) > after
826 {
827 return Ok(candidate.with_timezone(&Utc));
828 }
829 }
830 bail!("Unable to compute next WEEKLY run");
831 }
832 Self::Cron { expr } => {
833 let cron = ParsedCronExpr::parse(expr)?;
834 let mut candidate_naive = local_after
835 .naive_local()
836 .with_second(0)
837 .and_then(|dt| dt.with_nanosecond(0))
838 .ok_or_else(|| anyhow::anyhow!("Unable to round CRON search start"))?
839 .checked_add_signed(Duration::minutes(1))
840 .ok_or_else(|| anyhow::anyhow!("CRON schedule exceeded its range"))?;
841
842 for _ in 0..MAX_CRON_SEARCH_MINUTES {
843 if cron.matches(candidate_naive)
844 && let Some(candidate) = resolve_local_datetime(timezone, candidate_naive)
845 {
846 let candidate = candidate.with_timezone(&Utc);
847 if candidate > after {
848 return Ok(candidate);
849 }
850 }
851 candidate_naive = candidate_naive
852 .checked_add_signed(Duration::minutes(1))
853 .ok_or_else(|| anyhow::anyhow!("CRON schedule exceeded its range"))?;
854 }
855 bail!("Unable to compute next CRON run within 5 years");
856 }
857 }
858 }
859
860 fn next_after_slot(
861 &self,
862 slot: DateTime<Utc>,
863 anchor_reference: DateTime<Utc>,
864 ) -> Result<Option<DateTime<Utc>>> {
865 match self {
866 Self::Once { .. } => Ok(None),
867 _ => self
868 .next_after_with_anchor(slot, anchor_reference)
869 .map(Some),
870 }
871 }
872
873 /// First slot after `slot` that is still in the future at `now`.
874 ///
875 /// Missed slots coalesce: downtime, a paused window, or an in-flight
876 /// occurrence earn one receipt for the oldest owed slot, then the
877 /// schedule resumes on its own grid instead of replaying one stale slot
878 /// per tick. Calendar-anchored schedules (anchored HOURLY, WEEKLY, CRON)
879 /// live on a fixed wall-clock grid, so the first slot after `now` is
880 /// exactly the slot plain chaining would converge to; computing from
881 /// `now` directly skips the whole backlog in one step. Unanchored HOURLY
882 /// is a relative cadence with no calendar grid — hop along its
883 /// established `slot + k * interval` chain so a late recovery does not
884 /// re-phase the schedule to the recovery instant.
885 fn next_unskipped_slot(
886 &self,
887 slot: DateTime<Utc>,
888 now: DateTime<Utc>,
889 anchor_reference: DateTime<Utc>,
890 ) -> Result<Option<DateTime<Utc>>> {
891 if let Self::Hourly {
892 interval_hours,
893 anchor_hour: None,
894 anchor_minute: None,
895 ..
896 } = self
897 {
898 let first = self.next_after_with_anchor(slot, anchor_reference)?;
899 if first > now {
900 return Ok(Some(first));
901 }
902 // Jump whole intervals on the established UTC grid, then reuse
903 // the schedule's weekday filter for the next eligible slot.
904 // Minute normalization happens in the first advance above.
905 let interval_seconds = i64::from(*interval_hours) * 60 * 60;
906 let elapsed = (now - first).num_seconds();
907 let delta = Duration::seconds(elapsed / interval_seconds * interval_seconds);
908 let previous = first
909 .checked_add_signed(delta)
910 .context("HOURLY catch-up exceeded its range")?;
911 self.next_after_slot(previous, anchor_reference)
912 } else {
913 self.next_after_slot(slot.max(now), anchor_reference)
914 }
915 }
916 }
917
918 /// Resolve one calendar-local schedule slot.
919 ///
920 /// Nonexistent wall times in a forward clock change are skipped rather than
921 /// shifted to a different clock time. Ambiguous wall times in a backward clock
922 /// change use the first occurrence only, preventing a recurring automation from
923 /// running twice for one calendar slot.
924 fn resolve_local_datetime<Tz: TimeZone>(
925 timezone: &Tz,
926 naive: NaiveDateTime,
927 ) -> Option<DateTime<Tz>> {
928 timezone.from_local_datetime(&naive).earliest()
929 }
930
931 fn parse_byday(value: &str) -> Result<Vec<Weekday>> {
932 let mut days = Vec::new();
933 for token in value.split(',') {
934 let day = match token.trim().to_ascii_uppercase().as_str() {
935 "MO" => Weekday::Mon,
936 "TU" => Weekday::Tue,
937 "WE" => Weekday::Wed,
938 "TH" => Weekday::Thu,
939 "FR" => Weekday::Fri,
940 "SA" => Weekday::Sat,
941 "SU" => Weekday::Sun,
942 other => bail!("Invalid BYDAY value '{other}'"),
943 };
944 if !days.contains(&day) {
945 days.push(day);
946 }
947 }
948 Ok(days)
949 }
950
951 fn parse_once_schedule(parts: &BTreeMap<String, String>) -> Result<AutomationSchedule> {
952 for key in parts.keys() {
953 if key != "FREQ" && key != "AT" {
954 bail!("Unsupported RRULE field '{key}' for ONCE. Allowed: FREQ,AT");
955 }
956 }
957 let raw_at = parts
958 .get("AT")
959 .ok_or_else(|| anyhow::anyhow!("ONCE schedules require AT"))?;
960 let at = parse_once_at(raw_at)?;
961 Ok(AutomationSchedule::Once { at })
962 }
963
964 fn parse_cron_schedule(parts: &BTreeMap<String, String>) -> Result<AutomationSchedule> {
965 for key in parts.keys() {
966 if key != "FREQ" && key != "EXPR" {
967 bail!("Unsupported RRULE field '{key}' for CRON. Allowed: FREQ,EXPR");
968 }
969 }
970 let expr = parts
971 .get("EXPR")
972 .map(|value| value.trim().to_string())
973 .filter(|value| !value.is_empty())
974 .ok_or_else(|| anyhow::anyhow!("CRON schedules require EXPR"))?;
975 ParsedCronExpr::parse(&expr)?;
976 Ok(AutomationSchedule::Cron { expr })
977 }
978
979 fn parse_once_at(raw: &str) -> Result<DateTime<Utc>> {
980 let trimmed = raw.trim();
981 if let Ok(at) = DateTime::parse_from_rfc3339(trimmed) {
982 return Ok(at.with_timezone(&Utc));
983 }
984 for format in ["%Y-%m-%dT%H:%M:%S", "%Y-%m-%dT%H:%M"] {
985 if let Ok(naive) = NaiveDateTime::parse_from_str(trimmed, format) {
986 return resolve_local_datetime(&Local, naive)
987 .map(|value| value.with_timezone(&Utc))
988 .ok_or_else(|| anyhow::anyhow!("ONCE local time does not exist: {trimmed}"));
989 }
990 }
991 bail!("Failed to parse ONCE AT '{trimmed}'. Use local YYYY-MM-DDTHH:MM[:SS] or RFC3339")
992 }
993
994 #[derive(Debug, Clone)]
995 struct ParsedCronExpr {
996 minute: CronField,
997 hour: CronField,
998 day_of_month: CronField,
999 month: CronField,
1000 day_of_week: CronField,
1001 }
1002
1003 impl ParsedCronExpr {
1004 fn parse(expr: &str) -> Result<Self> {
1005 let fields: Vec<&str> = expr.split_whitespace().collect();
1006 if fields.len() != 5 {
1007 bail!(
1008 "CRON EXPR must have exactly 5 fields: minute hour day-of-month month day-of-week"
1009 );
1010 }
1011 let parsed = Self {
1012 minute: CronField::parse(fields[0], 0, 59, CronNameMap::none(), "minute")?,
1013 hour: CronField::parse(fields[1], 0, 23, CronNameMap::none(), "hour")?,
1014 day_of_month: CronField::parse(fields[2], 1, 31, CronNameMap::none(), "day-of-month")?,
1015 month: CronField::parse(fields[3], 1, 12, CronNameMap::month(), "month")?,
1016 day_of_week: CronField::parse(fields[4], 0, 7, CronNameMap::weekday(), "day-of-week")?
1017 .normalized_day_of_week(),
1018 };
1019 parsed.validate_date_space()?;
1020 Ok(parsed)
1021 }
1022
1023 fn matches(&self, candidate: NaiveDateTime) -> bool {
1024 if !self.minute.contains(candidate.minute())
1025 || !self.hour.contains(candidate.hour())
1026 || !self.month.contains(candidate.month())
1027 {
1028 return false;
1029 }
1030
1031 let day_of_month = self.day_of_month.contains(candidate.day());
1032 let weekday = self
1033 .day_of_week
1034 .contains(weekday_to_cron(candidate.weekday()));
1035 if self.day_of_month.is_wildcard && self.day_of_week.is_wildcard {
1036 true
1037 } else if self.day_of_month.is_wildcard {
1038 weekday
1039 } else if self.day_of_week.is_wildcard {
1040 day_of_month
1041 } else {
1042 day_of_month || weekday
1043 }
1044 }
1045
1046 fn validate_date_space(&self) -> Result<()> {
1047 if self.day_of_month.is_wildcard {
1048 return Ok(());
1049 }
1050 let months = self.month.values();
1051 let days = self.day_of_month.values();
1052 let valid = months.iter().copied().any(|month| {
1053 let common = days_in_month(2025, month);
1054 let leap = days_in_month(2024, month);
1055 days.iter().copied().any(|day| day <= common || day <= leap)
1056 });
1057 if valid {
1058 Ok(())
1059 } else {
1060 bail!("CRON EXPR day-of-month/month combination can never occur")
1061 }
1062 }
1063 }
1064
1065 #[derive(Debug, Clone)]
1066 struct CronField {
1067 values: Vec<u32>,
1068 is_wildcard: bool,
1069 }
1070
1071 impl CronField {
1072 fn parse(raw: &str, min: u32, max: u32, names: CronNameMap, field_name: &str) -> Result<Self> {
1073 let trimmed = raw.trim();
1074 if trimmed.is_empty() {
1075 bail!("CRON {field_name} field must not be empty");
1076 }
1077 let mut values = Vec::new();
1078 let is_wildcard = trimmed == "*";
1079 for part in trimmed.split(',') {
1080 let part = part.trim();
1081 if part.is_empty() {
1082 bail!("CRON {field_name} field contains an empty list item");
1083 }
1084 let (base, step) = if let Some((base, step)) = part.split_once('/') {
1085 let step = step
1086 .trim()
1087 .parse::<u32>()
1088 .with_context(|| format!("Failed to parse CRON {field_name} step"))?;
1089 if step == 0 {
1090 bail!("CRON {field_name} step must be >= 1");
1091 }
1092 (base.trim(), step)
1093 } else {
1094 (part, 1)
1095 };
1096
1097 let range = if base == "*" {
1098 (min, max)
1099 } else if let Some((start, end)) = base.split_once('-') {
1100 let start = parse_cron_atom(start.trim(), min, max, names, field_name)?;
1101 let end = parse_cron_atom(end.trim(), min, max, names, field_name)?;
1102 if start > end {
1103 bail!("CRON {field_name} range start must be <= end");
1104 }
1105 (start, end)
1106 } else {
1107 let start = parse_cron_atom(base, min, max, names, field_name)?;
1108 if part.contains('/') {
1109 (start, max)
1110 } else {
1111 (start, start)
1112 }
1113 };
1114
1115 let mut current = range.0;
1116 while current <= range.1 {
1117 if !values.contains(&current) {
1118 values.push(current);
1119 }
1120 let Some(next) = current.checked_add(step) else {
1121 break;
1122 };
1123 if next <= current {
1124 break;
1125 }
1126 current = next;
1127 }
1128 }
1129 values.sort_unstable();
1130 Ok(Self {
1131 values,
1132 is_wildcard,
1133 })
1134 }
1135
1136 fn normalized_day_of_week(mut self) -> Self {
1137 for value in &mut self.values {
1138 if *value == 7 {
1139 *value = 0;
1140 }
1141 }
1142 self.values.sort_unstable();
1143 self.values.dedup();
1144 self
1145 }
1146
1147 fn contains(&self, value: u32) -> bool {
1148 self.values.binary_search(&value).is_ok()
1149 }
1150
1151 fn values(&self) -> &[u32] {
1152 &self.values
1153 }
1154 }
1155
1156 #[derive(Debug, Clone, Copy)]
1157 struct CronNameMap(&'static [(&'static str, u32)]);
1158
1159 impl CronNameMap {
1160 const fn none() -> Self {
1161 Self(&[])
1162 }
1163
1164 const fn month() -> Self {
1165 Self(&[
1166 ("JAN", 1),
1167 ("FEB", 2),
1168 ("MAR", 3),
1169 ("APR", 4),
1170 ("MAY", 5),
1171 ("JUN", 6),
1172 ("JUL", 7),
1173 ("AUG", 8),
1174 ("SEP", 9),
1175 ("OCT", 10),
1176 ("NOV", 11),
1177 ("DEC", 12),
1178 ])
1179 }
1180
1181 const fn weekday() -> Self {
1182 Self(&[
1183 ("SUN", 0),
1184 ("MON", 1),
1185 ("TUE", 2),
1186 ("WED", 3),
1187 ("THU", 4),
1188 ("FRI", 5),
1189 ("SAT", 6),
1190 ])
1191 }
1192
1193 fn lookup(self, token: &str) -> Option<u32> {
1194 let needle = token.trim().to_ascii_uppercase();
1195 self.0
1196 .iter()
1197 .find_map(|(name, value)| (*name == needle).then_some(*value))
1198 }
1199 }
1200
1201 fn parse_cron_atom(
1202 raw: &str,
1203 min: u32,
1204 max: u32,
1205 names: CronNameMap,
1206 field_name: &str,
1207 ) -> Result<u32> {
1208 let value = names
1209 .lookup(raw)
1210 .or_else(|| raw.parse::<u32>().ok())
1211 .ok_or_else(|| anyhow::anyhow!("Invalid CRON {field_name} value '{raw}'"))?;
1212 if !(min..=max).contains(&value) {
1213 bail!("CRON {field_name} value {value} is out of range {min}-{max}");
1214 }
1215 Ok(value)
1216 }
1217
1218 fn weekday_to_cron(day: Weekday) -> u32 {
1219 match day {
1220 Weekday::Sun => 0,
1221 Weekday::Mon => 1,
1222 Weekday::Tue => 2,
1223 Weekday::Wed => 3,
1224 Weekday::Thu => 4,
1225 Weekday::Fri => 5,
1226 Weekday::Sat => 6,
1227 }
1228 }
1229
1230 fn days_in_month(year: i32, month: u32) -> u32 {
1231 match month {
1232 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
1233 4 | 6 | 9 | 11 => 30,
1234 2 => {
1235 let leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
1236 if leap { 29 } else { 28 }
1237 }
1238 _ => 0,
1239 }
1240 }
1241
1242 #[derive(Debug, Clone)]
1243 pub struct AutomationManager {
1244 execution_scope: Option<String>,
1245 thread_events: Option<ThreadEventSink>,
1246 automations_dir: PathBuf,
1247 runs_dir: PathBuf,
1248 triggers_dir: PathBuf,
1249 archive_dir: PathBuf,
1250 missed_dir: PathBuf,
1251 trigger_wakeup: Arc<Notify>,
1252 }
1253
1254 impl AutomationManager {
1255 fn open_lock(&self, name: &str) -> Result<fd_lock::RwLock<fs::File>> {
1256 let path = self
1257 .automations_dir
1258 .parent()
1259 .context("automation root")?
1260 .join(name);
1261 let mut options = fs::OpenOptions::new();
1262 options.create(true).truncate(false).read(true).write(true);
1263 #[cfg(unix)]
1264 {
1265 use std::os::unix::fs::OpenOptionsExt as _;
1266 options
1267 .mode(0o600)
1268 .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC);
1269 }
1270 #[cfg(windows)]
1271 {
1272 use std::os::windows::fs::OpenOptionsExt as _;
1273 options.custom_flags(0x0020_0000); // FILE_FLAG_OPEN_REPARSE_POINT
1274 }
1275 let file = options
1276 .open(&path)
1277 .with_context(|| format!("open {}", path.display()))?;
1278 let metadata = file.metadata()?;
1279 if !metadata.is_file() {
1280 bail!("Automation lock must be a regular file");
1281 }
1282 #[cfg(unix)]
1283 {
1284 use std::os::unix::fs::MetadataExt as _;
1285 if metadata.nlink() != 1 {
1286 bail!("Automation lock must not have hard links");
1287 }
1288 }
1289 #[cfg(windows)]
1290 {
1291 use std::os::windows::fs::MetadataExt as _;
1292 if metadata.file_attributes() & 0x400 != 0 {
1293 bail!("Automation lock must not be a reparse point");
1294 }
1295 }
1296 Ok(fd_lock::RwLock::new(file))
1297 }
1298
1299 fn with_transaction<T>(&self, operation: impl FnOnce() -> Result<T>) -> Result<T> {
1300 let mut lock = self.open_lock("state.lock")?;
1301 let _guard = lock.write().context("lock automation state")?;
1302 operation()
1303 }
1304
1305 /// Short read/modify/write transaction shared with scheduler admission.
1306 /// Returning None leaves an absent record absent; it does not delete one.
1307 pub fn edit_automation(
1308 &self,
1309 id: &str,
1310 edit: impl FnOnce(Option<AutomationRecord>) -> Result<Option<AutomationRecord>>,
1311 ) -> Result<Option<AutomationRecord>> {
1312 self.with_transaction(|| {
1313 let current = if self.automation_path(id)?.try_exists()? {
1314 Some(self.get_automation(id)?)
1315 } else {
1316 None
1317 };
1318 let edited = edit(current)?;
1319 if let Some(record) = &edited {
1320 if record.id != id {
1321 bail!("Automation transaction cannot replace its identity");
1322 }
1323 self.save_automation_unlocked(record)?;
1324 }
1325 Ok(edited)
1326 })
1327 }
1328
1329 pub fn open(root: PathBuf) -> Result<Self> {
1330 let automations_dir = root.join("automations");
1331 let runs_dir = root.join("runs");
1332 let triggers_dir = root.join("triggers");
1333 let archive_dir = root.join("archive");
1334 let missed_dir = root.join("missed");
1335 fs::create_dir_all(&automations_dir)
1336 .with_context(|| format!("Failed to create {}", automations_dir.display()))?;
1337 fs::create_dir_all(&runs_dir)
1338 .with_context(|| format!("Failed to create {}", runs_dir.display()))?;
1339 fs::create_dir_all(&triggers_dir)
1340 .with_context(|| format!("Failed to create {}", triggers_dir.display()))?;
1341 fs::create_dir_all(&archive_dir)
1342 .with_context(|| format!("Failed to create {}", archive_dir.display()))?;
1343 fs::create_dir_all(&missed_dir)
1344 .with_context(|| format!("Failed to create {}", missed_dir.display()))?;
1345 Ok(Self {
1346 execution_scope: None,
1347 thread_events: None,
1348 automations_dir,
1349 runs_dir,
1350 triggers_dir,
1351 archive_dir,
1352 missed_dir,
1353 trigger_wakeup: Arc::new(Notify::new()),
1354 })
1355 }
1356
1357 #[cfg(any(test, feature = "test-support"))]
1358 pub fn open_for_test(root: PathBuf) -> Result<Self> {
1359 let mut manager = Self::open(root)?;
1360 manager.execution_scope = Some(crate::task_manager::test_execution_scope("test"));
1361 Ok(manager)
1362 }
1363
1364 pub fn bind_task_manager(&mut self, tasks: &crate::task_manager::TaskManager) -> Result<()> {
1365 if self
1366 .execution_scope
1367 .as_deref()
1368 .is_some_and(|scope| scope != tasks.execution_scope())
1369 {
1370 bail!("Automation service belongs to another Runtime scope");
1371 }
1372 self.execution_scope = Some(tasks.execution_scope().to_string());
1373 Ok(())
1374 }
1375
1376 pub fn set_thread_event_sink(&mut self, sink: ThreadEventSink) {
1377 self.thread_events = Some(sink);
1378 }
1379
1380 fn emit_thread_event(
1381 &self,
1382 thread_id: Option<&str>,
1383 event: &'static str,
1384 payload: serde_json::Value,
1385 ) {
1386 if let (Some(sink), Some(thread_id)) = (self.thread_events.as_ref(), thread_id) {
1387 (sink.0)(thread_id.to_string(), event, payload);
1388 }
1389 }
1390
1391 fn emit_automation_event(&self, event: &'static str, record: &AutomationRecord) {
1392 self.emit_thread_event(
1393 record.destination_thread_id.as_deref(),
1394 event,
1395 serde_json::json!({
1396 "automation_id": record.id,
1397 "name": record.name,
1398 "rrule": record.rrule,
1399 "status": record.status,
1400 "next_run_at": record.next_run_at,
1401 "paused_reason": record.elevated_pause_reason(),
1402 }),
1403 );
1404 }
1405
1406 pub fn emit_trigger_event(&self, event: &'static str, record: &DelayedTriggerRecord) {
1407 self.emit_thread_event(
1408 record.destination_thread_id.as_deref(),
1409 event,
1410 serde_json::json!({
1411 "trigger_id": record.trigger_id,
1412 "message": record.message,
1413 "fire_at": record.fire_at,
1414 "status": record.status,
1415 "task_id": record.task_id,
1416 }),
1417 );
1418 }
1419
1420 pub fn execution_scope(&self) -> Option<&str> {
1421 self.execution_scope.as_deref()
1422 }
1423
1424 fn eligible_scope(&self, scope: Option<&str>) -> bool {
1425 scope.is_some() && scope == self.execution_scope()
1426 }
1427
1428 pub fn execution_ownership(&self, record: &AutomationRecord) -> AutomationExecutionOwnership {
1429 match (self.execution_scope(), record.execution_scope.as_deref()) {
1430 (Some(here), Some(bound)) if bound == here => AutomationExecutionOwnership::Owned,
1431 (Some(_), Some(_)) => AutomationExecutionOwnership::OtherRuntime,
1432 (_, None) => AutomationExecutionOwnership::Unbound,
1433 (None, Some(_)) => AutomationExecutionOwnership::HostUnattached,
1434 }
1435 }
1436
1437 pub fn is_scheduled_here(&self, record: &AutomationRecord) -> bool {
1438 record.status == AutomationStatus::Active
1439 && self.eligible_scope(record.execution_scope.as_deref())
1440 }
1441
1442 pub fn record_view(&self, mut record: AutomationRecord) -> AutomationRecordView {
1443 let paused_reason = record.elevated_pause_reason();
1444 if paused_reason.is_some() {
1445 record.pause_for_elevated_permissions();
1446 }
1447 let scheduled_here = self.is_scheduled_here(&record);
1448 let execution_ownership = self.execution_ownership(&record);
1449 AutomationRecordView {
1450 record,
1451 scheduled_here,
1452 execution_ownership,
1453 paused_reason,
1454 }
1455 }
1456
1457 fn pause_elevated_automation(&self, automation: &mut AutomationRecord) -> Result<()> {
1458 automation.pause_for_elevated_permissions();
1459 automation.updated_at = Utc::now();
1460 automation.revision = automation.revision.saturating_add(1);
1461 self.save_automation_unlocked(automation)?;
1462 self.emit_automation_event("automation.updated", automation);
1463 Ok(())
1464 }
1465
1466 /// Explicit control may bind an unbound definition; saved admissions never
1467 /// read this field back from the definition during recovery.
1468 fn adopt_for_run(&self, automation: &mut AutomationRecord) -> Result<()> {
1469 let scope = self
1470 .execution_scope()
1471 .context("Automation execution ownership is unverified")?;
1472 if let Some(bound) = &automation.execution_scope {
1473 if bound != scope {
1474 bail!("Automation belongs to another Runtime execution scope");
1475 }
1476 } else {
1477 automation.execution_scope = Some(scope.to_string());
1478 automation.schema_version =
1479 automation
1480 .schema_version
1481 .max(required_automation_schema_version(
1482 &automation.disallowed_tools,
1483 ));
1484 automation.updated_at = Utc::now();
1485 if automation.status == AutomationStatus::Active {
1486 let schedule = AutomationSchedule::parse_rrule(&automation.rrule)?;
1487 automation.next_run_at =
1488 match schedule.next_after_with_anchor(Utc::now(), automation.created_at) {
1489 Ok(next) => Some(next),
1490 Err(_) if matches!(schedule, AutomationSchedule::Once { .. }) => {
1491 automation.status = AutomationStatus::Paused;
1492 None
1493 }
1494 Err(error) => return Err(error),
1495 };
1496 }
1497 self.save_automation_unlocked(automation)?;
1498 }
1499 Ok(())
1500 }
1501
1502 pub fn default_location() -> Result<Self> {
1503 Self::open(default_automations_dir())
1504 }
1505
1506 fn automation_path(&self, id: &str) -> Result<PathBuf> {
1507 ensure_safe_storage_id("automation id", id)?;
1508 Ok(self.automations_dir.join(format!("{id}.json")))
1509 }
1510
1511 fn runs_dir_for(&self, automation_id: &str) -> Result<PathBuf> {
1512 ensure_safe_storage_id("automation id", automation_id)?;
1513 Ok(self.runs_dir.join(automation_id))
1514 }
1515
1516 fn trigger_path(&self, trigger_id: &str) -> Result<PathBuf> {
1517 ensure_safe_storage_id("trigger id", trigger_id)?;
1518 Ok(self.triggers_dir.join(format!("{trigger_id}.json")))
1519 }
1520
1521 /// Current run file name: `{sortable-created-at}-{run_id}.json`. The
1522 /// fixed-width timestamp prefix makes directory listings sort
1523 /// chronologically without reading file contents (see [`Self::list_runs`]).
1524 fn run_path(&self, run: &AutomationRunRecord) -> Result<PathBuf> {
1525 ensure_safe_storage_id("run id", &run.id)?;
1526 Ok(self.runs_dir_for(&run.automation_id)?.join(format!(
1527 "{}-{}.json",
1528 run_file_stamp(run.created_at),
1529 run.id
1530 )))
1531 }
1532
1533 /// Pre-sortable-name run file: `{run_id}.json` (run ids are UUIDs, so
1534 /// these carry no ordering hint and must be read to learn `created_at`).
1535 fn legacy_run_path(&self, automation_id: &str, run_id: &str) -> Result<PathBuf> {
1536 ensure_safe_storage_id("run id", run_id)?;
1537 Ok(self
1538 .runs_dir_for(automation_id)?
1539 .join(format!("{run_id}.json")))
1540 }
1541
1542 /// Terminal-run archive for one automation. Lives beside — never inside —
1543 /// the live `runs/` tree so `list_runs` and scheduler scans cannot see it.
1544 fn archive_dir_for(&self, automation_id: &str) -> Result<PathBuf> {
1545 ensure_safe_storage_id("automation id", automation_id)?;
1546 Ok(self.archive_dir.join(automation_id))
1547 }
1548
1549 /// Archived run file name: the same sortable `{stamp}-{run_id}.json` shape
1550 /// as live runs, so legacy-named runs are normalized when archived.
1551 fn archive_run_path(&self, run: &AutomationRunRecord) -> Result<PathBuf> {
1552 ensure_safe_storage_id("run id", &run.id)?;
1553 Ok(self.archive_dir_for(&run.automation_id)?.join(format!(
1554 "{}-{}.json",
1555 run_file_stamp(run.created_at),
1556 run.id
1557 )))
1558 }
1559
1560 pub fn create_automation(&self, req: CreateAutomationRequest) -> Result<AutomationRecord> {
1561 validate_name_and_prompt(&req.name, &req.prompt)?;
1562 let schedule = AutomationSchedule::parse_rrule(&req.rrule)?;
1563 let now = Utc::now();
1564 let status = req.status.unwrap_or(AutomationStatus::Active);
1565 let next_run_at = if matches!(status, AutomationStatus::Active) {
1566 Some(schedule.next_after_with_anchor(now, now)?)
1567 } else {
1568 None
1569 };
1570
1571 let disallowed_tools = crate::task_manager::normalize_deny_rules(req.disallowed_tools);
1572 let record = AutomationRecord {
1573 schema_version: required_automation_schema_version(&disallowed_tools),
1574 execution_scope: self.execution_scope.clone(),
1575 id: Uuid::new_v4().to_string(),
1576 name: req.name.trim().to_string(),
1577 prompt: req.prompt.trim().to_string(),
1578 rrule: req.rrule.trim().to_ascii_uppercase(),
1579 cwds: req.cwds,
1580 model: normalize_optional_string(req.model),
1581 model_provider: normalize_optional_string(req.model_provider),
1582 model_provider_id: normalize_optional_string(req.model_provider_id),
1583 mode: normalize_optional_string(req.mode),
1584 allow_shell: req.allow_shell,
1585 trust_mode: req.trust_mode,
1586 auto_approve: req.auto_approve,
1587 delivery_mode: req.delivery_mode,
1588 destination_thread_id: normalize_optional_string(req.destination_thread_id),
1589 disallowed_tools,
1590 status,
1591 created_at: now,
1592 updated_at: now,
1593 next_run_at,
1594 last_run_at: None,
1595 revision: 1,
1596 };
1597
1598 self.save_automation(&record)?;
1599 self.emit_automation_event("automation.created", &record);
1600 Ok(record)
1601 }
1602
1603 pub fn get_automation(&self, id: &str) -> Result<AutomationRecord> {
1604 let path = self.automation_path(id)?;
1605 read_automation_file(&path)
1606 }
1607
1608 pub fn get_automation_view(&self, id: &str) -> Result<AutomationRecordView> {
1609 Ok(self.record_view(self.get_automation(id)?))
1610 }
1611
1612 pub fn save_automation(&self, record: &AutomationRecord) -> Result<()> {
1613 self.with_transaction(|| self.save_automation_unlocked(record))
1614 }
1615
1616 fn save_automation_unlocked(&self, record: &AutomationRecord) -> Result<()> {
1617 if (record.model_provider.is_some() || record.model_provider_id.is_some())
1618 && record
1619 .model
1620 .as_deref()
1621 .is_none_or(|model| model.trim().is_empty())
1622 {
1623 bail!("A pinned automation provider requires an explicit model");
1624 }
1625 let min_version = if !record.disallowed_tools.is_empty() {
1626 DENY_RULES_AUTOMATION_SCHEMA_VERSION
1627 } else if record.model_provider.is_some() || record.model_provider_id.is_some() {
1628 CURRENT_AUTOMATION_SCHEMA_VERSION
1629 } else {
1630 record.schema_version
1631 };
1632 if record.schema_version < min_version {
1633 let mut record = record.clone();
1634 record.schema_version = min_version;
1635 return write_json_atomic(&self.automation_path(&record.id)?, &record);
1636 }
1637 write_json_atomic(&self.automation_path(&record.id)?, record)
1638 }
1639
1640 pub fn list_automations(&self) -> Result<Vec<AutomationRecord>> {
1641 let mut out = Vec::new();
1642 for entry in fs::read_dir(&self.automations_dir)
1643 .with_context(|| format!("Failed to read {}", self.automations_dir.display()))?
1644 {
1645 let entry = entry?;
1646 let path = entry.path();
1647 if path.extension().is_none_or(|ext| ext != "json") {
1648 continue;
1649 }
1650 let record = read_automation_file(&path)?;
1651 out.push(record);
1652 }
1653 out.sort_by_key(|r| std::cmp::Reverse(r.updated_at));
1654 Ok(out)
1655 }
1656
1657 pub fn list_automation_views(&self) -> Result<Vec<AutomationRecordView>> {
1658 Ok(self
1659 .list_automations()?
1660 .into_iter()
1661 .map(|record| self.record_view(record))
1662 .collect())
1663 }
1664
1665 pub fn adopt_automation(&self, id: &str) -> Result<AutomationRecord> {
1666 self.adopt_automation_if(id, None)
1667 }
1668
1669 pub fn adopt_automation_if(
1670 &self,
1671 id: &str,
1672 expected_revision: Option<u64>,
1673 ) -> Result<AutomationRecord> {
1674 self.with_transaction(|| {
1675 let scope = self
1676 .execution_scope()
1677 .context("Automation execution ownership is unverified")?
1678 .to_string();
1679 let mut existing = self.get_automation(id)?;
1680 check_expected_revision(&existing, expected_revision)?;
1681 if existing.execution_scope.as_deref() == Some(scope.as_str()) {
1682 return Ok(existing);
1683 }
1684 let now = Utc::now();
1685 existing.execution_scope = Some(scope);
1686 existing.schema_version =
1687 existing
1688 .schema_version
1689 .max(required_automation_schema_version(
1690 &existing.disallowed_tools,
1691 ));
1692 existing.updated_at = now;
1693 existing.revision = existing.revision.saturating_add(1);
1694 let mut missed_event: Option<&'static str> = None;
1695 let mut saved = false;
1696 if existing.status == AutomationStatus::Active
1697 && let Some(due_at) = existing.next_run_at
1698 && due_at < now
1699 {
1700 let mut state = self.read_missed_state(&existing.id)?;
1701 if !state
1702 .owed
1703 .as_ref()
1704 .is_some_and(|owed| owed.due_at == due_at)
1705 {
1706 match state
1707 .policy
1708 .unwrap_or_else(|| default_missed_policy(&existing))
1709 {
1710 AutomationMissedPolicy::RunOnce => {}
1711 AutomationMissedPolicy::Skip => {
1712 let schedule = AutomationSchedule::parse_rrule(&existing.rrule)?;
1713 state.owed = None;
1714 push_missed_outcome(
1715 &mut state,
1716 MissedRunOutcome {
1717 due_at,
1718 decided_at: now,
1719 outcome: MissedRunOutcomeKind::Skipped,
1720 decided_by: MissedRunDecider::Policy,
1721 run_id: None,
1722 },
1723 );
1724 self.save_missed_state(&existing.id, &state)?;
1725 self.advance_automation_after_slot(
1726 &mut existing,
1727 &schedule,
1728 due_at,
1729 now,
1730 )?;
1731 saved = true;
1732 missed_event = Some("automation.missed_skipped");
1733 }
1734 AutomationMissedPolicy::Ask => {
1735 state.owed = Some(OwedOccurrence {
1736 due_at,
1737 detected_at: now,
1738 });
1739 self.save_missed_state(&existing.id, &state)?;
1740 missed_event = Some("automation.missed");
1741 }
1742 }
1743 }
1744 }
1745 if !saved {
1746 self.save_automation_unlocked(&existing)?;
1747 }
1748 self.emit_automation_event("automation.updated", &existing);
1749 if let Some(event) = missed_event {
1750 self.emit_automation_event(event, &existing);
1751 }
1752 Ok(existing)
1753 })
1754 }
1755
1756 pub fn update_automation(
1757 &self,
1758 id: &str,
1759 req: UpdateAutomationRequest,
1760 ) -> Result<AutomationRecord> {
1761 self.with_transaction(|| self.update_automation_unlocked(id, req))
1762 }
1763
1764 fn update_automation_unlocked(
1765 &self,
1766 id: &str,
1767 req: UpdateAutomationRequest,
1768 ) -> Result<AutomationRecord> {
1769 let mut existing = self.get_automation(id)?;
1770 check_expected_revision(&existing, req.expected_revision)?;
1771 if self.execution_scope.is_some()
1772 && existing.execution_scope.is_some()
1773 && !self.eligible_scope(existing.execution_scope.as_deref())
1774 && req.status != Some(AutomationStatus::Paused)
1775 {
1776 bail!("Automation belongs to another Runtime execution scope");
1777 }
1778 let adopting = existing.execution_scope.is_none()
1779 && self.execution_scope.is_some()
1780 && req.status != Some(AutomationStatus::Paused);
1781 if adopting {
1782 existing.execution_scope = self.execution_scope.clone();
1783 }
1784 let schedule_changed = adopting || req.rrule.is_some() || req.status.is_some();
1785 let was_elevated = existing.elevated_pause_reason().is_some();
1786
1787 if let Some(name) = req.name {
1788 if name.trim().is_empty() {
1789 bail!("Automation name cannot be empty");
1790 }
1791 existing.name = name.trim().to_string();
1792 }
1793 if let Some(prompt) = req.prompt {
1794 if prompt.trim().is_empty() {
1795 bail!("Automation prompt cannot be empty");
1796 }
1797 existing.prompt = prompt.trim().to_string();
1798 }
1799 if let Some(rrule) = req.rrule {
1800 let normalized = rrule.trim().to_ascii_uppercase();
1801 AutomationSchedule::parse_rrule(&normalized)?;
1802 existing.rrule = normalized;
1803 }
1804 if let Some(cwds) = req.cwds {
1805 existing.cwds = cwds;
1806 }
1807 if let Some(model) = req.model {
1808 existing.model = normalize_optional_string(Some(model));
1809 }
1810 if let Some(provider) = req.model_provider {
1811 existing.model_provider = normalize_optional_string(Some(provider));
1812 }
1813 if let Some(provider_id) = req.model_provider_id {
1814 existing.model_provider_id = normalize_optional_string(Some(provider_id));
1815 }
1816 if let Some(mode) = req.mode {
1817 existing.mode = normalize_optional_string(Some(mode));
1818 }
1819 if let Some(allow_shell) = req.allow_shell {
1820 existing.allow_shell = Some(allow_shell);
1821 }
1822 if let Some(trust_mode) = req.trust_mode {
1823 existing.trust_mode = Some(trust_mode);
1824 }
1825 if let Some(auto_approve) = req.auto_approve {
1826 existing.auto_approve = Some(auto_approve);
1827 }
1828 if let Some(delivery_mode) = req.delivery_mode {
1829 existing.delivery_mode = Some(delivery_mode);
1830 }
1831 if let Some(destination) = req.destination_thread_id {
1832 existing.destination_thread_id = normalize_optional_string(Some(destination));
1833 }
1834 if let Some(status) = req.status {
1835 existing.status = status;
1836 }
1837 if existing.elevated_pause_reason().is_some() {
1838 if req.status == Some(AutomationStatus::Active) {
1839 bail!("{ELEVATED_AUTOMATION_PAUSE_REASON}");
1840 }
1841 existing.pause_for_elevated_permissions();
1842 } else if was_elevated && req.status.is_none() {
1843 existing.pause_for_elevated_permissions();
1844 }
1845 // Evaluate the final status once: editing a schedule and pausing it is
1846 // one atomic update, and must not first schedule an active run.
1847 if schedule_changed {
1848 if matches!(existing.status, AutomationStatus::Paused) {
1849 existing.next_run_at = None;
1850 } else {
1851 let schedule = AutomationSchedule::parse_rrule(&existing.rrule)?;
1852 existing.next_run_at =
1853 Some(schedule.next_after_with_anchor(Utc::now(), existing.created_at)?);
1854 }
1855 }
1856
1857 if existing.execution_scope.is_some()
1858 || existing.model_provider.is_some()
1859 || existing.model_provider_id.is_some()
1860 || !existing.disallowed_tools.is_empty()
1861 {
1862 existing.schema_version =
1863 existing
1864 .schema_version
1865 .max(required_automation_schema_version(
1866 &existing.disallowed_tools,
1867 ));
1868 }
1869
1870 existing.updated_at = Utc::now();
1871 existing.revision = existing.revision.saturating_add(1);
1872 self.save_automation_unlocked(&existing)?;
1873 self.emit_automation_event("automation.updated", &existing);
1874 Ok(existing)
1875 }
1876
1877 fn idempotency_path(&self) -> Result<PathBuf> {
1878 Ok(self
1879 .automations_dir
1880 .parent()
1881 .context("automation root")?
1882 .join("idempotency.json"))
1883 }
1884
1885 fn read_idempotency_unlocked(&self, now: DateTime<Utc>) -> Result<Vec<IdempotencyEntry>> {
1886 let path = self.idempotency_path()?;
1887 let mut entries: Vec<IdempotencyEntry> = match fs::read(&path) {
1888 Ok(bytes) => match serde_json::from_slice(&bytes) {
1889 Ok(entries) => entries,
1890 Err(parse_error) => {
1891 let quarantine = path.with_file_name(format!(
1892 "idempotency.corrupt-{}.json",
1893 now.format("%Y%m%dT%H%M%S%.3f")
1894 ));
1895 fs::rename(&path, &quarantine)
1896 .with_context(|| format!("quarantine corrupt {}", path.display()))?;
1897 anyhow::bail!(
1898 "idempotency store {} was unparseable ({parse_error}); moved to {}",
1899 path.display(),
1900 quarantine.display()
1901 );
1902 }
1903 },
1904 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Vec::new(),
1905 Err(error) => return Err(error).with_context(|| format!("read {}", path.display())),
1906 };
1907 let cutoff = now - Duration::hours(IDEMPOTENCY_TTL_HOURS);
1908 entries.retain(|entry| entry.created_at > cutoff);
1909 Ok(entries)
1910 }
1911
1912 pub fn idempotency_lookup(&self, key: &str, fingerprint: &str) -> Result<IdempotencyLookup> {
1913 self.with_transaction(|| {
1914 let entries = self.read_idempotency_unlocked(Utc::now())?;
1915 Ok(match entries.into_iter().find(|entry| entry.key == key) {
1916 None => IdempotencyLookup::Miss,
1917 Some(entry) if entry.fingerprint == fingerprint => IdempotencyLookup::Replay {
1918 status: entry.status,
1919 body: entry.body,
1920 },
1921 Some(_) => IdempotencyLookup::KeyReused,
1922 })
1923 })
1924 }
1925
1926 pub fn idempotency_store(
1927 &self,
1928 key: &str,
1929 fingerprint: &str,
1930 status: u16,
1931 body: serde_json::Value,
1932 ) -> Result<()> {
1933 self.with_transaction(|| {
1934 let now = Utc::now();
1935 let mut entries = self.read_idempotency_unlocked(now)?;
1936 entries.retain(|entry| entry.key != key);
1937 entries.push(IdempotencyEntry {
1938 key: key.to_string(),
1939 fingerprint: fingerprint.to_string(),
1940 status,
1941 body,
1942 created_at: now,
1943 });
1944 if entries.len() > IDEMPOTENCY_MAX_ENTRIES {
1945 let excess = entries.len() - IDEMPOTENCY_MAX_ENTRIES;
1946 entries.drain(..excess);
1947 }
1948 write_json_atomic(&self.idempotency_path()?, &entries)
1949 })
1950 }
1951
1952 pub fn pause_automation(&self, id: &str) -> Result<AutomationRecord> {
1953 self.update_automation(
1954 id,
1955 UpdateAutomationRequest {
1956 status: Some(AutomationStatus::Paused),
1957 ..UpdateAutomationRequest::default()
1958 },
1959 )
1960 }
1961
1962 pub fn resume_automation(&self, id: &str) -> Result<AutomationRecord> {
1963 self.update_automation(
1964 id,
1965 UpdateAutomationRequest {
1966 status: Some(AutomationStatus::Active),
1967 ..UpdateAutomationRequest::default()
1968 },
1969 )
1970 }
1971
1972 /// Delete an automation, keeping its terminal run history. Terminal runs
1973 /// (completed, failed, canceled) are archived under `<root>/archive/<id>/`
1974 /// — bounded to the most recent [`ARCHIVE_RETAINED_TERMINAL_RUNS`] per
1975 /// automation — before the live paths are removed. Deleting is refused
1976 /// while any run is still queued or running: an in-flight occurrence has
1977 /// already crossed the admission boundary, so its definition and run
1978 /// binding must stay intact for recovery to settle it.
1979 pub fn delete_automation(&self, id: &str) -> Result<AutomationRecord> {
1980 self.with_transaction(|| {
1981 let existing = self.get_automation(id)?;
1982 let runs = self.list_runs_with_visibility(id, None, true)?;
1983 if let Some(active) = runs.iter().find(|run| {
1984 matches!(
1985 run.status,
1986 AutomationRunStatus::Queued | AutomationRunStatus::Running
1987 )
1988 }) {
1989 bail!(
1990 "Refusing to delete automation {id}: run {} is still active",
1991 active.id
1992 );
1993 }
1994
1995 // Archive before removing live receipts, and remove the
1996 // definition last. A crash or cleanup failure leaves the
1997 // definition available to retry; retained archive copies survive
1998 // even when some live receipts have already been removed.
1999 let terminal: Vec<AutomationRunRecord> = runs
2000 .into_iter()
2001 .filter(|run| {
2002 matches!(
2003 run.status,
2004 AutomationRunStatus::Completed
2005 | AutomationRunStatus::Failed
2006 | AutomationRunStatus::Canceled
2007 )
2008 })
2009 .collect();
2010 for run in &terminal {
2011 write_json_atomic(&self.archive_run_path(run)?, run)?;
2012 }
2013 self.enforce_archive_retention(id)?;
2014
2015 for run in &terminal {
2016 self.delete_run(run)?;
2017 }
2018 let runs_dir = self.runs_dir_for(id)?;
2019 if runs_dir.try_exists()? && fs::read_dir(&runs_dir)?.next().is_none() {
2020 fs::remove_dir(&runs_dir).with_context(|| {
2021 format!(
2022 "Failed to remove empty run directory {}",
2023 runs_dir.display()
2024 )
2025 })?;
2026 }
2027 let missed = self.missed_path(id)?;
2028 if missed.try_exists()? {
2029 fs::remove_file(&missed).with_context(|| {
2030 format!("Failed to delete missed-run state {}", missed.display())
2031 })?;
2032 }
2033 let path = self.automation_path(id)?;
2034 fs::remove_file(&path)
2035 .with_context(|| format!("Failed to delete automation {}", path.display()))?;
2036 Ok(existing)
2037 })
2038 }
2039
2040 /// Terminal runs archived for a deleted automation (see
2041 /// [`Self::delete_automation`]), newest-first by `ended_at` (falling back
2042 /// to `created_at`).
2043 pub fn list_archived_runs(&self, automation_id: &str) -> Result<Vec<AutomationRunRecord>> {
2044 Ok(self
2045 .read_archive_entries(automation_id)?
2046 .into_iter()
2047 .map(|(_, run)| run)
2048 .collect())
2049 }
2050
2051 /// Archived runs paired with their file paths, newest-first by `ended_at`
2052 /// (falling back to `created_at`).
2053 fn read_archive_entries(
2054 &self,
2055 automation_id: &str,
2056 ) -> Result<Vec<(PathBuf, AutomationRunRecord)>> {
2057 let dir = self.archive_dir_for(automation_id)?;
2058 if !dir.exists() {
2059 return Ok(Vec::new());
2060 }
2061 let mut entries = Vec::new();
2062 for entry in
2063 fs::read_dir(&dir).with_context(|| format!("Failed to read {}", dir.display()))?
2064 {
2065 let path = entry?.path();
2066 if path.extension().is_none_or(|ext| ext != "json") {
2067 continue;
2068 }
2069 let run = read_run_file(&path)?;
2070 entries.push((path, run));
2071 }
2072 entries.sort_by_key(|(_, run)| std::cmp::Reverse(run.ended_at.unwrap_or(run.created_at)));
2073 Ok(entries)
2074 }
2075
2076 /// Drop archived terminal runs beyond the per-automation retention budget,
2077 /// keeping the most recent [`ARCHIVE_RETAINED_TERMINAL_RUNS`].
2078 fn enforce_archive_retention(&self, automation_id: &str) -> Result<()> {
2079 let entries = self.read_archive_entries(automation_id)?;
2080 for (path, _) in entries.into_iter().skip(ARCHIVE_RETAINED_TERMINAL_RUNS) {
2081 fs::remove_file(&path)
2082 .with_context(|| format!("Failed to delete archived run {}", path.display()))?;
2083 }
2084 Ok(())
2085 }
2086
2087 pub fn list_runs(
2088 &self,
2089 automation_id: &str,
2090 limit: Option<usize>,
2091 ) -> Result<Vec<AutomationRunRecord>> {
2092 self.list_runs_with_visibility(automation_id, limit, false)
2093 }
2094
2095 fn list_runs_with_visibility(
2096 &self,
2097 automation_id: &str,
2098 limit: Option<usize>,
2099 include_suppressed: bool,
2100 ) -> Result<Vec<AutomationRunRecord>> {
2101 let dir = self.runs_dir_for(automation_id)?;
2102 if !dir.exists() {
2103 return Ok(Vec::new());
2104 }
2105
2106 // Split the listing into sortable-name files (newest-first by file
2107 // name alone, so reads stop after the newest `limit`) and legacy
2108 // `{uuid}.json` files, which must all be read to learn `created_at`.
2109 let mut sortable = Vec::new();
2110 let mut legacy = Vec::new();
2111 for entry in
2112 fs::read_dir(&dir).with_context(|| format!("Failed to read {}", dir.display()))?
2113 {
2114 let entry = entry?;
2115 let path = entry.path();
2116 if path.extension().is_none_or(|ext| ext != "json") {
2117 continue;
2118 }
2119 if path
2120 .file_stem()
2121 .and_then(|stem| stem.to_str())
2122 .is_some_and(has_sortable_run_stem)
2123 {
2124 sortable.push(path);
2125 } else {
2126 legacy.push(path);
2127 }
2128 }
2129
2130 // A sortable receipt supersedes its legacy copy even when hidden or
2131 // older than the requested window. Fence identity before visibility.
2132 let sortable_ids: std::collections::BTreeSet<_> = sortable
2133 .iter()
2134 .filter_map(|path| path.file_stem()?.to_str()?.get(RUN_STAMP_LEN + 1..))
2135 .collect();
2136 legacy.retain(|path| {
2137 !path
2138 .file_stem()
2139 .and_then(|stem| stem.to_str())
2140 .is_some_and(|id| sortable_ids.contains(id))
2141 });
2142 sortable.sort_by(|a, b| b.file_name().cmp(&a.file_name()));
2143 let visible = |run: &AutomationRunRecord| {
2144 include_suppressed
2145 || !run
2146 .dispatch
2147 .as_ref()
2148 .is_some_and(|dispatch| dispatch.suppress_report)
2149 };
2150 let mut out = Vec::new();
2151 for path in sortable {
2152 if limit.is_some_and(|limit| out.len() >= limit) {
2153 break;
2154 }
2155 let run = read_run_file(&path)?;
2156 if visible(&run) {
2157 out.push(run);
2158 }
2159 }
2160 for path in legacy {
2161 let run = read_run_file(&path)?;
2162 if visible(&run) {
2163 out.push(run);
2164 }
2165 }
2166
2167 out.sort_by_key(|r| std::cmp::Reverse(r.created_at));
2168 // A crash between the sortable-name write and the legacy-file removal
2169 // in `save_run` can leave one run under both names; keep the sortable
2170 // copy (chained first above, so it survives the stable sort).
2171 out.dedup_by(|a, b| a.id == b.id);
2172 if let Some(limit) = limit {
2173 out.truncate(limit);
2174 }
2175 Ok(out)
2176 }
2177
2178 /// Re-read specific runs by id without a full history pass. Run file
2179 /// names end in `-{run_id}.json` (or are legacy `{run_id}.json`), so a
2180 /// directory listing locates them and only those files are read. Used
2181 /// by the activity-band scan to keep watching runs this session saw go
2182 /// live even after newer runs push them past the newest-run window.
2183 pub fn get_runs_by_ids(
2184 &self,
2185 automation_id: &str,
2186 run_ids: &std::collections::BTreeSet<String>,
2187 ) -> Result<Vec<AutomationRunRecord>> {
2188 if run_ids.is_empty() {
2189 return Ok(Vec::new());
2190 }
2191 let dir = self.runs_dir_for(automation_id)?;
2192 if !dir.exists() {
2193 return Ok(Vec::new());
2194 }
2195 let mut paths = BTreeMap::<String, (bool, PathBuf)>::new();
2196 for entry in
2197 fs::read_dir(&dir).with_context(|| format!("Failed to read {}", dir.display()))?
2198 {
2199 let path = entry?.path();
2200 if path.extension().and_then(|ext| ext.to_str()) != Some("json") {
2201 continue;
2202 }
2203 let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) else {
2204 continue;
2205 };
2206 let sortable = has_sortable_run_stem(stem);
2207 let id = if sortable {
2208 &stem[RUN_STAMP_LEN + 1..]
2209 } else {
2210 stem
2211 };
2212 if run_ids.contains(id)
2213 && paths
2214 .get(id)
2215 .is_none_or(|(current, _)| !current && sortable)
2216 {
2217 paths.insert(id.to_string(), (sortable, path));
2218 }
2219 }
2220 let mut out = Vec::new();
2221 for (_, path) in paths.into_values() {
2222 let run = read_run_file(&path)?;
2223 if !run
2224 .dispatch
2225 .as_ref()
2226 .is_some_and(|dispatch| dispatch.suppress_report)
2227 {
2228 out.push(run);
2229 }
2230 }
2231 Ok(out)
2232 }
2233
2234 fn save_run(&self, run: &AutomationRunRecord) -> Result<()> {
2235 let dir = self.runs_dir_for(&run.automation_id)?;
2236 fs::create_dir_all(&dir).with_context(|| format!("Failed to create {}", dir.display()))?;
2237 let path = self.run_path(run)?;
2238 let min_version = required_run_schema_version(run.dispatch.as_ref());
2239 if run.schema_version < min_version {
2240 let mut updated = run.clone();
2241 updated.schema_version = min_version;
2242 write_json_atomic(&path, &updated)?;
2243 } else {
2244 write_json_atomic(&path, run)?;
2245 }
2246 // Rewrites of a legacy-named run migrate it to the sortable name; drop
2247 // the old file so the run never exists twice.
2248 let legacy = self.legacy_run_path(&run.automation_id, &run.id)?;
2249 if legacy != path && legacy.exists() {
2250 fs::remove_file(&legacy)
2251 .with_context(|| format!("Failed to remove legacy run {}", legacy.display()))?;
2252 }
2253 Ok(())
2254 }
2255
2256 fn delete_run(&self, run: &AutomationRunRecord) -> Result<()> {
2257 let sortable = self.run_path(run)?;
2258 if sortable.exists() {
2259 fs::remove_file(&sortable)
2260 .with_context(|| format!("Failed to delete run {}", sortable.display()))?;
2261 }
2262 let legacy = self.legacy_run_path(&run.automation_id, &run.id)?;
2263 if legacy.exists() {
2264 fs::remove_file(&legacy)
2265 .with_context(|| format!("Failed to delete run {}", legacy.display()))?;
2266 }
2267 Ok(())
2268 }
2269
2270 /// Definitions this build can read, in `list_automations` order.
2271 ///
2272 /// One corrupt, unreadable, or newer-schema file is quarantined in place:
2273 /// its bytes stay on disk and every pass logs the path, but it cannot
2274 /// starve collection of the healthy definitions behind it, and it is never
2275 /// rewritten or adopted by a runtime that does not understand it.
2276 fn readable_automations(&self) -> Result<Vec<AutomationRecord>> {
2277 let mut out = Vec::new();
2278 for entry in fs::read_dir(&self.automations_dir)
2279 .with_context(|| format!("Failed to read {}", self.automations_dir.display()))?
2280 {
2281 let entry = entry?;
2282 let path = entry.path();
2283 if path.extension().is_none_or(|ext| ext != "json") {
2284 continue;
2285 }
2286 match read_automation_file(&path) {
2287 Ok(record) => out.push(record),
2288 Err(error) => {
2289 tracing::warn!("Skipping damaged automation file: {error:#}");
2290 }
2291 }
2292 }
2293 out.sort_by_key(|r| std::cmp::Reverse(r.updated_at));
2294 Ok(out)
2295 }
2296
2297 /// List proposals only. Every proposal is revalidated and durably claimed
2298 /// immediately before dispatch, not when an earlier batch item is awaited.
2299 fn collect_due_runs(
2300 &self,
2301 now: DateTime<Utc>,
2302 ) -> Result<Vec<(AutomationRecord, AutomationRunRecord)>> {
2303 self.with_transaction(|| {
2304 let mut due = Vec::new();
2305 let awake_since = self.read_presence().map(|presence| presence.awake_since);
2306 for mut automation in self.readable_automations()? {
2307 if automation.status != AutomationStatus::Active
2308 || !self.eligible_scope(automation.execution_scope.as_deref())
2309 {
2310 continue;
2311 }
2312 if automation.elevated_pause_reason().is_some() {
2313 if let Err(error) = self.pause_elevated_automation(&mut automation) {
2314 tracing::warn!(
2315 "Could not pause automation {} that carries elevated permissions: {error:#}",
2316 automation.id
2317 );
2318 }
2319 continue;
2320 }
2321 // An owned definition whose schedule cannot be evaluated is
2322 // quarantined like a damaged file: left untouched (a newer
2323 // build may understand it), diagnosed every pass, and never
2324 // allowed to take down the rest of the collection.
2325 let schedule = match AutomationSchedule::parse_rrule(&automation.rrule) {
2326 Ok(schedule) => schedule,
2327 Err(error) => {
2328 tracing::warn!(
2329 "Skipping automation {} with unevaluable schedule {:?}: {error:#}",
2330 automation.id,
2331 automation.rrule
2332 );
2333 continue;
2334 }
2335 };
2336 let Some(due_at) = automation.next_run_at else {
2337 automation.next_run_at =
2338 match schedule.next_after_with_anchor(now, automation.created_at) {
2339 Ok(next) => Some(next),
2340 Err(error)
2341 if matches!(schedule, AutomationSchedule::Once { .. })
2342 && error
2343 .to_string()
2344 .contains("Once schedule has no future run") =>
2345 {
2346 automation.status = AutomationStatus::Paused;
2347 None
2348 }
2349 Err(error) => {
2350 tracing::warn!(
2351 "Skipping automation {} whose schedule cannot produce a slot: {error:#}",
2352 automation.id
2353 );
2354 continue;
2355 }
2356 };
2357 automation.updated_at = now;
2358 self.save_automation_unlocked(&automation)?;
2359 continue;
2360 };
2361 if due_at <= now {
2362 match self.due_disposition(
2363 &mut automation,
2364 &schedule,
2365 due_at,
2366 now,
2367 awake_since,
2368 ) {
2369 Ok(DueDisposition::Due) => due.push((
2370 automation.clone(),
2371 new_run_record(&automation.id, due_at, now),
2372 )),
2373 Ok(DueDisposition::Held) => {}
2374 Err(error) => {
2375 tracing::warn!(
2376 "Holding automation {} whose missed-run state cannot be evaluated: {error:#}",
2377 automation.id
2378 );
2379 }
2380 }
2381 }
2382 }
2383 Ok(due)
2384 })
2385 }
2386
2387 fn claim_scheduled_run(
2388 &self,
2389 observed: &AutomationRecord,
2390 mut run: AutomationRunRecord,
2391 task_data_dir: &Path,
2392 ) -> Result<Option<AutomationRunRecord>> {
2393 self.with_transaction(|| {
2394 if !self.automation_path(&observed.id)?.try_exists()? {
2395 return Ok(None);
2396 }
2397 let mut current = self.get_automation(&observed.id)?;
2398 if !self.eligible_scope(current.execution_scope.as_deref())
2399 || current != *observed
2400 || current.status != AutomationStatus::Active
2401 || current.next_run_at != Some(run.scheduled_for)
2402 {
2403 return Ok(None);
2404 }
2405 let schedule = AutomationSchedule::parse_rrule(&current.rrule)?;
2406 // Include the complete history, including legacy occurrence ids.
2407 let history = self.list_runs_with_visibility(&current.id, None, true)?;
2408 if history
2409 .iter()
2410 .any(|existing| existing.scheduled_for == run.scheduled_for)
2411 {
2412 self.advance_automation_after_slot(
2413 &mut current,
2414 &schedule,
2415 run.scheduled_for,
2416 Utc::now(),
2417 )?;
2418 return Ok(None);
2419 }
2420 // Keep the owed slot until the earlier run settles. Its eventual
2421 // catch-up coalesces the backlog without overlapping executions
2422 // or inventing cancellation receipts. Explicit run-now requests
2423 // remain operator intent and stay ungated.
2424 if history.iter().any(|existing| {
2425 matches!(
2426 existing.status,
2427 AutomationRunStatus::Queued | AutomationRunStatus::Running
2428 )
2429 }) {
2430 return Ok(None);
2431 }
2432 bind_run_dispatch(&mut run, &current, task_data_dir, true)?;
2433 self.save_run(&run)?;
2434 // The durable claim is the point of no return. Pausing after
2435 // this point affects future occurrences, not this admitted work
2436 // (deleting an automation with an admitted run is refused).
2437 // No task can start before the binding above is durable.
2438 self.advance_automation_after_slot(
2439 &mut current,
2440 &schedule,
2441 run.scheduled_for,
2442 Utc::now(),
2443 )?;
2444 Ok(Some(run))
2445 })
2446 }
2447
2448 /// Repair only a torn claim/advance transaction. A replacement definition,
2449 /// pause, or Operate kick has a different generation or slot and wins.
2450 fn recover_schedule_advance(&self, run: &AutomationRunRecord) -> Result<()> {
2451 let Some(admitted) = run
2452 .dispatch
2453 .as_ref()
2454 .and_then(|dispatch| dispatch.schedule.as_ref())
2455 else {
2456 return Ok(());
2457 };
2458 self.with_transaction(|| {
2459 if !self.automation_path(&run.automation_id)?.try_exists()? {
2460 return Ok(());
2461 }
2462 let mut current = self.get_automation(&run.automation_id)?;
2463 if current.status == AutomationStatus::Active
2464 && current.updated_at == admitted.updated_at
2465 && current.rrule == admitted.rrule
2466 && current.next_run_at == Some(run.scheduled_for)
2467 {
2468 let schedule = AutomationSchedule::parse_rrule(&current.rrule)?;
2469 self.advance_automation_after_slot(
2470 &mut current,
2471 &schedule,
2472 run.scheduled_for,
2473 Utc::now(),
2474 )?;
2475 }
2476 Ok(())
2477 })
2478 }
2479
2480 /// Completion publishes only this occurrence's receipt. It never advances
2481 /// a definition that may have been edited during the enqueue await.
2482 fn finish_scheduled_run(&self, run: &AutomationRunRecord, now: DateTime<Utc>) -> Result<()> {
2483 self.with_transaction(|| {
2484 self.save_run(run)?;
2485 if matches!(
2486 run.status,
2487 AutomationRunStatus::Completed
2488 | AutomationRunStatus::Failed
2489 | AutomationRunStatus::Canceled
2490 ) && !run
2491 .dispatch
2492 .as_ref()
2493 .is_some_and(|dispatch| dispatch.suppress_report)
2494 && self.automation_path(&run.automation_id)?.try_exists()?
2495 {
2496 let mut current = self.get_automation(&run.automation_id)?;
2497 let ended = run.ended_at.unwrap_or(now);
2498 current.last_run_at = Some(
2499 current
2500 .last_run_at
2501 .map_or(ended, |previous| previous.max(ended)),
2502 );
2503 // Receipt metadata is not a new schedule generation. Never
2504 // recompute the current definition from this run's old slot.
2505 self.save_automation_unlocked(&current)?;
2506 }
2507 Ok(())
2508 })
2509 }
2510
2511 fn advance_automation_after_slot(
2512 &self,
2513 automation: &mut AutomationRecord,
2514 schedule: &AutomationSchedule,
2515 slot: DateTime<Utc>,
2516 now: DateTime<Utc>,
2517 ) -> Result<()> {
2518 automation.updated_at = now;
2519 automation.next_run_at = schedule.next_unskipped_slot(slot, now, automation.created_at)?;
2520 if automation.next_run_at.is_none() {
2521 automation.status = AutomationStatus::Paused;
2522 }
2523 self.save_automation_unlocked(automation)
2524 }
2525
2526 fn missed_path(&self, automation_id: &str) -> Result<PathBuf> {
2527 ensure_safe_storage_id("automation id", automation_id)?;
2528 Ok(self.missed_dir.join(format!("{automation_id}.json")))
2529 }
2530
2531 fn presence_path(&self) -> Result<PathBuf> {
2532 Ok(self
2533 .automations_dir
2534 .parent()
2535 .context("automation root")?
2536 .join(SCHEDULER_PRESENCE_FILE))
2537 }
2538
2539 fn read_missed_state(&self, automation_id: &str) -> Result<AutomationMissedState> {
2540 let path = self.missed_path(automation_id)?;
2541 if !path.try_exists()? {
2542 return Ok(AutomationMissedState::default());
2543 }
2544 let bytes = fs::read(&path).with_context(|| format!("read {}", path.display()))?;
2545 serde_json::from_slice(&bytes).with_context(|| format!("parse {}", path.display()))
2546 }
2547
2548 fn save_missed_state(&self, automation_id: &str, state: &AutomationMissedState) -> Result<()> {
2549 write_json_atomic(&self.missed_path(automation_id)?, state)
2550 }
2551
2552 fn missed_status_for(
2553 automation: &AutomationRecord,
2554 state: AutomationMissedState,
2555 ) -> AutomationMissedStatus {
2556 AutomationMissedStatus {
2557 automation_id: automation.id.clone(),
2558 name: automation.name.clone(),
2559 policy: state
2560 .policy
2561 .unwrap_or_else(|| default_missed_policy(automation)),
2562 policy_is_default: state.policy.is_none(),
2563 owed: valid_owed(automation, &state),
2564 outcomes: state.outcomes,
2565 }
2566 }
2567
2568 pub fn missed_status(&self, automation_id: &str) -> Result<AutomationMissedStatus> {
2569 let automation = self.get_automation(automation_id)?;
2570 let state = self.read_missed_state(automation_id)?;
2571 Ok(Self::missed_status_for(&automation, state))
2572 }
2573
2574 pub fn list_missed(&self) -> Result<Vec<AutomationMissedStatus>> {
2575 let mut out = Vec::new();
2576 for automation in self.readable_automations()? {
2577 let state = match self.read_missed_state(&automation.id) {
2578 Ok(state) => state,
2579 Err(error) => {
2580 tracing::warn!(
2581 "Skipping damaged missed-run state for automation {}: {error:#}",
2582 automation.id
2583 );
2584 continue;
2585 }
2586 };
2587 let status = Self::missed_status_for(&automation, state);
2588 if status.owed.is_some() {
2589 out.push(status);
2590 }
2591 }
2592 out.sort_by_key(|status| status.owed.as_ref().map(|owed| owed.due_at));
2593 Ok(out)
2594 }
2595
2596 pub fn set_missed_policy(
2597 &self,
2598 automation_id: &str,
2599 policy: Option<AutomationMissedPolicy>,
2600 ) -> Result<AutomationMissedStatus> {
2601 self.with_transaction(|| {
2602 let automation = self.get_automation(automation_id)?;
2603 let mut state = self.read_missed_state(automation_id)?;
2604 state.policy = policy;
2605 self.save_missed_state(automation_id, &state)?;
2606 self.emit_automation_event("automation.updated", &automation);
2607 Ok(Self::missed_status_for(&automation, state))
2608 })
2609 }
2610
2611 pub fn note_scheduler_presence(
2612 &self,
2613 now: DateTime<Utc>,
2614 grace: Duration,
2615 ) -> Result<DateTime<Utc>> {
2616 self.with_transaction(|| {
2617 let path = self.presence_path()?;
2618 let previous = self.read_presence();
2619 let awake_since = match previous {
2620 Some(previous) if now - previous.last_tick <= grace => {
2621 previous.awake_since.min(now)
2622 }
2623 _ => now,
2624 };
2625 write_json_atomic(
2626 &path,
2627 &SchedulerPresence {
2628 awake_since,
2629 last_tick: now,
2630 },
2631 )?;
2632 Ok(awake_since)
2633 })
2634 }
2635
2636 fn read_presence(&self) -> Option<SchedulerPresence> {
2637 let path = self.presence_path().ok()?;
2638 let bytes = match fs::read(&path) {
2639 Ok(bytes) => bytes,
2640 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return None,
2641 Err(error) => {
2642 tracing::warn!(
2643 "Unreadable scheduler presence {}: {error:#}",
2644 path.display()
2645 );
2646 return None;
2647 }
2648 };
2649 match serde_json::from_slice(&bytes) {
2650 Ok(presence) => Some(presence),
2651 Err(error) => {
2652 tracing::warn!("Damaged scheduler presence {}: {error:#}", path.display());
2653 None
2654 }
2655 }
2656 }
2657
2658 fn due_disposition(
2659 &self,
2660 automation: &mut AutomationRecord,
2661 schedule: &AutomationSchedule,
2662 due_at: DateTime<Utc>,
2663 now: DateTime<Utc>,
2664 awake_since: Option<DateTime<Utc>>,
2665 ) -> Result<DueDisposition> {
2666 let mut state = self.read_missed_state(&automation.id)?;
2667 if state
2668 .owed
2669 .as_ref()
2670 .is_some_and(|owed| owed.due_at == due_at)
2671 {
2672 return Ok(DueDisposition::Held);
2673 }
2674 if !awake_since.is_some_and(|awake_since| due_at < awake_since) {
2675 return Ok(DueDisposition::Due);
2676 }
2677 match state
2678 .policy
2679 .unwrap_or_else(|| default_missed_policy(automation))
2680 {
2681 AutomationMissedPolicy::RunOnce => Ok(DueDisposition::Due),
2682 AutomationMissedPolicy::Skip => {
2683 state.owed = None;
2684 push_missed_outcome(
2685 &mut state,
2686 MissedRunOutcome {
2687 due_at,
2688 decided_at: now,
2689 outcome: MissedRunOutcomeKind::Skipped,
2690 decided_by: MissedRunDecider::Policy,
2691 run_id: None,
2692 },
2693 );
2694 self.save_missed_state(&automation.id, &state)?;
2695 self.advance_automation_after_slot(automation, schedule, due_at, now)?;
2696 self.emit_automation_event("automation.missed_skipped", automation);
2697 Ok(DueDisposition::Held)
2698 }
2699 AutomationMissedPolicy::Ask => {
2700 state.owed = Some(OwedOccurrence {
2701 due_at,
2702 detected_at: now,
2703 });
2704 self.save_missed_state(&automation.id, &state)?;
2705 self.emit_automation_event("automation.missed", automation);
2706 Ok(DueDisposition::Held)
2707 }
2708 }
2709 }
2710
2711 fn admit_missed_decision(
2712 &self,
2713 automation_id: &str,
2714 decision: MissedRunDecision,
2715 task_data_dir: &Path,
2716 now: DateTime<Utc>,
2717 ) -> Result<(AutomationMissedStatus, Option<AutomationRunRecord>)> {
2718 self.with_transaction(|| {
2719 let mut current = self.get_automation(automation_id)?;
2720 if !self.eligible_scope(current.execution_scope.as_deref()) {
2721 bail!("Automation belongs to another Runtime execution scope");
2722 }
2723 let mut state = self.read_missed_state(automation_id)?;
2724 let Some(owed) = valid_owed(&current, &state) else {
2725 if state.owed.take().is_some() {
2726 self.save_missed_state(automation_id, &state)?;
2727 }
2728 bail!("No missed run of {} is waiting for an answer", current.name);
2729 };
2730 let schedule = AutomationSchedule::parse_rrule(&current.rrule)?;
2731 let mut outcome = MissedRunOutcome {
2732 due_at: owed.due_at,
2733 decided_at: now,
2734 outcome: MissedRunOutcomeKind::Skipped,
2735 decided_by: MissedRunDecider::Person,
2736 run_id: None,
2737 };
2738 let mut admitted = None;
2739 if decision == MissedRunDecision::RunNow {
2740 let history = self.list_runs_with_visibility(automation_id, None, true)?;
2741 if history.iter().any(|existing| {
2742 matches!(
2743 existing.status,
2744 AutomationRunStatus::Queued | AutomationRunStatus::Running
2745 )
2746 }) {
2747 bail!(
2748 "An earlier run of {} is still in progress; answer again when it finishes",
2749 current.name
2750 );
2751 }
2752 outcome.outcome = MissedRunOutcomeKind::Ran;
2753 if let Some(existing) = history
2754 .iter()
2755 .find(|existing| existing.scheduled_for == owed.due_at)
2756 {
2757 outcome.run_id = Some(existing.id.clone());
2758 } else {
2759 let mut run = new_run_record(automation_id, owed.due_at, now);
2760 bind_run_dispatch(&mut run, &current, task_data_dir, true)?;
2761 self.save_run(&run)?;
2762 outcome.run_id = Some(run.id.clone());
2763 admitted = Some(run);
2764 }
2765 }
2766 state.owed = None;
2767 push_missed_outcome(&mut state, outcome);
2768 self.save_missed_state(automation_id, &state)?;
2769 self.advance_automation_after_slot(&mut current, &schedule, owed.due_at, now)?;
2770 Ok((Self::missed_status_for(&current, state), admitted))
2771 })
2772 }
2773
2774 /// Active receipts are independent of the definition's lifetime and of
2775 /// presentation limits on recent history.
2776 fn collect_pending_runs(&self) -> Result<Vec<AutomationRunRecord>> {
2777 let mut pending = Vec::new();
2778 for entry in fs::read_dir(&self.runs_dir)? {
2779 let entry = entry?;
2780 if !entry.file_type()?.is_dir() {
2781 continue;
2782 }
2783 let Some(id) = entry.file_name().to_str().map(str::to_owned) else {
2784 continue;
2785 };
2786 // A damaged receipt quarantines only its own automation: the bytes
2787 // stay on disk and the diagnostic is logged every pass, but one
2788 // corrupt file must not block recovery of every other pending run.
2789 let runs = match self.list_runs_with_visibility(&id, None, true) {
2790 Ok(runs) => runs,
2791 Err(error) => {
2792 tracing::warn!("Skipping damaged run history for automation {id}: {error:#}");
2793 continue;
2794 }
2795 };
2796 for run in runs {
2797 if matches!(
2798 run.status,
2799 AutomationRunStatus::Queued | AutomationRunStatus::Running
2800 ) && run.task_id.is_some()
2801 {
2802 pending.push(run);
2803 }
2804 }
2805 }
2806 Ok(pending)
2807 }
2808
2809 // ── Delayed-trigger storage methods ──────────────────────────────────
2810
2811 /// Persist a new delayed trigger and return the record.
2812 pub fn create_trigger(&self, req: CreateDelayedTriggerRequest) -> Result<DelayedTriggerRecord> {
2813 let now = Utc::now();
2814 if req.fire_at <= now {
2815 bail!(
2816 "fire_at must be in the future (got {}, now is {})",
2817 req.fire_at.to_rfc3339(),
2818 now.to_rfc3339()
2819 );
2820 }
2821 if req.message.trim().is_empty() {
2822 bail!("Trigger message must not be empty");
2823 }
2824 let disallowed_tools = crate::task_manager::normalize_deny_rules(req.disallowed_tools);
2825 let record = DelayedTriggerRecord {
2826 schema_version: if disallowed_tools.is_empty() {
2827 CURRENT_TRIGGER_SCHEMA_VERSION
2828 } else {
2829 DENY_RULES_TRIGGER_SCHEMA_VERSION
2830 },
2831 execution_scope: self.execution_scope.clone(),
2832 trigger_id: format!("trig_{}", Uuid::new_v4().simple()),
2833 fire_at: req.fire_at,
2834 message: req.message.trim().to_string(),
2835 workspace: req.workspace,
2836 owner_session_id: req.owner_session_id,
2837 destination_thread_id: normalize_optional_string(req.destination_thread_id),
2838 disallowed_tools,
2839 status: DelayedTriggerStatus::Pending,
2840 created_at: now,
2841 fired_at: None,
2842 task_id: None,
2843 thread_id: None,
2844 error: None,
2845 parent_trigger_id: req.parent_trigger_id,
2846 dispatch: None,
2847 };
2848 self.save_trigger(&record)?;
2849 self.trigger_wakeup.notify_one();
2850 self.emit_trigger_event("trigger.scheduled", &record);
2851 Ok(record)
2852 }
2853
2854 /// Load a trigger by id.
2855 pub fn get_trigger(&self, trigger_id: &str) -> Result<DelayedTriggerRecord> {
2856 let path = self.trigger_path(trigger_id)?;
2857 let raw = fs::read_to_string(&path)
2858 .with_context(|| format!("Trigger '{trigger_id}' not found"))?;
2859 let record: DelayedTriggerRecord = serde_json::from_str(&raw)
2860 .with_context(|| format!("Failed to parse trigger '{trigger_id}'"))?;
2861 if record.schema_version > MAX_SUPPORTED_TRIGGER_SCHEMA_VERSION {
2862 bail!(
2863 "Trigger schema v{} is newer than supported v{}",
2864 record.schema_version,
2865 MAX_SUPPORTED_TRIGGER_SCHEMA_VERSION
2866 );
2867 }
2868 Ok(record)
2869 }
2870
2871 /// Load a trigger only when it belongs to the given session.
2872 ///
2873 /// Foreign, ownerless legacy, unreadable, and absent records share the same
2874 /// result so trigger existence cannot be disclosed across sessions.
2875 pub fn get_trigger_for_owner(
2876 &self,
2877 trigger_id: &str,
2878 owner_session_id: &str,
2879 ) -> Result<DelayedTriggerRecord> {
2880 self.get_trigger(trigger_id)
2881 .ok()
2882 .filter(|record| record.owner_session_id.as_deref() == Some(owner_session_id))
2883 .ok_or_else(|| anyhow::anyhow!("Trigger '{trigger_id}' not found"))
2884 }
2885
2886 /// Atomically persist a trigger record.
2887 pub fn save_trigger(&self, record: &DelayedTriggerRecord) -> Result<()> {
2888 self.with_transaction(|| self.save_trigger_unlocked(record))
2889 }
2890
2891 fn save_trigger_unlocked(&self, record: &DelayedTriggerRecord) -> Result<()> {
2892 let path = self.trigger_path(&record.trigger_id)?;
2893 let min_version = required_trigger_schema_version(record);
2894 if record.schema_version < min_version {
2895 let mut updated = record.clone();
2896 updated.schema_version = min_version;
2897 return write_json_atomic(&path, &updated);
2898 }
2899 write_json_atomic(&path, record)
2900 }
2901
2902 /// List triggers, newest first. Pass `status_filter` to restrict results.
2903 pub fn list_triggers(
2904 &self,
2905 status_filter: Option<DelayedTriggerStatus>,
2906 limit: Option<usize>,
2907 ) -> Result<Vec<DelayedTriggerRecord>> {
2908 let mut out = Vec::new();
2909 if !self.triggers_dir.exists() {
2910 return Ok(out);
2911 }
2912 for entry in fs::read_dir(&self.triggers_dir)
2913 .with_context(|| format!("Failed to read {}", self.triggers_dir.display()))?
2914 {
2915 let entry = entry?;
2916 let path = entry.path();
2917 if path.extension().is_none_or(|ext| ext != "json") {
2918 continue;
2919 }
2920 match fs::read_to_string(&path)
2921 .ok()
2922 .and_then(|raw| serde_json::from_str::<DelayedTriggerRecord>(&raw).ok())
2923 {
2924 Some(record) => {
2925 if record.schema_version > MAX_SUPPORTED_TRIGGER_SCHEMA_VERSION {
2926 tracing::warn!(
2927 "Skipping trigger file {} with unsupported schema v{}",
2928 path.display(),
2929 record.schema_version
2930 );
2931 continue;
2932 }
2933 if let Some(filter) = status_filter
2934 && record.status != filter
2935 {
2936 continue;
2937 }
2938 out.push(record);
2939 }
2940 None => {
2941 tracing::warn!("Skipping unreadable trigger file {}", path.display());
2942 }
2943 }
2944 }
2945 out.sort_by_key(|r| std::cmp::Reverse(r.created_at));
2946 if let Some(limit) = limit {
2947 out.truncate(limit);
2948 }
2949 Ok(out)
2950 }
2951
2952 /// List session-owned triggers, applying ownership before sorting and limit.
2953 pub fn list_triggers_for_owner(
2954 &self,
2955 status_filter: Option<DelayedTriggerStatus>,
2956 limit: Option<usize>,
2957 owner_session_id: &str,
2958 ) -> Result<Vec<DelayedTriggerRecord>> {
2959 let mut records = self.list_triggers(status_filter, None)?;
2960 records.retain(|record| record.owner_session_id.as_deref() == Some(owner_session_id));
2961 if let Some(limit) = limit {
2962 records.truncate(limit);
2963 }
2964 Ok(records)
2965 }
2966
2967 /// Cancel a pending trigger owned by the given session.
2968 pub fn cancel_trigger_for_owner(
2969 &self,
2970 trigger_id: &str,
2971 owner_session_id: &str,
2972 ) -> Result<DelayedTriggerRecord> {
2973 self.cancel_trigger_visible_to(trigger_id, Some(owner_session_id))
2974 }
2975
2976 pub fn cancel_trigger(&self, trigger_id: &str) -> Result<DelayedTriggerRecord> {
2977 self.cancel_trigger_visible_to(trigger_id, None)
2978 }
2979
2980 fn cancel_trigger_visible_to(
2981 &self,
2982 trigger_id: &str,
2983 owner_session_id: Option<&str>,
2984 ) -> Result<DelayedTriggerRecord> {
2985 let record = self.with_transaction(|| {
2986 let mut record = match owner_session_id {
2987 Some(owner) => self.get_trigger_for_owner(trigger_id, owner)?,
2988 None => self.get_trigger(trigger_id)?,
2989 };
2990 if record.status != DelayedTriggerStatus::Pending || record.dispatch.is_some() {
2991 bail!(
2992 "Trigger '{trigger_id}' cannot be canceled after admission (status: {:?})",
2993 record.status
2994 );
2995 }
2996 record.status = DelayedTriggerStatus::Canceled;
2997 self.save_trigger_unlocked(&record)?;
2998 Ok(record)
2999 })?;
3000 self.trigger_wakeup.notify_one();
3001 self.emit_trigger_event("trigger.canceled", &record);
3002 Ok(record)
3003 }
3004
3005 pub(crate) fn trigger_wakeup(&self) -> Arc<Notify> {
3006 Arc::clone(&self.trigger_wakeup)
3007 }
3008
3009 pub(crate) fn trigger_wait_duration(
3010 &self,
3011 now: DateTime<Utc>,
3012 max_wait: std::time::Duration,
3013 ) -> Result<std::time::Duration> {
3014 let next_fire_at = self
3015 .list_triggers(Some(DelayedTriggerStatus::Pending), None)?
3016 .into_iter()
3017 .filter(|trigger| {
3018 trigger.owner_session_id.is_some()
3019 && self.eligible_scope(trigger.execution_scope.as_deref())
3020 })
3021 .map(|trigger| trigger.fire_at)
3022 .min();
3023 let wait = match next_fire_at {
3024 Some(fire_at) if fire_at <= now => std::time::Duration::ZERO,
3025 Some(fire_at) => (fire_at - now)
3026 .to_std()
3027 .unwrap_or(max_wait)
3028 .clamp(std::time::Duration::ZERO, max_wait),
3029 None => max_wait,
3030 };
3031 Ok(wait)
3032 }
3033
3034 /// Return due proposals and unfinished durable trigger admissions.
3035 pub fn collect_due_triggers(&self, now: DateTime<Utc>) -> Result<Vec<DelayedTriggerRecord>> {
3036 Ok(self
3037 .list_triggers(None, None)?
3038 .into_iter()
3039 .filter(|trigger| {
3040 trigger.status == DelayedTriggerStatus::Dispatching
3041 || (trigger.status == DelayedTriggerStatus::Pending
3042 && trigger.owner_session_id.is_some()
3043 && trigger.fire_at <= now)
3044 })
3045 .collect())
3046 }
3047 }
3048
3049 fn valid_owed(
3050 automation: &AutomationRecord,
3051 state: &AutomationMissedState,
3052 ) -> Option<OwedOccurrence> {
3053 state.owed.clone().filter(|owed| {
3054 automation.status == AutomationStatus::Active && automation.next_run_at == Some(owed.due_at)
3055 })
3056 }
3057
3058 fn push_missed_outcome(state: &mut AutomationMissedState, outcome: MissedRunOutcome) {
3059 if state
3060 .outcomes
3061 .last()
3062 .is_some_and(|last| last.due_at == outcome.due_at && last.outcome == outcome.outcome)
3063 {
3064 return;
3065 }
3066 state.outcomes.push(outcome);
3067 let excess = state
3068 .outcomes
3069 .len()
3070 .saturating_sub(MISSED_OUTCOMES_RETAINED);
3071 state.outcomes.drain(..excess);
3072 }
3073
3074 pub async fn resolve_missed_run_shared(
3075 automations: &SharedAutomationManager,
3076 automation_id: &str,
3077 decision: MissedRunDecision,
3078 task_manager: &SharedTaskManager,
3079 ) -> Result<MissedRunResolution> {
3080 automations.lock().await.bind_task_manager(task_manager)?;
3081 let task_manager = Arc::clone(task_manager);
3082 let task_data_dir = task_manager.data_dir();
3083 resolve_missed_run_inner(
3084 automations,
3085 automation_id,
3086 decision,
3087 &task_data_dir,
3088 Utc::now(),
3089 move |mut run| async move {
3090 enqueue_run_task(&mut run, &task_manager).await;
3091 run
3092 },
3093 )
3094 .await
3095 }
3096
3097 async fn resolve_missed_run_inner<F, Fut>(
3098 automations: &SharedAutomationManager,
3099 automation_id: &str,
3100 decision: MissedRunDecision,
3101 task_data_dir: &Path,
3102 now: DateTime<Utc>,
3103 enqueue: F,
3104 ) -> Result<MissedRunResolution>
3105 where
3106 F: FnOnce(AutomationRunRecord) -> Fut,
3107 Fut: Future<Output = AutomationRunRecord>,
3108 {
3109 let mut lock = automations.lock().await.open_lock("dispatch.lock")?;
3110 let _dispatch = lock
3111 .try_write()
3112 .context("Automation dispatcher is busy; retry the answer")?;
3113 let (status, admitted) = with_manager_blocking(automations, {
3114 let automation_id = automation_id.to_string();
3115 let task_data_dir = task_data_dir.to_path_buf();
3116 move |manager| manager.admit_missed_decision(&automation_id, decision, &task_data_dir, now)
3117 })
3118 .await?;
3119 let run = match admitted {
3120 Some(run) => {
3121 let run = enqueue(run).await;
3122 with_manager_blocking(automations, {
3123 let run = run.clone();
3124 move |manager| manager.finish_scheduled_run(&run, Utc::now())
3125 })
3126 .await?;
3127 Some(run)
3128 }
3129 None => None,
3130 };
3131 Ok(MissedRunResolution { status, run })
3132 }
3133
3134 fn new_run_record(
3135 automation_id: &str,
3136 scheduled_for: DateTime<Utc>,
3137 created_at: DateTime<Utc>,
3138 ) -> AutomationRunRecord {
3139 AutomationRunRecord {
3140 schema_version: CURRENT_RUN_SCHEMA_VERSION,
3141 id: Uuid::new_v4().to_string(),
3142 automation_id: automation_id.to_string(),
3143 scheduled_for,
3144 status: AutomationRunStatus::Queued,
3145 created_at,
3146 started_at: None,
3147 ended_at: None,
3148 task_id: None,
3149 thread_id: None,
3150 turn_id: None,
3151 error: None,
3152 dispatch: None,
3153 }
3154 }
3155
3156 /// The posture an automation's `auto_approve` bit stands for, in the wire
3157 /// spelling a task request carries.
3158 ///
3159 /// A scheduled run fires with no session to inherit from, so the only authority
3160 /// it has is its own record — and stating it explicitly keeps the scheduled
3161 /// task from re-deriving a posture out of a legacy bit on every later change to
3162 /// what that bit means.
3163 fn automation_posture(auto_approve: bool) -> String {
3164 codewhale_runtime::runtime_policy::approval_wire(
3165 codewhale_execpolicy::ApprovalMode::from_auto_approve(auto_approve),
3166 )
3167 .to_string()
3168 }
3169
3170 fn automation_task_request(automation: &AutomationRecord) -> NewTaskRequest {
3171 NewTaskRequest {
3172 prompt: automation.prompt.clone(),
3173 name: Some(automation.name.clone()),
3174 model: automation.model.clone(),
3175 model_provider: automation.model_provider.clone(),
3176 model_provider_id: automation.model_provider_id.clone(),
3177 workspace: automation.cwds.first().cloned(),
3178 mode: Some(automation.task_mode()),
3179 allow_shell: Some(automation.task_allow_shell()),
3180 trust_mode: Some(automation.task_trust_mode()),
3181 auto_approve: Some(automation.task_auto_approve()),
3182 permission_posture: Some(automation_posture(automation.task_auto_approve())),
3183 disallowed_tools: automation.disallowed_tools.clone(),
3184 owner_session_id: None,
3185 destination_thread_id: automation.destination_thread_id.clone(),
3186 }
3187 }
3188
3189 #[derive(Debug)]
3190 struct ElevatedDispatchRefused;
3191
3192 impl std::fmt::Display for ElevatedDispatchRefused {
3193 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3194 f.write_str(
3195 "Refusing to dispatch unattended automation with elevated permissions without an owner session",
3196 )
3197 }
3198 }
3199
3200 impl std::error::Error for ElevatedDispatchRefused {}
3201
3202 fn unattended_elevated(request: &NewTaskRequest) -> bool {
3203 let missing_owner = request
3204 .owner_session_id
3205 .as_deref()
3206 .map(str::trim)
3207 .filter(|id| !id.is_empty())
3208 .is_none();
3209 let bypass_posture = request
3210 .permission_posture
3211 .as_deref()
3212 .and_then(codewhale_execpolicy::ApprovalMode::from_config_value)
3213 == Some(codewhale_execpolicy::ApprovalMode::Bypass);
3214 missing_owner
3215 && (request.auto_approve.unwrap_or(false)
3216 || request.trust_mode.unwrap_or(false)
3217 || request.allow_shell.unwrap_or(false)
3218 || bypass_posture)
3219 }
3220
3221 fn reject_unattended_elevated_request(request: &NewTaskRequest) -> Result<()> {
3222 if unattended_elevated(request) {
3223 return Err(ElevatedDispatchRefused.into());
3224 }
3225 Ok(())
3226 }
3227
3228 fn bind_run_dispatch(
3229 run: &mut AutomationRunRecord,
3230 automation: &AutomationRecord,
3231 task_data_dir: &Path,
3232 scheduled: bool,
3233 ) -> Result<()> {
3234 if automation.execution_scope.is_none() {
3235 bail!("Automation execution ownership is unverified");
3236 }
3237 let request = automation_task_request(automation);
3238 reject_unattended_elevated_request(&request)?;
3239 let min_version = if request.disallowed_tools.is_empty() {
3240 CURRENT_RUN_SCHEMA_VERSION
3241 } else {
3242 DENY_RULES_RUN_SCHEMA_VERSION
3243 };
3244 run.schema_version = run.schema_version.max(min_version);
3245 run.task_id = Some(crate::task_manager::TaskManager::new_task_id());
3246 run.dispatch = Some(AutomationDispatch {
3247 execution_scope: automation.execution_scope.clone(),
3248 request,
3249 task_data_dir: task_data_dir
3250 .canonicalize()
3251 .context("resolve task store before automation admission")?,
3252 accepted: false,
3253 delivery_mode: automation.delivery_mode(),
3254 suppress_report: false,
3255 schedule: scheduled.then(|| AdmittedSchedule {
3256 updated_at: automation.updated_at,
3257 rrule: automation.rrule.clone(),
3258 }),
3259 });
3260 Ok(())
3261 }
3262
3263 fn check_dispatch_store(dispatch: &AutomationDispatch, tasks: &SharedTaskManager) -> Result<()> {
3264 if tasks.data_dir().canonicalize()? != dispatch.task_data_dir.canonicalize()? {
3265 bail!("Automation admission belongs to a different task store; it cannot be replayed here");
3266 }
3267 Ok(())
3268 }
3269
3270 async fn dispatch_bound_task(
3271 dispatch: &mut AutomationDispatch,
3272 task_id: &str,
3273 tasks: &SharedTaskManager,
3274 ) -> Result<crate::task_manager::TaskRecord> {
3275 check_dispatch_store(dispatch, tasks)?;
3276 if !dispatch.accepted {
3277 reject_unattended_elevated_request(&dispatch.request)?;
3278 }
3279 if dispatch.execution_scope.as_deref() != Some(tasks.execution_scope()) {
3280 bail!(
3281 "Automation admission execution ownership is unverified or belongs to another Runtime"
3282 );
3283 }
3284 let task = if dispatch.accepted {
3285 tasks
3286 .read_bound_task(task_id)?
3287 .context("Accepted automation task is missing; refusing to replay it")?
3288 } else {
3289 tasks
3290 .recover_task_admission(dispatch.request.clone(), task_id.to_owned())
3291 .await?
3292 };
3293 crate::task_manager::validate_bound_task_request(&task, &dispatch.request)?;
3294 dispatch.accepted = true;
3295 dispatch.suppress_report = dispatch.delivery_mode == AutomationDeliveryMode::Watcher
3296 && task.status == TaskStatus::Completed
3297 && task
3298 .result_summary
3299 .as_deref()
3300 .is_some_and(|summary| summary.trim() == AUTOMATION_WATCHER_NO_REPORT_SENTINEL);
3301 Ok(task)
3302 }
3303
3304 /// Caller owns dispatch.lock and has already persisted this exact binding.
3305 async fn enqueue_run_task(run: &mut AutomationRunRecord, tasks: &SharedTaskManager) {
3306 let result = match (&mut run.dispatch, &run.task_id) {
3307 (Some(dispatch), Some(task_id)) => dispatch_bound_task(dispatch, task_id, tasks).await,
3308 _ => Err(anyhow::anyhow!(
3309 "Automation run has no durable task binding"
3310 )),
3311 };
3312 match result {
3313 Ok(task) => {
3314 run.error = None;
3315 apply_task_status(run, &task);
3316 }
3317 Err(error) if error.downcast_ref::<ElevatedDispatchRefused>().is_some() => {
3318 run.status = AutomationRunStatus::Failed;
3319 run.ended_at = Some(Utc::now());
3320 run.error = Some(ELEVATED_AUTOMATION_RUN_REFUSAL.to_string());
3321 }
3322 Err(error) => {
3323 // Keep the same pending identity after uncertain admission. A later
3324 // tick first looks for its canonical task; no new id is allocated.
3325 run.error = Some(format!(
3326 "Automation task admission needs recovery: {error:#}"
3327 ));
3328 }
3329 }
3330 }
3331
3332 fn dispatch_lock_busy(error: &std::io::Error) -> bool {
3333 error.kind() == std::io::ErrorKind::WouldBlock || matches!(error.raw_os_error(), Some(32 | 33))
3334 }
3335
3336 pub async fn run_now_shared(
3337 automations: &SharedAutomationManager,
3338 automation_id: &str,
3339 task_manager: &SharedTaskManager,
3340 ) -> Result<AutomationRunRecord> {
3341 run_now_shared_if(automations, automation_id, None, task_manager).await
3342 }
3343
3344 pub async fn run_now_shared_if(
3345 automations: &SharedAutomationManager,
3346 automation_id: &str,
3347 expected_revision: Option<u64>,
3348 task_manager: &SharedTaskManager,
3349 ) -> Result<AutomationRunRecord> {
3350 automations.lock().await.bind_task_manager(task_manager)?;
3351 let task_manager = Arc::clone(task_manager);
3352 let task_data_dir = task_manager.data_dir();
3353 run_now_inner(
3354 automations,
3355 automation_id,
3356 expected_revision,
3357 &task_data_dir,
3358 move |_, mut run| async move {
3359 enqueue_run_task(&mut run, &task_manager).await;
3360 run
3361 },
3362 )
3363 .await
3364 }
3365
3366 #[cfg(test)]
3367 async fn run_now_with<F, Fut>(
3368 automations: &SharedAutomationManager,
3369 automation_id: &str,
3370 task_data_dir: &Path,
3371 enqueue: F,
3372 ) -> Result<AutomationRunRecord>
3373 where
3374 F: FnOnce(AutomationRecord, AutomationRunRecord) -> Fut,
3375 Fut: Future<Output = AutomationRunRecord>,
3376 {
3377 run_now_inner(automations, automation_id, None, task_data_dir, enqueue).await
3378 }
3379
3380 /// Keep the process-wide dispatch claim over the await, never the manager mutex.
3381 async fn run_now_inner<F, Fut>(
3382 automations: &SharedAutomationManager,
3383 automation_id: &str,
3384 expected_revision: Option<u64>,
3385 task_data_dir: &Path,
3386 enqueue: F,
3387 ) -> Result<AutomationRunRecord>
3388 where
3389 F: FnOnce(AutomationRecord, AutomationRunRecord) -> Fut,
3390 Fut: Future<Output = AutomationRunRecord>,
3391 {
3392 let mut lock = automations.lock().await.open_lock("dispatch.lock")?;
3393 let _dispatch = lock
3394 .try_write()
3395 .context("Automation dispatcher is busy; retry the run")?;
3396 let (automation, run) = {
3397 let manager = automations.lock().await;
3398 manager.with_transaction(|| {
3399 let mut automation = manager.get_automation(automation_id)?;
3400 check_expected_revision(&automation, expected_revision)?;
3401 manager.adopt_for_run(&mut automation)?;
3402 let now = Utc::now();
3403 let mut run = new_run_record(&automation.id, now, now);
3404 bind_run_dispatch(&mut run, &automation, task_data_dir, false)?;
3405 manager.save_run(&run)?;
3406 Ok((automation, run))
3407 })?
3408 };
3409 let run = enqueue(automation, run).await;
3410 automations
3411 .lock()
3412 .await
3413 .finish_scheduled_run(&run, Utc::now())?;
3414 Ok(run)
3415 }
3416
3417 /// Run a scheduler store operation on the blocking pool (#6149), holding the
3418 /// manager lock exactly as the inline call did: the whole-store scans (every
3419 /// automation or run record read and parsed) and the per-record claim,
3420 /// recovery, and receipt transactions, which wait on the cross-process
3421 /// `state.lock` and read/write JSON. Known limit: opening `dispatch.lock`
3422 /// (one small file open whose non-blocking guard must outlive the awaits)
3423 /// and the in-memory scope checks stay inline.
3424 async fn with_manager_blocking<T, F>(automations: &SharedAutomationManager, scan: F) -> Result<T>
3425 where
3426 T: Send + 'static,
3427 F: FnOnce(&AutomationManager) -> Result<T> + Send + 'static,
3428 {
3429 let manager = Arc::clone(automations).lock_owned().await;
3430 tokio::task::spawn_blocking(move || scan(&manager))
3431 .await
3432 .context("automation store scan task failed")?
3433 }
3434
3435 async fn scheduler_tick_shared(
3436 automations: &SharedAutomationManager,
3437 task_manager: &SharedTaskManager,
3438 ) -> Result<()> {
3439 automations.lock().await.bind_task_manager(task_manager)?;
3440 let tasks = Arc::clone(task_manager);
3441 scheduler_tick_with(automations, &tasks.data_dir(), move |mut run| {
3442 let tasks = Arc::clone(&tasks);
3443 async move {
3444 enqueue_run_task(&mut run, &tasks).await;
3445 run
3446 }
3447 })
3448 .await
3449 }
3450
3451 async fn scheduler_tick_with<F, Fut>(
3452 automations: &SharedAutomationManager,
3453 task_data_dir: &Path,
3454 mut enqueue: F,
3455 ) -> Result<()>
3456 where
3457 F: FnMut(AutomationRunRecord) -> Fut,
3458 Fut: Future<Output = AutomationRunRecord>,
3459 {
3460 let mut lock = automations.lock().await.open_lock("dispatch.lock")?;
3461 let _dispatch = match lock.try_write() {
3462 Ok(guard) => guard,
3463 Err(error) if dispatch_lock_busy(&error) => return Ok(()),
3464 Err(error) => return Err(error).context("claim automation dispatch"),
3465 };
3466 // Repair admitted work before collecting a new occurrence, including claims
3467 // whose definitions were edited/deleted or whose final enqueue save tore.
3468 let pending =
3469 with_manager_blocking(automations, AutomationManager::collect_pending_runs).await?;
3470 for run in pending.into_iter().filter(|run| {
3471 run.dispatch
3472 .as_ref()
3473 .is_some_and(|dispatch| !dispatch.accepted)
3474 }) {
3475 if !automations.lock().await.eligible_scope(
3476 run.dispatch
3477 .as_ref()
3478 .and_then(|dispatch| dispatch.execution_scope.as_deref()),
3479 ) {
3480 continue;
3481 }
3482 // A single damaged admission is quarantined to its diagnostic; it must
3483 // not take down recovery of every pending run behind it.
3484 let recovered = with_manager_blocking(automations, {
3485 let run = run.clone();
3486 move |manager| manager.recover_schedule_advance(&run)
3487 })
3488 .await;
3489 if let Err(error) = recovered {
3490 tracing::warn!(
3491 "automation schedule recovery failed for run {}: {error:#}",
3492 run.id
3493 );
3494 continue;
3495 }
3496 let run = enqueue(run).await;
3497 if let Err(error) = with_manager_blocking(automations, {
3498 let run = run.clone();
3499 move |manager| manager.finish_scheduled_run(&run, Utc::now())
3500 })
3501 .await
3502 {
3503 tracing::warn!(
3504 "automation run {} receipt could not be persisted: {error:#}",
3505 run.id
3506 );
3507 }
3508 }
3509 let now = Utc::now();
3510 let due =
3511 with_manager_blocking(automations, move |manager| manager.collect_due_runs(now)).await?;
3512 for (observed, proposed) in due {
3513 if !automations
3514 .lock()
3515 .await
3516 .eligible_scope(observed.execution_scope.as_deref())
3517 {
3518 continue;
3519 }
3520 let claimed = with_manager_blocking(automations, {
3521 let observed = observed.clone();
3522 let task_data_dir = task_data_dir.to_path_buf();
3523 move |manager| manager.claim_scheduled_run(&observed, proposed, &task_data_dir)
3524 })
3525 .await;
3526 let run = match claimed {
3527 Ok(run) => run,
3528 Err(error) => {
3529 // One automation's claim failure (for example a corrupt
3530 // receipt in its own dedup history) quarantines that
3531 // automation, not the tick: later due work still dispatches.
3532 tracing::warn!(
3533 "automation {} occurrence claim failed: {error:#}",
3534 observed.id
3535 );
3536 continue;
3537 }
3538 };
3539 let Some(run) = run else {
3540 continue;
3541 };
3542 let run = enqueue(run).await;
3543 if let Err(error) = with_manager_blocking(automations, {
3544 let run = run.clone();
3545 move |manager| manager.finish_scheduled_run(&run, now)
3546 })
3547 .await
3548 {
3549 tracing::warn!(
3550 "automation run {} receipt could not be persisted: {error:#}",
3551 run.id
3552 );
3553 }
3554 }
3555 Ok(())
3556 }
3557
3558 pub(crate) async fn fire_due_triggers_shared(
3559 automations: &SharedAutomationManager,
3560 task_manager: &SharedTaskManager,
3561 ) -> Result<()> {
3562 automations.lock().await.bind_task_manager(task_manager)?;
3563 let tasks = Arc::clone(task_manager);
3564 fire_due_triggers_with(automations, &tasks.data_dir(), move |trigger| {
3565 let tasks = Arc::clone(&tasks);
3566 async move { enqueue_trigger_task(trigger, &tasks).await }
3567 })
3568 .await
3569 }
3570
3571 async fn enqueue_trigger_task(
3572 mut trigger: DelayedTriggerRecord,
3573 tasks: &SharedTaskManager,
3574 ) -> Result<DelayedTriggerRecord> {
3575 let result = dispatch_bound_task(
3576 trigger.dispatch.as_mut().context("trigger dispatch")?,
3577 trigger.task_id.as_deref().context("trigger task binding")?,
3578 tasks,
3579 )
3580 .await;
3581 match result {
3582 Ok(task) => {
3583 trigger.status = DelayedTriggerStatus::Fired;
3584 trigger.fired_at = Some(Utc::now());
3585 trigger.thread_id = task
3586 .thread_id
3587 .clone()
3588 .or_else(|| trigger.destination_thread_id.clone());
3589 trigger.error = None;
3590 }
3591 Err(error) => {
3592 trigger.error = Some(format!(
3593 "Delayed trigger admission needs recovery: {error:#}"
3594 ))
3595 }
3596 }
3597 Ok(trigger)
3598 }
3599
3600 async fn fire_due_triggers_with<F, Fut>(
3601 automations: &SharedAutomationManager,
3602 task_data_dir: &Path,
3603 mut enqueue: F,
3604 ) -> Result<()>
3605 where
3606 F: FnMut(DelayedTriggerRecord) -> Fut,
3607 Fut: Future<Output = Result<DelayedTriggerRecord>>,
3608 {
3609 let mut lock = automations.lock().await.open_lock("dispatch.lock")?;
3610 let _dispatch = match lock.try_write() {
3611 Ok(guard) => guard,
3612 Err(error) if dispatch_lock_busy(&error) => return Ok(()),
3613 Err(error) => return Err(error).context("claim delayed-trigger dispatch"),
3614 };
3615 let now = Utc::now();
3616 let candidates = with_manager_blocking(automations, move |manager| {
3617 manager.collect_due_triggers(now)
3618 })
3619 .await?;
3620 for candidate in candidates {
3621 let scope = if candidate.status == DelayedTriggerStatus::Dispatching {
3622 candidate
3623 .dispatch
3624 .as_ref()
3625 .and_then(|d| d.execution_scope.as_deref())
3626 } else {
3627 candidate.execution_scope.as_deref()
3628 };
3629 if !automations.lock().await.eligible_scope(scope) {
3630 continue;
3631 }
3632 if !(candidate.status == DelayedTriggerStatus::Dispatching
3633 || (candidate.status == DelayedTriggerStatus::Pending && candidate.fire_at <= now))
3634 {
3635 continue;
3636 }
3637 let claim = with_manager_blocking(automations, {
3638 let trigger_id = candidate.trigger_id.clone();
3639 let task_data_dir = task_data_dir.to_path_buf();
3640 move |manager| {
3641 manager.with_transaction(|| {
3642 let mut current = manager.get_trigger(&trigger_id)?;
3643 if current.status == DelayedTriggerStatus::Dispatching {
3644 if !manager.eligible_scope(
3645 current
3646 .dispatch
3647 .as_ref()
3648 .and_then(|d| d.execution_scope.as_deref()),
3649 ) {
3650 return Ok(None);
3651 }
3652 if current.dispatch.is_none() || current.task_id.is_none() {
3653 bail!("Claimed delayed trigger has no durable task binding");
3654 }
3655 return Ok(Some(current));
3656 }
3657 if !manager.eligible_scope(current.execution_scope.as_deref())
3658 || current.status != DelayedTriggerStatus::Pending
3659 || current.fire_at > now
3660 || current.owner_session_id.is_none()
3661 {
3662 return Ok(None);
3663 }
3664 current.status = DelayedTriggerStatus::Dispatching;
3665 current.task_id = Some(crate::task_manager::TaskManager::new_task_id());
3666 current.dispatch = Some(AutomationDispatch {
3667 execution_scope: current.execution_scope.clone(),
3668 request: NewTaskRequest {
3669 prompt: current.message.clone(),
3670 name: None,
3671 model: None,
3672 model_provider: None,
3673 model_provider_id: None,
3674 workspace: current.workspace.clone(),
3675 mode: Some("agent".into()),
3676 allow_shell: Some(false),
3677 trust_mode: Some(false),
3678 auto_approve: Some(false),
3679 permission_posture: Some(automation_posture(false)),
3680 disallowed_tools: current.disallowed_tools.clone(),
3681 owner_session_id: current.owner_session_id.clone(),
3682 destination_thread_id: current.destination_thread_id.clone(),
3683 },
3684 task_data_dir: task_data_dir.canonicalize()?,
3685 accepted: false,
3686 delivery_mode: AutomationDeliveryMode::Task,
3687 suppress_report: false,
3688 schedule: None,
3689 });
3690 current.schema_version = current
3691 .schema_version
3692 .max(required_trigger_schema_version(&current));
3693 manager.save_trigger_unlocked(&current)?;
3694 Ok(Some(current))
3695 })
3696 }
3697 })
3698 .await;
3699 let claimed = match claim {
3700 Ok(claimed) => claimed,
3701 Err(error) => {
3702 // One damaged trigger record quarantines to a diagnostic;
3703 // the remaining due triggers still fire this pass.
3704 tracing::warn!(
3705 "delayed trigger {} claim failed: {error:#}",
3706 candidate.trigger_id
3707 );
3708 continue;
3709 }
3710 };
3711 let Some(trigger) = claimed else {
3712 continue;
3713 };
3714 let trigger = match enqueue(trigger).await {
3715 Ok(trigger) => trigger,
3716 Err(error) => {
3717 tracing::warn!(
3718 "delayed trigger {} enqueue failed: {error:#}",
3719 candidate.trigger_id
3720 );
3721 continue;
3722 }
3723 };
3724 if let Err(error) = with_manager_blocking(automations, {
3725 let trigger = trigger.clone();
3726 move |manager| {
3727 manager.save_trigger(&trigger)?;
3728 if trigger.status == DelayedTriggerStatus::Fired {
3729 manager.emit_trigger_event("trigger.fired", &trigger);
3730 }
3731 Ok(())
3732 }
3733 })
3734 .await
3735 {
3736 tracing::warn!(
3737 "delayed trigger {} receipt could not be persisted: {error:#}",
3738 trigger.trigger_id
3739 );
3740 }
3741 }
3742 Ok(())
3743 }
3744
3745 /// Fold a durable task's state back into its automation run. Returns whether
3746 /// the run changed and needs persisting.
3747 fn apply_task_status(
3748 run: &mut AutomationRunRecord,
3749 task: &crate::task_manager::TaskRecord,
3750 ) -> bool {
3751 let mut changed = run.thread_id != task.thread_id || run.turn_id != task.turn_id;
3752 run.thread_id = task.thread_id.clone();
3753 run.turn_id = task.turn_id.clone();
3754 match task.status {
3755 TaskStatus::Queued => {
3756 if !matches!(run.status, AutomationRunStatus::Queued) {
3757 run.status = AutomationRunStatus::Queued;
3758 changed = true;
3759 }
3760 }
3761 TaskStatus::Running => {
3762 if !matches!(run.status, AutomationRunStatus::Running) {
3763 run.status = AutomationRunStatus::Running;
3764 changed = true;
3765 }
3766 if run.started_at.is_none() {
3767 run.started_at = Some(task.started_at.unwrap_or_else(Utc::now));
3768 changed = true;
3769 }
3770 }
3771 TaskStatus::Completed => {
3772 run.status = AutomationRunStatus::Completed;
3773 run.started_at = run.started_at.or(task.started_at);
3774 run.ended_at = task.ended_at.or(Some(Utc::now()));
3775 run.error = None;
3776 changed = true;
3777 }
3778 TaskStatus::Failed => {
3779 run.status = AutomationRunStatus::Failed;
3780 run.started_at = run.started_at.or(task.started_at);
3781 run.ended_at = task.ended_at.or(Some(Utc::now()));
3782 run.error = task.error.clone();
3783 changed = true;
3784 }
3785 TaskStatus::Canceled => {
3786 run.status = AutomationRunStatus::Canceled;
3787 run.started_at = run.started_at.or(task.started_at);
3788 run.ended_at = task.ended_at.or(Some(Utc::now()));
3789 // #6162: a cancellation is not silent. Keep the task's own error
3790 // when it recorded one, otherwise name the terminal reason so the
3791 // settled receipt can say who or what canceled the run.
3792 run.error = task.error.clone().or_else(|| {
3793 task.terminal_reason
3794 .as_deref()
3795 .map(cancellation_reason_text)
3796 });
3797 changed = true;
3798 }
3799 }
3800 changed
3801 }
3802
3803 /// Human-readable cancellation detail for a run whose task ended without an
3804 /// error of its own. The task manager's terminal reasons are stable strings
3805 /// (`TaskTerminalReason::as_str`); anything unknown is passed through.
3806 fn cancellation_reason_text(terminal_reason: &str) -> String {
3807 // A cooperative cancel is the one path that arrives without an error of
3808 // its own; cancel-timeout and shutdown already carry the task manager's
3809 // receipt message, so those arms are a fallback for records that lost it.
3810 match terminal_reason {
3811 "canceled" => "canceled by request".to_string(),
3812 "cancel_timeout" => "canceled; the task did not stop within the cancel timeout".to_string(),
3813 "shutdown" => "canceled by shutdown".to_string(),
3814 other => format!("canceled ({other})"),
3815 }
3816 }
3817
3818 async fn reconcile_run_statuses_shared(
3819 automations: &SharedAutomationManager,
3820 task_manager: &SharedTaskManager,
3821 ) -> Result<()> {
3822 automations.lock().await.bind_task_manager(task_manager)?;
3823 let mut lock = automations.lock().await.open_lock("dispatch.lock")?;
3824 let _dispatch = match lock.try_write() {
3825 Ok(guard) => guard,
3826 Err(error) if dispatch_lock_busy(&error) => return Ok(()),
3827 Err(error) => return Err(error).context("claim automation reconciliation"),
3828 };
3829 let pending =
3830 with_manager_blocking(automations, AutomationManager::collect_pending_runs).await?;
3831 for mut run in pending {
3832 // Shared storage is not shared ownership. A receipt admitted under
3833 // another execution scope is reconciled by that scope's owner; this
3834 // process must not stamp errors onto it or rewrite it from a bound
3835 // task record it cannot see.
3836 if run
3837 .dispatch
3838 .as_ref()
3839 .and_then(|dispatch| dispatch.execution_scope.as_deref())
3840 != Some(task_manager.execution_scope())
3841 {
3842 continue;
3843 }
3844 let Some(task_id) = run.task_id.clone() else {
3845 continue;
3846 };
3847 // The bound task record is a JSON read under the task store: keep it
3848 // off the Tokio worker like the scans above (#6149).
3849 let lookup = tokio::task::spawn_blocking({
3850 let dispatch = run.dispatch.clone();
3851 let task_id = task_id.clone();
3852 let task_manager = Arc::clone(task_manager);
3853 move || {
3854 if let Some(dispatch) = &dispatch {
3855 check_dispatch_store(dispatch, &task_manager)?;
3856 }
3857 let task = task_manager.read_bound_task(&task_id)?;
3858 if let Some(task) = &task
3859 && let Some(dispatch) = &dispatch
3860 {
3861 crate::task_manager::validate_bound_task_request(task, &dispatch.request)?;
3862 }
3863 Ok::<_, anyhow::Error>(task)
3864 }
3865 })
3866 .await
3867 .context("automation task lookup failed")
3868 .and_then(|lookup| lookup);
3869 let task = match lookup {
3870 Ok(Some(task)) => task,
3871 Ok(None) => {
3872 if run
3873 .dispatch
3874 .as_ref()
3875 .is_some_and(|dispatch| dispatch.accepted)
3876 {
3877 // The admission was durably accepted but the bound task
3878 // record is gone: this occurrence can never be replayed
3879 // or reconciled. Settle it terminally instead of retrying
3880 // the same lookup every pass and starving the schedule
3881 // behind it.
3882 run.status = AutomationRunStatus::Failed;
3883 run.ended_at = Some(run.ended_at.unwrap_or_else(Utc::now));
3884 run.error = Some(format!(
3885 "Bound automation task {task_id} is missing after durable acceptance"
3886 ));
3887 } else {
3888 // Unaccepted admissions are the scheduler's recovery path:
3889 // the next tick reuses the durable binding or recreates
3890 // the task; reconcile only records the uncertainty.
3891 run.error = Some(format!(
3892 "Automation reconciliation unavailable: bound task {task_id} is missing"
3893 ));
3894 }
3895 if let Err(error) = with_manager_blocking(automations, {
3896 let run = run.clone();
3897 move |manager| manager.finish_scheduled_run(&run, Utc::now())
3898 })
3899 .await
3900 {
3901 tracing::warn!(
3902 "automation run {} receipt could not be persisted: {error:#}",
3903 run.id
3904 );
3905 }
3906 continue;
3907 }
3908 Err(error) => {
3909 run.error = Some(format!("Automation reconciliation unavailable: {error:#}"));
3910 if let Err(error) = with_manager_blocking(automations, {
3911 let run = run.clone();
3912 move |manager| manager.finish_scheduled_run(&run, Utc::now())
3913 })
3914 .await
3915 {
3916 tracing::warn!(
3917 "automation run {} receipt could not be persisted: {error:#}",
3918 run.id
3919 );
3920 }
3921 continue;
3922 }
3923 };
3924 // The bound task itself belongs to another Runtime — hands off.
3925 if task.execution_scope.as_deref() != Some(task_manager.execution_scope()) {
3926 continue;
3927 }
3928 let watcher = run
3929 .dispatch
3930 .as_ref()
3931 .map(|dispatch| dispatch.delivery_mode)
3932 .or_else(|| {
3933 automations.try_lock().ok().and_then(|manager| {
3934 manager
3935 .get_automation(&run.automation_id)
3936 .ok()
3937 .map(|automation| automation.delivery_mode())
3938 })
3939 })
3940 == Some(AutomationDeliveryMode::Watcher);
3941 let watcher_noop = watcher
3942 && task.status == TaskStatus::Completed
3943 && task
3944 .result_summary
3945 .as_deref()
3946 .is_some_and(|summary| summary.trim() == AUTOMATION_WATCHER_NO_REPORT_SENTINEL);
3947 if !apply_task_status(&mut run, &task) {
3948 continue;
3949 }
3950 let dispatch = run.dispatch.get_or_insert_with(|| AutomationDispatch {
3951 execution_scope: task.execution_scope.clone(),
3952 request: NewTaskRequest::from_task(&task),
3953 task_data_dir: task_manager.data_dir(),
3954 accepted: true,
3955 delivery_mode: if watcher {
3956 AutomationDeliveryMode::Watcher
3957 } else {
3958 AutomationDeliveryMode::Task
3959 },
3960 suppress_report: false,
3961 schedule: None,
3962 });
3963 run.schema_version = run
3964 .schema_version
3965 .max(required_run_schema_version(Some(&*dispatch)));
3966 dispatch.accepted = true;
3967 dispatch.suppress_report = watcher_noop;
3968 if let Err(error) = with_manager_blocking(automations, {
3969 let run = run.clone();
3970 move |manager| manager.finish_scheduled_run(&run, Utc::now())
3971 })
3972 .await
3973 {
3974 tracing::warn!(
3975 "automation run {} receipt could not be persisted: {error:#}",
3976 run.id
3977 );
3978 }
3979 }
3980 Ok(())
3981 }
3982
3983 /// Fixed-width, lexically-sortable UTC stamp for run file names, e.g.
3984 /// `20260705T142530123Z` (millisecond precision; the run id suffix breaks
3985 /// same-millisecond ties deterministically).
3986 const RUN_STAMP_FORMAT: &str = "%Y%m%dT%H%M%S%3fZ";
3987 const RUN_STAMP_LEN: usize = "20260705T142530123Z".len();
3988
3989 fn run_file_stamp(created_at: DateTime<Utc>) -> String {
3990 created_at.format(RUN_STAMP_FORMAT).to_string()
3991 }
3992
3993 /// Shape check for `{stamp}-{run_id}` file stems. Ordering trusts the file
3994 /// name only for pruning; the parsed record's `created_at` stays
3995 /// authoritative for the final sort.
3996 fn has_sortable_run_stem(stem: &str) -> bool {
3997 let Some((stamp, rest)) = stem.split_at_checked(RUN_STAMP_LEN) else {
3998 return false;
3999 };
4000 if !rest.starts_with('-') || rest.len() < 2 {
4001 return false;
4002 }
4003 stamp.char_indices().all(|(idx, ch)| match idx {
4004 8 => ch == 'T',
4005 18 => ch == 'Z',
4006 _ => ch.is_ascii_digit(),
4007 })
4008 }
4009
4010 fn read_automation_file(path: &Path) -> Result<AutomationRecord> {
4011 let raw = fs::read_to_string(path)
4012 .with_context(|| format!("Failed to read automation {}", path.display()))?;
4013 let record: AutomationRecord = serde_json::from_str(&raw)
4014 .with_context(|| format!("Failed to parse automation {}", path.display()))?;
4015 if record.schema_version > MAX_SUPPORTED_AUTOMATION_SCHEMA_VERSION {
4016 bail!(
4017 "Automation schema v{} is newer than supported v{}",
4018 record.schema_version,
4019 MAX_SUPPORTED_AUTOMATION_SCHEMA_VERSION
4020 );
4021 }
4022 Ok(record)
4023 }
4024
4025 fn read_run_file(path: &Path) -> Result<AutomationRunRecord> {
4026 let raw =
4027 fs::read_to_string(path).with_context(|| format!("Failed to read {}", path.display()))?;
4028 let run: AutomationRunRecord = serde_json::from_str(&raw)
4029 .with_context(|| format!("Failed to parse {}", path.display()))?;
4030 if run.schema_version > MAX_SUPPORTED_RUN_SCHEMA_VERSION {
4031 bail!(
4032 "Automation run schema v{} is newer than supported v{}",
4033 run.schema_version,
4034 MAX_SUPPORTED_RUN_SCHEMA_VERSION
4035 );
4036 }
4037 Ok(run)
4038 }
4039
4040 fn ensure_safe_storage_id(kind: &str, value: &str) -> Result<()> {
4041 let mut components = Path::new(value).components();
4042 let Some(component) = components.next() else {
4043 bail!("{kind} must not be empty");
4044 };
4045 if components.next().is_some() || !matches!(component, std::path::Component::Normal(_)) {
4046 bail!("{kind} must be a single path component");
4047 }
4048 Ok(())
4049 }
4050
4051 fn validate_name_and_prompt(name: &str, prompt: &str) -> Result<()> {
4052 if name.trim().is_empty() {
4053 bail!("Automation name is required");
4054 }
4055 if prompt.trim().is_empty() {
4056 bail!("Automation prompt is required");
4057 }
4058 Ok(())
4059 }
4060
4061 fn normalize_optional_string(value: Option<String>) -> Option<String> {
4062 value
4063 .map(|value| value.trim().to_string())
4064 .filter(|value| !value.is_empty())
4065 }
4066
4067 fn write_json_atomic<T: Serialize>(path: &Path, value: &T) -> Result<()> {
4068 if let Some(parent) = path.parent() {
4069 fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
4070 }
4071 codewhale_util::utils::write_atomic(path, &serde_json::to_vec_pretty(value)?)
4072 .with_context(|| format!("write {}", path.display()))
4073 }
4074
4075 pub fn default_automations_dir() -> PathBuf {
4076 // Most-specific override: an explicit automations dir.
4077 for var in ["CODEWHALE_AUTOMATIONS_DIR", "DEEPSEEK_AUTOMATIONS_DIR"] {
4078 if let Ok(path) = std::env::var(var) {
4079 let trimmed = path.trim();
4080 if !trimmed.is_empty() {
4081 return PathBuf::from(trimmed);
4082 }
4083 }
4084 }
4085 // $CODEWHALE_HOME is a hard override of the base data directory
4086 // (docs/CONFIGURATION.md): when SET, automations live under it and we do
4087 // NOT fall back to the legacy ~/.deepseek path — silent fallback would
4088 // defeat the isolation the override promises. Check the env var directly
4089 // (not codewhale_home()'s Ok/Err, which succeeds for the default home too).
4090 if let Some(home) = codewhale_paths::codewhale_home_override().ok().flatten() {
4091 return home.join("automations");
4092 }
4093 codewhale_paths::user_home()
4094 .map(|home| {
4095 let primary = home.join(".codewhale").join("automations");
4096 let legacy = home.join(".deepseek").join("automations");
4097 if primary.exists() || !legacy.exists() {
4098 return primary;
4099 }
4100 legacy
4101 })
4102 .unwrap_or_else(|| PathBuf::from(".codewhale").join("automations"))
4103 }
4104
4105 pub type SharedAutomationManager = Arc<Mutex<AutomationManager>>;
4106
4107 #[derive(Debug, Clone)]
4108 pub struct AutomationSchedulerConfig {
4109 pub tick_interval_secs: u64,
4110 }
4111
4112 impl Default for AutomationSchedulerConfig {
4113 fn default() -> Self {
4114 Self {
4115 tick_interval_secs: 15,
4116 }
4117 }
4118 }
4119
4120 pub fn spawn_scheduler(
4121 automations: SharedAutomationManager,
4122 task_manager: SharedTaskManager,
4123 cancel: CancellationToken,
4124 config: AutomationSchedulerConfig,
4125 ) -> tokio::task::JoinHandle<()> {
4126 spawn_supervised(
4127 "automation-scheduler",
4128 std::panic::Location::caller(),
4129 async move {
4130 let interval = config.tick_interval_secs.max(5);
4131 let max_wait = std::time::Duration::from_secs(interval);
4132 let wakeup =
4133 with_manager_blocking(&automations, |manager| Ok(manager.trigger_wakeup()))
4134 .await
4135 .unwrap_or_else(|_| Arc::new(Notify::new()));
4136 let grace = Duration::seconds(
4137 SCHEDULER_PRESENCE_MIN_GRACE_SECS.max(
4138 i64::try_from(interval)
4139 .unwrap_or(i64::MAX / 8)
4140 .saturating_mul(4),
4141 ),
4142 );
4143 loop {
4144 if cancel.is_cancelled() {
4145 break;
4146 }
4147
4148 // Lock scope lives inside the shared helpers: the manager
4149 // mutex is dropped across every task-manager await so API and
4150 // tool callers are never queued behind enqueue/status latency.
4151 let presence = with_manager_blocking(&automations, move |manager| {
4152 manager.note_scheduler_presence(Utc::now(), grace)
4153 })
4154 .await;
4155 if let Err(err) = presence {
4156 tracing::warn!(
4157 "automation scheduler presence could not be recorded; holding due work: {err:#}"
4158 );
4159 } else if let Err(err) = scheduler_tick_shared(&automations, &task_manager).await {
4160 tracing::warn!("automation scheduler tick failed: {err}");
4161 }
4162 if let Err(err) = reconcile_run_statuses_shared(&automations, &task_manager).await {
4163 tracing::warn!("automation reconcile failed: {err}");
4164 }
4165 if let Err(err) = fire_due_triggers_shared(&automations, &task_manager).await {
4166 tracing::warn!("delayed trigger tick failed: {err}");
4167 }
4168
4169 let wait_duration = with_manager_blocking(&automations, move |manager| {
4170 manager.trigger_wait_duration(Utc::now(), max_wait)
4171 })
4172 .await
4173 .unwrap_or(max_wait);
4174
4175 tokio::select! {
4176 _ = cancel.cancelled() => break,
4177 _ = sleep(wait_duration) => {}
4178 _ = wakeup.notified() => {}
4179 }
4180 }
4181 },
4182 )
4183 }
4184
4185 #[cfg(test)]
4186 mod tests {
4187 use super::*;
4188 use async_trait::async_trait;
4189 use chrono::{FixedOffset, LocalResult, NaiveDate};
4190 use tokio::sync::mpsc;
4191
4192 use crate::task_manager::{
4193 ExecutionTask, TaskExecutionEvent, TaskExecutionResult, TaskExecutor, TaskManager,
4194 TaskManagerConfig,
4195 };
4196
4197 struct AutomationRecordingExecutor(PathBuf);
4198
4199 #[async_trait]
4200 impl TaskExecutor for AutomationRecordingExecutor {
4201 async fn execute(
4202 &self,
4203 task: ExecutionTask,
4204 _events: mpsc::Sender<TaskExecutionEvent>,
4205 _cancel: CancellationToken,
4206 ) -> TaskExecutionResult {
4207 use std::io::Write as _;
4208 let recorded = (|| -> Result<()> {
4209 let id = task
4210 .thread_request()
4211 .task_id
4212 .context("fixture task identity")?;
4213 let mut file = fs::OpenOptions::new()
4214 .create(true)
4215 .append(true)
4216 .open(&self.0)?;
4217 writeln!(file, "{id}")?;
4218 file.sync_all()?;
4219 Ok(())
4220 })();
4221 match recorded {
4222 Ok(()) => TaskExecutionResult {
4223 status: TaskStatus::Completed,
4224 result_text: Some("automation fixture completed".into()),
4225 error: None,
4226 terminal_reason: crate::task_manager::TaskTerminalReason::Completed,
4227 },
4228 Err(error) => TaskExecutionResult {
4229 status: TaskStatus::Failed,
4230 result_text: None,
4231 error: Some(error.to_string()),
4232 terminal_reason: crate::task_manager::TaskTerminalReason::Failed,
4233 },
4234 }
4235 }
4236 }
4237
4238 fn fixture_executions(path: &Path) -> Vec<String> {
4239 match fs::read_to_string(path) {
4240 Ok(text) => text.lines().map(str::to_owned).collect(),
4241 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Vec::new(),
4242 Err(error) => panic!("read independent execution receipts: {error}"),
4243 }
4244 }
4245
4246 async fn fixture_tasks(root: &Path, receipts: &Path) -> Result<SharedTaskManager> {
4247 TaskManager::start_with_executor(
4248 automation_task_config(root.to_path_buf()),
4249 Arc::new(AutomationRecordingExecutor(receipts.to_path_buf())),
4250 )
4251 .await
4252 }
4253
4254 fn fixture_due_automation(
4255 manager: &AutomationManager,
4256 id: &str,
4257 order: i64,
4258 ) -> AutomationRecord {
4259 let mut automation = automation_record_with_settings(None, None, None, None);
4260 automation.id = id.to_owned();
4261 automation.prompt = format!("automation fixture {id}");
4262 automation.created_at = Utc::now() - Duration::hours(2);
4263 automation.updated_at = Utc::now() - Duration::minutes(order);
4264 automation.next_run_at = Some(Utc::now() - Duration::minutes(1));
4265 manager
4266 .save_automation(&automation)
4267 .expect("save due fixture");
4268 automation
4269 }
4270
4271 #[tokio::test]
4272 async fn interrupted_dispatch_reuses_binding_and_preserves_replacement_schedule() -> Result<()>
4273 {
4274 for accepted_before_cut in [false, true] {
4275 let root = tempfile::tempdir()?;
4276 let receipts = root.path().join("executions");
4277 let tasks = fixture_tasks(&root.path().join("tasks"), &receipts).await?;
4278 let manager = AutomationManager::open_for_test(root.path().join("automations"))?;
4279 let automation = fixture_due_automation(&manager, "recover", 1);
4280 let shared = Arc::new(Mutex::new(manager));
4281 let (at_cut, reached_cut) = tokio::sync::oneshot::channel();
4282 let tick = tokio::spawn({
4283 let shared = shared.clone();
4284 let tasks = tasks.clone();
4285 let mut at_cut = Some(at_cut);
4286 async move {
4287 scheduler_tick_with(&shared, &tasks.data_dir(), move |mut run| {
4288 let tasks = tasks.clone();
4289 let at_cut = at_cut.take();
4290 async move {
4291 if accepted_before_cut {
4292 enqueue_run_task(&mut run, &tasks).await;
4293 }
4294 if let Some(at_cut) = at_cut {
4295 let _ = at_cut.send(run.clone());
4296 }
4297 std::future::pending::<()>().await;
4298 run
4299 }
4300 })
4301 .await
4302 }
4303 });
4304 let observed =
4305 tokio::time::timeout(std::time::Duration::from_secs(5), reached_cut).await??;
4306 let bound_id = observed.task_id.clone().context("claimed task id")?;
4307 let persisted = shared.lock().await.list_runs(&automation.id, None)?;
4308 assert_eq!(
4309 persisted.len(),
4310 1,
4311 "intent exists before either interruption boundary"
4312 );
4313 assert_eq!(persisted[0].task_id.as_deref(), Some(bound_id.as_str()));
4314 assert!(
4315 !persisted[0].dispatch.as_ref().unwrap().accepted,
4316 "final acceptance save has not run"
4317 );
4318 if accepted_before_cut {
4319 let task = crate::task_manager::wait_for_terminal_state(
4320 &tasks,
4321 &bound_id,
4322 std::time::Duration::from_secs(5),
4323 )
4324 .await?;
4325 assert_eq!(task.status, TaskStatus::Completed);
4326 assert!(
4327 task.result_summary
4328 .as_deref()
4329 .unwrap_or_default()
4330 .contains("automation fixture completed")
4331 );
4332 assert_eq!(fixture_executions(&receipts), vec![bound_id.clone()]);
4333 } else {
4334 assert!(tasks.read_bound_task(&bound_id)?.is_none());
4335 assert!(fixture_executions(&receipts).is_empty());
4336 }
4337 // Simulate a dropped request/process before the final run receipt.
4338 tick.abort();
4339 assert!(tick.await.unwrap_err().is_cancelled());
4340 let reopened = AutomationManager::open_for_test(root.path().join("automations"))?;
4341 let future = Utc::now() + Duration::hours(4);
4342 let edited = reopened.update_automation(
4343 &automation.id,
4344 UpdateAutomationRequest {
4345 rrule: Some(format!("FREQ=ONCE;AT={}", future.to_rfc3339())),
4346 prompt: Some("future revised prompt".into()),
4347 ..Default::default()
4348 },
4349 )?;
4350 let restarted = Arc::new(Mutex::new(reopened));
4351 scheduler_tick_shared(&restarted, &tasks).await?;
4352 let task = crate::task_manager::wait_for_terminal_state(
4353 &tasks,
4354 &bound_id,
4355 std::time::Duration::from_secs(5),
4356 )
4357 .await?;
4358 assert_eq!(task.status, TaskStatus::Completed);
4359 assert_eq!(
4360 task.prompt, automation.prompt,
4361 "claim keeps its original request"
4362 );
4363 reconcile_run_statuses_shared(&restarted, &tasks).await?;
4364 scheduler_tick_shared(&restarted, &tasks).await?;
4365 assert_eq!(
4366 fixture_executions(&receipts),
4367 vec![bound_id.clone()],
4368 "same occurrence executes exactly once"
4369 );
4370 let manager = restarted.lock().await;
4371 let runs = manager.list_runs(&automation.id, None)?;
4372 assert_eq!(runs.len(), 1);
4373 assert_eq!(runs[0].task_id.as_deref(), Some(bound_id.as_str()));
4374 assert_eq!(runs[0].status, AutomationRunStatus::Completed);
4375 assert!(runs[0].dispatch.as_ref().unwrap().accepted);
4376 let current = manager.get_automation(&automation.id)?;
4377 assert_eq!(current.rrule, edited.rrule);
4378 assert_eq!(
4379 current.next_run_at, edited.next_run_at,
4380 "old completion must not clear future ONCE"
4381 );
4382 assert_eq!(current.status, AutomationStatus::Active);
4383 assert_eq!(current.updated_at, edited.updated_at);
4384 assert_eq!(current.prompt, edited.prompt);
4385 assert!(current.last_run_at.is_some());
4386 tasks.shutdown();
4387 }
4388 Ok(())
4389 }
4390
4391 #[tokio::test]
4392 async fn pause_and_delete_before_claim_stop_collected_work_but_preserve_admitted_work()
4393 -> Result<()> {
4394 let root = tempfile::tempdir()?;
4395 let receipts = root.path().join("executions");
4396 let tasks = fixture_tasks(&root.path().join("tasks"), &receipts).await?;
4397 let manager = AutomationManager::open_for_test(root.path().join("automations"))?;
4398 let first = fixture_due_automation(&manager, "first", 1);
4399 let paused = fixture_due_automation(&manager, "paused", 2);
4400 let deleted = fixture_due_automation(&manager, "deleted", 3);
4401 let shared = Arc::new(Mutex::new(manager));
4402 let (entered, reached) = tokio::sync::oneshot::channel();
4403 let (release, released) = tokio::sync::oneshot::channel();
4404 let tick = tokio::spawn({
4405 let shared = shared.clone();
4406 let tasks = tasks.clone();
4407 let mut barrier = Some((entered, released));
4408 async move {
4409 scheduler_tick_with(&shared, &tasks.data_dir(), move |mut run| {
4410 let barrier = barrier.take();
4411 let tasks = tasks.clone();
4412 async move {
4413 if let Some((entered, released)) = barrier {
4414 let _ = entered.send(run.clone());
4415 let _ = released.await;
4416 }
4417 enqueue_run_task(&mut run, &tasks).await;
4418 run
4419 }
4420 })
4421 .await
4422 }
4423 });
4424 let admitted = tokio::time::timeout(std::time::Duration::from_secs(5), reached).await??;
4425 assert_eq!(
4426 admitted.automation_id, first.id,
4427 "ordered first claim really entered"
4428 );
4429 let other = AutomationManager::open_for_test(root.path().join("automations"))?;
4430 other.pause_automation(&paused.id)?;
4431 other.delete_automation(&deleted.id)?;
4432 // Pause after durable admission affects future runs; this run remains owned.
4433 other.pause_automation(&first.id)?;
4434 release
4435 .send(())
4436 .map_err(|_| anyhow::anyhow!("release fixture"))?;
4437 tokio::time::timeout(std::time::Duration::from_secs(5), tick).await???;
4438 let id = admitted.task_id.context("admitted task identity")?;
4439 let task = crate::task_manager::wait_for_terminal_state(
4440 &tasks,
4441 &id,
4442 std::time::Duration::from_secs(5),
4443 )
4444 .await?;
4445 assert_eq!(task.status, TaskStatus::Completed);
4446 reconcile_run_statuses_shared(&shared, &tasks).await?;
4447 assert_eq!(fixture_executions(&receipts), vec![id]);
4448 assert!(other.list_runs(&paused.id, None)?.is_empty());
4449 assert!(other.list_runs(&deleted.id, None)?.is_empty());
4450 assert_eq!(
4451 other.get_automation(&first.id)?.status,
4452 AutomationStatus::Paused
4453 );
4454 assert!(other.get_automation(&first.id)?.next_run_at.is_none());
4455 tasks.shutdown();
4456 Ok(())
4457 }
4458
4459 #[tokio::test]
4460 async fn reconciliation_reaches_old_runs_and_delete_waits_for_settled_receipts() -> Result<()> {
4461 for delete_definition in [false, true] {
4462 let root = tempfile::tempdir()?;
4463 let receipts = root.path().join("executions");
4464 let tasks = fixture_tasks(&root.path().join("tasks"), &receipts).await?;
4465 let manager = AutomationManager::open_for_test(root.path().join("automations"))?;
4466 let automation = fixture_due_automation(&manager, "history", 1);
4467 let shared = Arc::new(Mutex::new(manager));
4468 let run = run_now_shared(&shared, &automation.id, &tasks).await?;
4469 let id = run.task_id.clone().context("real task id")?;
4470 let task = crate::task_manager::wait_for_terminal_state(
4471 &tasks,
4472 &id,
4473 std::time::Duration::from_secs(5),
4474 )
4475 .await?;
4476 assert_eq!(task.status, TaskStatus::Completed);
4477 {
4478 let manager = shared.lock().await;
4479 for offset in 1..=110 {
4480 let mut newer = new_run_record(
4481 &automation.id,
4482 Utc::now(),
4483 run.created_at + Duration::seconds(offset),
4484 );
4485 newer.status = AutomationRunStatus::Completed;
4486 newer.ended_at = Some(newer.created_at);
4487 manager.save_run(&newer)?;
4488 }
4489 assert!(
4490 manager
4491 .list_runs(&automation.id, Some(100))?
4492 .iter()
4493 .all(|candidate| candidate.id != run.id)
4494 );
4495 if delete_definition {
4496 // The receipt is still queued on disk even though its task
4497 // already settled, so deletion is refused: an in-flight
4498 // occurrence must not be stranded by a deleted definition.
4499 let refused = manager.delete_automation(&automation.id);
4500 assert!(refused.is_err(), "unsettled receipts must block deletion");
4501 }
4502 }
4503 reconcile_run_statuses_shared(&shared, &tasks).await?;
4504 let manager = shared.lock().await;
4505 let found =
4506 manager.get_runs_by_ids(&automation.id, &[run.id.clone()].into_iter().collect())?;
4507 assert_eq!(
4508 found.len(),
4509 1,
4510 "run binding survives until its receipt settles"
4511 );
4512 assert_eq!(found[0].status, AutomationRunStatus::Completed);
4513 assert_eq!(found[0].task_id.as_deref(), Some(id.as_str()));
4514 assert_eq!(fixture_executions(&receipts), vec![id]);
4515 if delete_definition {
4516 // The earlier delete was refused, so the definition survived
4517 // and reconciliation settled its receipt in place. Deleting
4518 // now archives the settled history and removes the live tree.
4519 assert!(manager.get_automation(&automation.id).is_ok());
4520 manager.delete_automation(&automation.id)?;
4521 assert!(manager.get_automation(&automation.id).is_err());
4522 let ids = std::collections::BTreeSet::from([run.id.clone()]);
4523 assert!(manager.get_runs_by_ids(&automation.id, &ids)?.is_empty());
4524 let archived = manager.list_archived_runs(&automation.id)?;
4525 assert_eq!(archived.len(), ARCHIVE_RETAINED_TERMINAL_RUNS);
4526 assert!(archived.iter().all(|candidate| candidate.id != run.id));
4527 } else {
4528 assert!(
4529 manager
4530 .get_automation(&automation.id)?
4531 .last_run_at
4532 .is_some()
4533 );
4534 }
4535 tasks.shutdown();
4536 }
4537 Ok(())
4538 }
4539
4540 #[tokio::test]
4541 async fn foreign_store_and_missing_accepted_task_preserve_binding_without_fallback()
4542 -> Result<()> {
4543 let root = tempfile::tempdir()?;
4544 let receipts = root.path().join("executions");
4545 let tasks = fixture_tasks(&root.path().join("tasks"), &receipts).await?;
4546 let other_receipts = root.path().join("foreign-executions");
4547 let other_tasks =
4548 fixture_tasks(&root.path().join("foreign-tasks"), &other_receipts).await?;
4549 let manager = AutomationManager::open_for_test(root.path().join("automations"))?;
4550 let automation = fixture_due_automation(&manager, "bound-store", 1);
4551 let proposed = manager.collect_due_runs(Utc::now())?.remove(0);
4552 let mut run = manager
4553 .claim_scheduled_run(&proposed.0, proposed.1, &tasks.data_dir())?
4554 .context("claim")?;
4555 let id = run.task_id.clone().context("bound task")?;
4556 let shared = Arc::new(Mutex::new(manager));
4557 scheduler_tick_shared(&shared, &other_tasks).await?;
4558 let rows = shared.lock().await.list_runs(&automation.id, None)?;
4559 assert_eq!(rows[0].task_id.as_deref(), Some(id.as_str()));
4560 assert!(
4561 rows[0]
4562 .error
4563 .as_deref()
4564 .unwrap_or_default()
4565 .contains("different task store")
4566 );
4567 assert!(fixture_executions(&other_receipts).is_empty());
4568 enqueue_run_task(&mut run, &tasks).await;
4569 let task = crate::task_manager::wait_for_terminal_state(
4570 &tasks,
4571 &id,
4572 std::time::Duration::from_secs(5),
4573 )
4574 .await?;
4575 assert_eq!(task.status, TaskStatus::Completed);
4576 assert!(run.dispatch.as_ref().unwrap().accepted);
4577 shared.lock().await.finish_scheduled_run(&run, Utc::now())?;
4578 fs::remove_file(tasks.data_dir().join("tasks").join(format!("{id}.json")))?;
4579 scheduler_tick_shared(&shared, &tasks).await?;
4580 reconcile_run_statuses_shared(&shared, &tasks).await?;
4581 let rows = shared.lock().await.list_runs(&automation.id, None)?;
4582 assert_eq!(rows[0].task_id.as_deref(), Some(id.as_str()));
4583 assert!(rows[0].dispatch.as_ref().unwrap().accepted);
4584 assert!(
4585 rows[0]
4586 .error
4587 .as_deref()
4588 .unwrap_or_default()
4589 .contains("missing")
4590 );
4591 assert_eq!(fixture_executions(&receipts), vec![id]);
4592 assert!(fixture_executions(&other_receipts).is_empty());
4593 tasks.shutdown();
4594 other_tasks.shutdown();
4595 Ok(())
4596 }
4597
4598 #[tokio::test]
4599 async fn canceled_collected_trigger_is_not_admitted_after_an_earlier_enqueue_wait() -> Result<()>
4600 {
4601 let root = tempfile::tempdir()?;
4602 let receipts = root.path().join("executions");
4603 let tasks = fixture_tasks(&root.path().join("tasks"), &receipts).await?;
4604 let manager = AutomationManager::open_for_test(root.path().join("automations"))?;
4605 let mut triggers = Vec::new();
4606 for index in 0..2 {
4607 let mut trigger = manager.create_trigger(CreateDelayedTriggerRequest {
4608 destination_thread_id: None,
4609 fire_at: Utc::now() + Duration::hours(1),
4610 message: format!("trigger fixture {index}"),
4611 workspace: None,
4612 owner_session_id: Some("fixture-owner".into()),
4613 parent_trigger_id: None,
4614 disallowed_tools: Vec::new(),
4615 })?;
4616 trigger.fire_at = Utc::now() - Duration::minutes(1);
4617 trigger.created_at = Utc::now() - Duration::minutes(index);
4618 manager.save_trigger(&trigger)?;
4619 triggers.push(trigger);
4620 }
4621 let shared = Arc::new(Mutex::new(manager));
4622 let (entered, reached) = tokio::sync::oneshot::channel();
4623 let (release, released) = tokio::sync::oneshot::channel();
4624 let tick = tokio::spawn({
4625 let shared = shared.clone();
4626 let tasks = tasks.clone();
4627 let mut barrier = Some((entered, released));
4628 async move {
4629 fire_due_triggers_with(&shared, &tasks.data_dir(), move |trigger| {
4630 let tasks = tasks.clone();
4631 let barrier = barrier.take();
4632 async move {
4633 if let Some((entered, released)) = barrier {
4634 let _ = entered.send(trigger.clone());
4635 let _ = released.await;
4636 }
4637 enqueue_trigger_task(trigger, &tasks).await
4638 }
4639 })
4640 .await
4641 }
4642 });
4643 let admitted = tokio::time::timeout(std::time::Duration::from_secs(5), reached).await??;
4644 assert_eq!(admitted.trigger_id, triggers[0].trigger_id);
4645 assert_eq!(admitted.status, DelayedTriggerStatus::Dispatching);
4646 let other = AutomationManager::open_for_test(root.path().join("automations"))?;
4647 other.cancel_trigger_for_owner(&triggers[1].trigger_id, "fixture-owner")?;
4648 assert!(
4649 other
4650 .cancel_trigger_for_owner(&admitted.trigger_id, "fixture-owner")
4651 .is_err(),
4652 "claimed work has crossed the admission boundary"
4653 );
4654 release
4655 .send(())
4656 .map_err(|_| anyhow::anyhow!("release trigger fixture"))?;
4657 tokio::time::timeout(std::time::Duration::from_secs(5), tick).await???;
4658 let id = admitted.task_id.context("trigger task identity")?;
4659 let task = crate::task_manager::wait_for_terminal_state(
4660 &tasks,
4661 &id,
4662 std::time::Duration::from_secs(5),
4663 )
4664 .await?;
4665 assert_eq!(task.status, TaskStatus::Completed);
4666 assert_eq!(task.owner_session_id.as_deref(), Some("fixture-owner"));
4667 assert!(!task.allow_shell && !task.trust_mode && !task.auto_approve);
4668 assert_eq!(fixture_executions(&receipts), vec![id]);
4669 assert_eq!(
4670 other.get_trigger(&triggers[0].trigger_id)?.status,
4671 DelayedTriggerStatus::Fired
4672 );
4673 let canceled = other.get_trigger(&triggers[1].trigger_id)?;
4674 assert_eq!(canceled.status, DelayedTriggerStatus::Canceled);
4675 assert!(canceled.task_id.is_none());
4676 tasks.shutdown();
4677 Ok(())
4678 }
4679
4680 async fn wait_fixture_path(path: &Path) -> Result<()> {
4681 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
4682 while !path.try_exists()? {
4683 if std::time::Instant::now() >= deadline {
4684 bail!("fixture barrier timed out: {}", path.display());
4685 }
4686 tokio::time::sleep(std::time::Duration::from_millis(10)).await;
4687 }
4688 Ok(())
4689 }
4690
4691 struct SchedulerFixtureChild(std::process::Child);
4692
4693 impl Drop for SchedulerFixtureChild {
4694 fn drop(&mut self) {
4695 let _ = self.0.kill();
4696 let _ = self.0.wait();
4697 }
4698 }
4699
4700 fn spawn_scheduler_fixture(root: &Path, role: &str) -> Result<SchedulerFixtureChild> {
4701 let log = fs::File::create(root.join(format!("{role}.log")))?;
4702 let home = root.join(format!("{role}-home"));
4703 fs::create_dir_all(&home)?;
4704 Ok(SchedulerFixtureChild(
4705 std::process::Command::new(std::env::current_exe()?)
4706 .args([
4707 "--ignored",
4708 "--exact",
4709 "automation_manager::tests::scheduler_process_fixture",
4710 "--nocapture",
4711 "--test-threads=1",
4712 ])
4713 .env("CW_AUTOMATION_PROCESS_FIXTURE", root)
4714 .env("CW_AUTOMATION_PROCESS_ROLE", role)
4715 .env("CODEWHALE_HOME", &home)
4716 .env("HOME", &home)
4717 .env("USERPROFILE", &home)
4718 .stdin(std::process::Stdio::null())
4719 .stdout(std::process::Stdio::from(log.try_clone()?))
4720 .stderr(std::process::Stdio::from(log))
4721 .spawn()?,
4722 ))
4723 }
4724
4725 async fn finish_scheduler_fixture(child: &mut SchedulerFixtureChild, log: &Path) -> Result<()> {
4726 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
4727 loop {
4728 if let Some(status) = child.0.try_wait()? {
4729 if !status.success() {
4730 bail!("fixture process failed: {}", fs::read_to_string(log)?);
4731 }
4732 return Ok(());
4733 }
4734 if std::time::Instant::now() >= deadline {
4735 bail!("fixture process timed out: {}", log.display());
4736 }
4737 tokio::time::sleep(std::time::Duration::from_millis(10)).await;
4738 }
4739 }
4740
4741 /// Only the parent test launches this entry point with explicit temporary
4742 /// stores. Missing fixture parameters fail; this helper cannot pass by skip.
4743 #[tokio::test]
4744 #[ignore = "subprocess entry point for independent scheduler contention fixture"]
4745 async fn scheduler_process_fixture() -> Result<()> {
4746 let root = PathBuf::from(
4747 std::env::var_os("CW_AUTOMATION_PROCESS_FIXTURE").context("required fixture root")?,
4748 );
4749 let role = std::env::var("CW_AUTOMATION_PROCESS_ROLE")?;
4750 if !matches!(role.as_str(), "first" | "second") {
4751 bail!("invalid fixture role");
4752 }
4753 let scope = if role == "first" {
4754 "test"
4755 } else {
4756 "foreign-scheduler"
4757 };
4758 let tasks = TaskManager::start_with_executor_in_scope(
4759 automation_task_config(root.join("tasks")),
4760 Arc::new(AutomationRecordingExecutor(root.join("executions"))),
4761 scope,
4762 )
4763 .await?;
4764 let mut service = AutomationManager::open(root.join("automations"))?;
4765 service.bind_task_manager(&tasks)?;
4766 let shared = Arc::new(Mutex::new(service));
4767 codewhale_util::utils::write_atomic(&root.join(format!("{role}-ready")), b"ready")?;
4768 wait_fixture_path(&root.join(format!("{role}-go"))).await?;
4769 let observations = Arc::new(std::sync::Mutex::new(Vec::new()));
4770 scheduler_tick_with(&shared, &tasks.data_dir(), {
4771 let tasks = tasks.clone();
4772 let root = root.clone();
4773 let role = role.clone();
4774 let observations = observations.clone();
4775 move |mut run| {
4776 let tasks = tasks.clone();
4777 let root = root.clone();
4778 let role = role.clone();
4779 let observations = observations.clone();
4780 async move {
4781 let id = run.task_id.clone().expect("durably claimed fixture id");
4782 observations.lock().unwrap().push(id.clone());
4783 codewhale_util::utils::write_atomic(
4784 &root.join(format!("{role}-entered")),
4785 id.as_bytes(),
4786 )
4787 .expect("record dispatch entry");
4788 if role == "first" {
4789 codewhale_util::utils::write_atomic(
4790 &root.join("first-held"),
4791 id.as_bytes(),
4792 )
4793 .expect("record claim barrier");
4794 wait_fixture_path(&root.join("release-first"))
4795 .await
4796 .expect("release owner");
4797 }
4798 enqueue_run_task(&mut run, &tasks).await;
4799 run
4800 }
4801 }
4802 })
4803 .await?;
4804 let ids = observations.lock().unwrap().clone();
4805 for id in &ids {
4806 let task = crate::task_manager::wait_for_terminal_state(
4807 &tasks,
4808 id,
4809 std::time::Duration::from_secs(5),
4810 )
4811 .await?;
4812 assert_eq!(task.status, TaskStatus::Completed);
4813 }
4814 reconcile_run_statuses_shared(&shared, &tasks).await?;
4815 codewhale_util::utils::write_atomic(
4816 &root.join(format!("{role}-done")),
4817 serde_json::to_vec(&ids)?.as_slice(),
4818 )?;
4819 tasks.shutdown();
4820 Ok(())
4821 }
4822
4823 #[tokio::test]
4824 async fn two_scheduler_processes_preserve_the_bound_scope_and_execute_one_task() -> Result<()> {
4825 let root = tempfile::tempdir()?;
4826 let manager = AutomationManager::open_for_test(root.path().join("automations"))?;
4827 let automation = fixture_due_automation(&manager, "cross-process", 1);
4828 let mut first = spawn_scheduler_fixture(root.path(), "first")?;
4829 let mut second = spawn_scheduler_fixture(root.path(), "second")?;
4830 // Separate Runtime scopes share storage. The foreign scheduler cannot
4831 // adopt the first scope's immutable dispatch even before acceptance.
4832 wait_fixture_path(&root.path().join("first-ready")).await?;
4833 wait_fixture_path(&root.path().join("second-ready")).await?;
4834 codewhale_util::utils::write_atomic(&root.path().join("first-go"), b"go")?;
4835 wait_fixture_path(&root.path().join("first-held")).await?;
4836 let id = fs::read_to_string(root.path().join("first-held"))?;
4837 codewhale_util::utils::write_atomic(&root.path().join("second-go"), b"go")?;
4838 wait_fixture_path(&root.path().join("second-done")).await?;
4839 finish_scheduler_fixture(&mut second, &root.path().join("second.log")).await?;
4840 assert!(
4841 !root.path().join("second-entered").exists(),
4842 "a live dispatcher still owns the unaccepted intent"
4843 );
4844 assert!(
4845 fixture_executions(&root.path().join("executions")).is_empty(),
4846 "owner is blocked before actual enqueue"
4847 );
4848 codewhale_util::utils::write_atomic(&root.path().join("release-first"), b"release")?;
4849 finish_scheduler_fixture(&mut first, &root.path().join("first.log")).await?;
4850 assert_eq!(
4851 fixture_executions(&root.path().join("executions")),
4852 vec![id.clone()]
4853 );
4854 let entered: Vec<String> =
4855 serde_json::from_slice(&fs::read(root.path().join("first-done"))?)?;
4856 assert_eq!(
4857 entered,
4858 vec![id.clone()],
4859 "first process traversed the real enqueue path"
4860 );
4861 let runs = manager.list_runs(&automation.id, None)?;
4862 assert_eq!(runs.len(), 1);
4863 assert_eq!(runs[0].task_id.as_deref(), Some(id.as_str()));
4864 assert_eq!(runs[0].status, AutomationRunStatus::Completed);
4865 assert!(runs[0].dispatch.as_ref().unwrap().accepted);
4866 let task: crate::task_manager::TaskRecord = serde_json::from_slice(&fs::read(
4867 root.path().join("tasks/tasks").join(format!("{id}.json")),
4868 )?)?;
4869 assert_eq!(task.id, id);
4870 assert_eq!(task.status, TaskStatus::Completed);
4871 assert!(
4872 task.result_summary
4873 .as_deref()
4874 .unwrap_or_default()
4875 .contains("automation fixture completed")
4876 );
4877 Ok(())
4878 }
4879
4880 struct AutomationNoopExecutor;
4881 struct AutomationWatcherNoopExecutor;
4882
4883 /// A deterministic America/New_York-compatible zone for the 2026 DST
4884 /// boundary tests. Keeping the transition table local avoids mutating the
4885 /// process-wide `TZ` setting while the test binary runs in parallel.
4886 #[derive(Debug, Clone, Copy)]
4887 struct Eastern2026;
4888
4889 impl Eastern2026 {
4890 fn standard_offset() -> FixedOffset {
4891 FixedOffset::west_opt(5 * 60 * 60).expect("valid standard offset")
4892 }
4893
4894 fn daylight_offset() -> FixedOffset {
4895 FixedOffset::west_opt(4 * 60 * 60).expect("valid daylight offset")
4896 }
4897
4898 fn time(month: u32, day: u32, hour: u32) -> NaiveDateTime {
4899 NaiveDate::from_ymd_opt(2026, month, day)
4900 .expect("valid transition date")
4901 .and_hms_opt(hour, 0, 0)
4902 .expect("valid transition time")
4903 }
4904 }
4905
4906 impl TimeZone for Eastern2026 {
4907 type Offset = FixedOffset;
4908
4909 fn from_offset(_offset: &Self::Offset) -> Self {
4910 Self
4911 }
4912
4913 fn offset_from_local_date(&self, local: &NaiveDate) -> LocalResult<Self::Offset> {
4914 self.offset_from_local_datetime(
4915 &local
4916 .and_hms_opt(12, 0, 0)
4917 .expect("valid local date midpoint"),
4918 )
4919 }
4920
4921 fn offset_from_local_datetime(&self, local: &NaiveDateTime) -> LocalResult<Self::Offset> {
4922 let gap_start = Self::time(3, 8, 2);
4923 let gap_end = Self::time(3, 8, 3);
4924 let fold_start = Self::time(11, 1, 1);
4925 let fold_end = Self::time(11, 1, 2);
4926
4927 if *local >= gap_start && *local < gap_end {
4928 LocalResult::None
4929 } else if *local >= fold_start && *local < fold_end {
4930 LocalResult::Ambiguous(Self::daylight_offset(), Self::standard_offset())
4931 } else if *local >= gap_end && *local < fold_start {
4932 LocalResult::Single(Self::daylight_offset())
4933 } else {
4934 LocalResult::Single(Self::standard_offset())
4935 }
4936 }
4937
4938 fn offset_from_utc_date(&self, utc: &NaiveDate) -> Self::Offset {
4939 self.offset_from_utc_datetime(
4940 &utc.and_hms_opt(12, 0, 0).expect("valid UTC date midpoint"),
4941 )
4942 }
4943
4944 fn offset_from_utc_datetime(&self, utc: &NaiveDateTime) -> Self::Offset {
4945 let daylight_start = Self::time(3, 8, 7);
4946 let daylight_end = Self::time(11, 1, 6);
4947 if *utc >= daylight_start && *utc < daylight_end {
4948 Self::daylight_offset()
4949 } else {
4950 Self::standard_offset()
4951 }
4952 }
4953 }
4954
4955 #[async_trait]
4956 impl TaskExecutor for AutomationNoopExecutor {
4957 async fn execute(
4958 &self,
4959 _task: ExecutionTask,
4960 _events: mpsc::Sender<TaskExecutionEvent>,
4961 _cancel: CancellationToken,
4962 ) -> TaskExecutionResult {
4963 TaskExecutionResult {
4964 status: TaskStatus::Completed,
4965 result_text: Some("done".to_string()),
4966 error: None,
4967 terminal_reason: crate::task_manager::TaskTerminalReason::Completed,
4968 }
4969 }
4970 }
4971
4972 #[async_trait]
4973 impl TaskExecutor for AutomationWatcherNoopExecutor {
4974 async fn execute(
4975 &self,
4976 _task: ExecutionTask,
4977 _events: mpsc::Sender<TaskExecutionEvent>,
4978 _cancel: CancellationToken,
4979 ) -> TaskExecutionResult {
4980 TaskExecutionResult {
4981 status: TaskStatus::Completed,
4982 result_text: Some(AUTOMATION_WATCHER_NO_REPORT_SENTINEL.to_string()),
4983 error: None,
4984 terminal_reason: crate::task_manager::TaskTerminalReason::Completed,
4985 }
4986 }
4987 }
4988
4989 fn automation_task_config(root: PathBuf) -> TaskManagerConfig {
4990 TaskManagerConfig {
4991 data_dir: root,
4992 worker_count: 1,
4993 default_workspace: PathBuf::from("."),
4994 default_model: "deepseek-v4-flash".to_string(),
4995 default_mode: "plan".to_string(),
4996 allow_shell: true,
4997 trust_mode: true,
4998 execution_limits: crate::task_manager::TaskExecutionLimits::default(),
4999 human_waits_answerable: false,
5000 }
5001 }
5002
5003 fn automation_record_with_settings(
5004 mode: Option<&str>,
5005 allow_shell: Option<bool>,
5006 trust_mode: Option<bool>,
5007 auto_approve: Option<bool>,
5008 ) -> AutomationRecord {
5009 let now = Utc::now();
5010 AutomationRecord {
5011 destination_thread_id: None,
5012 schema_version: CURRENT_AUTOMATION_SCHEMA_VERSION,
5013 execution_scope: Some(crate::task_manager::test_execution_scope("test")),
5014 id: Uuid::new_v4().to_string(),
5015 name: "Test automation".to_string(),
5016 prompt: "Run the automation".to_string(),
5017 rrule: "FREQ=HOURLY;INTERVAL=1".to_string(),
5018 cwds: Vec::new(),
5019 model: None,
5020 model_provider: None,
5021 model_provider_id: None,
5022 mode: mode.map(ToString::to_string),
5023 allow_shell,
5024 trust_mode,
5025 auto_approve,
5026 delivery_mode: None,
5027 status: AutomationStatus::Active,
5028 created_at: now,
5029 updated_at: now,
5030 next_run_at: None,
5031 last_run_at: None,
5032 revision: 0,
5033 disallowed_tools: Vec::new(),
5034 }
5035 }
5036
5037 fn queued_run_for(automation: &AutomationRecord) -> AutomationRunRecord {
5038 let now = Utc::now();
5039 AutomationRunRecord {
5040 schema_version: CURRENT_RUN_SCHEMA_VERSION,
5041 id: Uuid::new_v4().to_string(),
5042 automation_id: automation.id.clone(),
5043 scheduled_for: now,
5044 status: AutomationRunStatus::Queued,
5045 created_at: now,
5046 started_at: None,
5047 ended_at: None,
5048 task_id: None,
5049 thread_id: None,
5050 turn_id: None,
5051 error: None,
5052 dispatch: None,
5053 }
5054 }
5055
5056 fn eastern_datetime(year: i32, month: u32, day: u32, hour: u32, minute: u32) -> DateTime<Utc> {
5057 Eastern2026
5058 .with_ymd_and_hms(year, month, day, hour, minute, 0)
5059 .single()
5060 .expect("unambiguous Eastern wall time")
5061 .with_timezone(&Utc)
5062 }
5063
5064 fn anchored_automation(
5065 created_at: DateTime<Utc>,
5066 status: AutomationStatus,
5067 ) -> AutomationRecord {
5068 let mut record = automation_record_with_settings(None, None, None, None);
5069 record.rrule = "FREQ=HOURLY;INTERVAL=7;BYMINUTE=17".to_string();
5070 record.status = status;
5071 record.created_at = created_at;
5072 record.updated_at = created_at;
5073 record.next_run_at = None;
5074 record
5075 }
5076
5077 fn local_naive_to_utc(naive: NaiveDateTime) -> DateTime<Utc> {
5078 Local
5079 .from_local_datetime(&naive)
5080 .earliest()
5081 .expect("valid unambiguous local time")
5082 .with_timezone(&Utc)
5083 }
5084
5085 #[test]
5086 fn parses_hourly_rrule() {
5087 let parsed =
5088 AutomationSchedule::parse_rrule("FREQ=HOURLY;INTERVAL=2;BYDAY=MO,TU").expect("parse");
5089 match parsed {
5090 AutomationSchedule::Hourly {
5091 interval_hours,
5092 byday,
5093 ..
5094 } => {
5095 assert_eq!(interval_hours, 2);
5096 assert_eq!(byday.expect("byday").len(), 2);
5097 }
5098 _ => panic!("expected hourly"),
5099 }
5100 }
5101
5102 #[test]
5103 fn parses_once_rrule() {
5104 let parsed =
5105 AutomationSchedule::parse_rrule("FREQ=ONCE;AT=2026-08-03T14:30").expect("parse");
5106 match parsed {
5107 AutomationSchedule::Once { at } => {
5108 assert_eq!(
5109 at,
5110 local_naive_to_utc(
5111 NaiveDateTime::parse_from_str("2026-08-03T14:30", "%Y-%m-%dT%H:%M")
5112 .expect("naive")
5113 )
5114 );
5115 }
5116 _ => panic!("expected once"),
5117 }
5118 }
5119
5120 #[test]
5121 fn parses_hourly_clock_anchor() {
5122 let parsed =
5123 AutomationSchedule::parse_rrule("FREQ=HOURLY;INTERVAL=24;BYHOUR=8;BYMINUTE=30")
5124 .expect("parse anchored hourly schedule");
5125
5126 assert!(matches!(
5127 parsed,
5128 AutomationSchedule::Hourly {
5129 anchor_hour: Some(8),
5130 anchor_minute: Some(30),
5131 ..
5132 }
5133 ));
5134
5135 let minute_only = AutomationSchedule::parse_rrule("FREQ=HOURLY;INTERVAL=1;BYMINUTE=15")
5136 .expect("parse minute-only anchor");
5137 assert!(matches!(
5138 minute_only,
5139 AutomationSchedule::Hourly {
5140 anchor_hour: None,
5141 anchor_minute: Some(15),
5142 ..
5143 }
5144 ));
5145 }
5146
5147 #[test]
5148 fn anchored_hourly_schedule_keeps_wall_time_across_spring_forward() {
5149 let schedule =
5150 AutomationSchedule::parse_rrule("FREQ=HOURLY;INTERVAL=24;BYHOUR=8;BYMINUTE=30")
5151 .expect("parse");
5152 let created_at = eastern_datetime(2026, 3, 6, 7, 0);
5153 let after = eastern_datetime(2026, 3, 7, 9, 0);
5154
5155 let next = schedule
5156 .next_after_in_timezone(after, created_at, &Eastern2026)
5157 .expect("next run");
5158
5159 assert_eq!(next, eastern_datetime(2026, 3, 8, 8, 30));
5160 }
5161
5162 #[test]
5163 fn anchored_hourly_schedule_keeps_wall_time_across_fall_back() {
5164 let schedule =
5165 AutomationSchedule::parse_rrule("FREQ=HOURLY;INTERVAL=24;BYHOUR=8;BYMINUTE=30")
5166 .expect("parse");
5167 let created_at = eastern_datetime(2026, 10, 30, 7, 0);
5168 let after = eastern_datetime(2026, 10, 31, 9, 0);
5169
5170 let next = schedule
5171 .next_after_in_timezone(after, created_at, &Eastern2026)
5172 .expect("next run");
5173
5174 assert_eq!(next, eastern_datetime(2026, 11, 1, 8, 30));
5175 }
5176
5177 #[test]
5178 fn anchored_hourly_schedule_skips_nonexistent_wall_time() {
5179 let schedule =
5180 AutomationSchedule::parse_rrule("FREQ=HOURLY;INTERVAL=24;BYHOUR=2;BYMINUTE=30")
5181 .expect("parse");
5182 let created_at = eastern_datetime(2026, 3, 7, 1, 0);
5183 let after = eastern_datetime(2026, 3, 7, 3, 0);
5184
5185 let next = schedule
5186 .next_after_in_timezone(after, created_at, &Eastern2026)
5187 .expect("next run after spring-forward gap");
5188
5189 assert_eq!(next, eastern_datetime(2026, 3, 9, 2, 30));
5190 }
5191
5192 #[test]
5193 fn anchored_hourly_schedule_uses_first_ambiguous_wall_time_once() {
5194 let schedule =
5195 AutomationSchedule::parse_rrule("FREQ=HOURLY;INTERVAL=24;BYHOUR=1;BYMINUTE=30")
5196 .expect("parse");
5197 let created_at = eastern_datetime(2026, 10, 31, 0, 0);
5198 let after = eastern_datetime(2026, 10, 31, 2, 0);
5199 let first_fold_occurrence = Eastern2026
5200 .with_ymd_and_hms(2026, 11, 1, 1, 30, 0)
5201 .earliest()
5202 .expect("first fold occurrence")
5203 .with_timezone(&Utc);
5204
5205 let next = schedule
5206 .next_after_in_timezone(after, created_at, &Eastern2026)
5207 .expect("next run at fall-back fold");
5208 assert_eq!(next, first_fold_occurrence);
5209
5210 let during_second_fold = Eastern2026
5211 .with_ymd_and_hms(2026, 11, 1, 1, 15, 0)
5212 .latest()
5213 .expect("second fold occurrence")
5214 .with_timezone(&Utc);
5215 let after_fold = schedule
5216 .next_after_in_timezone(during_second_fold, created_at, &Eastern2026)
5217 .expect("next run after fold");
5218 assert_eq!(after_fold, eastern_datetime(2026, 11, 2, 1, 30));
5219 }
5220
5221 #[test]
5222 fn anchored_hourly_schedule_reuses_persisted_anchor_after_restart_and_resume() {
5223 let rrule = "FREQ=HOURLY;INTERVAL=24;BYHOUR=8;BYMINUTE=30";
5224 let created_at = eastern_datetime(2026, 3, 6, 7, 0);
5225 let schedule = AutomationSchedule::parse_rrule(rrule).expect("parse");
5226 let before_restart = schedule
5227 .next_after_in_timezone(
5228 eastern_datetime(2026, 3, 7, 12, 0),
5229 created_at,
5230 &Eastern2026,
5231 )
5232 .expect("next before restart");
5233 assert_eq!(before_restart, eastern_datetime(2026, 3, 8, 8, 30));
5234
5235 // Reparsing models a process restart; the persisted creation timestamp
5236 // remains the recurrence anchor when the record is loaded or resumed.
5237 let restarted = AutomationSchedule::parse_rrule(rrule).expect("reparse after restart");
5238 let after_restart = restarted
5239 .next_after_in_timezone(
5240 eastern_datetime(2026, 3, 8, 10, 0),
5241 created_at,
5242 &Eastern2026,
5243 )
5244 .expect("next after restart");
5245 assert_eq!(after_restart, eastern_datetime(2026, 3, 9, 8, 30));
5246
5247 let after_resume = restarted
5248 .next_after_in_timezone(
5249 eastern_datetime(2026, 3, 10, 12, 0),
5250 created_at,
5251 &Eastern2026,
5252 )
5253 .expect("next after resume");
5254 assert_eq!(after_resume, eastern_datetime(2026, 3, 11, 8, 30));
5255 }
5256
5257 #[test]
5258 fn scheduler_restart_uses_persisted_creation_anchor() {
5259 let tempdir = tempfile::tempdir().expect("tempdir");
5260 let now = Utc::now();
5261 let created_at = now - Duration::hours(51);
5262 let automation = anchored_automation(created_at, AutomationStatus::Active);
5263 let schedule = AutomationSchedule::parse_rrule(&automation.rrule).expect("parse");
5264 let expected = schedule
5265 .next_after_with_anchor(now, created_at)
5266 .expect("persisted-anchor schedule");
5267 let reset_anchor = schedule
5268 .next_after_with_anchor(now, now)
5269 .expect("reset-anchor schedule");
5270 assert_ne!(expected, reset_anchor, "fixture must detect anchor resets");
5271
5272 let manager =
5273 AutomationManager::open_for_test(tempdir.path().to_path_buf()).expect("manager");
5274 manager.save_automation(&automation).expect("save");
5275 drop(manager);
5276
5277 let restarted =
5278 AutomationManager::open_for_test(tempdir.path().to_path_buf()).expect("reopen");
5279 assert!(
5280 restarted
5281 .collect_due_runs(now)
5282 .expect("restart tick")
5283 .is_empty(),
5284 "an uninitialized future slot must not enqueue immediately"
5285 );
5286 let reloaded = restarted
5287 .get_automation(&automation.id)
5288 .expect("reloaded automation");
5289 assert_eq!(reloaded.next_run_at, Some(expected));
5290 }
5291
5292 #[test]
5293 fn resume_uses_persisted_creation_anchor() {
5294 let tempdir = tempfile::tempdir().expect("tempdir");
5295 let manager =
5296 AutomationManager::open_for_test(tempdir.path().to_path_buf()).expect("manager");
5297 let before = Utc::now();
5298 let created_at = before - Duration::hours(51);
5299 let automation = anchored_automation(created_at, AutomationStatus::Paused);
5300 let schedule = AutomationSchedule::parse_rrule(&automation.rrule).expect("parse");
5301 manager.save_automation(&automation).expect("save");
5302
5303 let expected_before = schedule
5304 .next_after_with_anchor(before, created_at)
5305 .expect("next before resume");
5306 let reset_anchor = schedule
5307 .next_after_with_anchor(before, before)
5308 .expect("reset-anchor schedule");
5309 assert_ne!(
5310 expected_before, reset_anchor,
5311 "fixture must detect anchor resets"
5312 );
5313
5314 let resumed = manager
5315 .resume_automation(&automation.id)
5316 .expect("resume automation");
5317 let after = Utc::now();
5318 let expected_after = schedule
5319 .next_after_with_anchor(after, created_at)
5320 .expect("next after resume");
5321 let actual = resumed.next_run_at.expect("resumed next run");
5322 assert!(
5323 actual == expected_before || actual == expected_after,
5324 "resume must keep the persisted creation anchor"
5325 );
5326 }
5327
5328 #[test]
5329 fn anchored_hourly_schedule_applies_byday_on_calendar_slots() {
5330 let schedule = AutomationSchedule::parse_rrule(
5331 "FREQ=HOURLY;INTERVAL=24;BYDAY=MO,TU,WE,TH,FR;BYHOUR=8;BYMINUTE=30",
5332 )
5333 .expect("parse");
5334 let created_at = eastern_datetime(2026, 3, 6, 7, 0);
5335
5336 let next = schedule
5337 .next_after_in_timezone(eastern_datetime(2026, 3, 6, 9, 0), created_at, &Eastern2026)
5338 .expect("next weekday run");
5339
5340 assert_eq!(next, eastern_datetime(2026, 3, 9, 8, 30));
5341 }
5342
5343 #[test]
5344 fn parses_weekly_rrule() {
5345 let parsed =
5346 AutomationSchedule::parse_rrule("FREQ=WEEKLY;BYDAY=MO,WE;BYHOUR=9;BYMINUTE=30")
5347 .expect("parse");
5348 match parsed {
5349 AutomationSchedule::Weekly {
5350 byday,
5351 byhour,
5352 byminute,
5353 } => {
5354 assert_eq!(byday.len(), 2);
5355 assert_eq!(byhour, 9);
5356 assert_eq!(byminute, 30);
5357 }
5358 _ => panic!("expected weekly"),
5359 }
5360 }
5361
5362 #[test]
5363 fn parses_cron_rrule_and_computes_next_minute_slot() {
5364 let schedule =
5365 AutomationSchedule::parse_rrule("FREQ=CRON;EXPR=*/17 * * * *").expect("parse");
5366 let after = Utc
5367 .with_ymd_and_hms(2026, 8, 3, 9, 17, 1)
5368 .single()
5369 .expect("after");
5370 let next = schedule
5371 .next_after_in_timezone(after, after, &Utc)
5372 .expect("next cron run");
5373 assert_eq!(
5374 next,
5375 Utc.with_ymd_and_hms(2026, 8, 3, 9, 34, 0)
5376 .single()
5377 .expect("next")
5378 );
5379 }
5380
5381 #[test]
5382 fn cron_weekday_schedule_uses_standard_five_field_local_time() {
5383 let schedule =
5384 AutomationSchedule::parse_rrule("FREQ=CRON;EXPR=3 9 * * MON-FRI").expect("parse");
5385 let after = Utc
5386 .with_ymd_and_hms(2026, 8, 7, 9, 4, 0)
5387 .single()
5388 .expect("after");
5389 let next = schedule
5390 .next_after_in_timezone(after, after, &Utc)
5391 .expect("next weekday cron run");
5392 assert_eq!(
5393 next,
5394 Utc.with_ymd_and_hms(2026, 8, 10, 9, 3, 0)
5395 .single()
5396 .expect("next")
5397 );
5398 }
5399
5400 #[test]
5401 fn cron_rejects_impossible_date() {
5402 let err = AutomationSchedule::parse_rrule("FREQ=CRON;EXPR=0 9 31 2 *")
5403 .expect_err("impossible february date must fail");
5404 assert!(err.to_string().contains("can never occur"));
5405 }
5406
5407 #[test]
5408 fn rejects_invalid_rrule_fields() {
5409 let err =
5410 AutomationSchedule::parse_rrule("FREQ=WEEKLY;BYSECOND=5").expect_err("should fail");
5411 assert!(err.to_string().contains("Unsupported RRULE field"));
5412 }
5413
5414 #[test]
5415 fn automation_model_round_trips_through_create_and_update() {
5416 let tempdir = tempfile::tempdir().expect("tempdir");
5417 let manager =
5418 AutomationManager::open_for_test(tempdir.path().to_path_buf()).expect("manager");
5419
5420 let created = manager
5421 .create_automation(CreateAutomationRequest {
5422 destination_thread_id: None,
5423 name: "Pinned model".to_string(),
5424 prompt: "prompt".to_string(),
5425 rrule: "FREQ=HOURLY;INTERVAL=1".to_string(),
5426 cwds: Vec::new(),
5427 model: Some(" scheduled-model ".to_string()),
5428 model_provider: None,
5429 model_provider_id: None,
5430 mode: None,
5431 allow_shell: None,
5432 trust_mode: None,
5433 auto_approve: None,
5434 delivery_mode: None,
5435 status: Some(AutomationStatus::Active),
5436 disallowed_tools: Vec::new(),
5437 })
5438 .expect("create");
5439 assert_eq!(created.model.as_deref(), Some("scheduled-model"));
5440 assert_eq!(
5441 manager
5442 .get_automation(&created.id)
5443 .expect("reload")
5444 .model
5445 .as_deref(),
5446 Some("scheduled-model")
5447 );
5448
5449 let updated = manager
5450 .update_automation(
5451 &created.id,
5452 UpdateAutomationRequest {
5453 model: Some("replacement-model".to_string()),
5454 ..UpdateAutomationRequest::default()
5455 },
5456 )
5457 .expect("update");
5458 assert_eq!(updated.model.as_deref(), Some("replacement-model"));
5459 }
5460
5461 #[test]
5462 fn delete_refuses_active_receipts_then_archives_settled_runs() {
5463 let tempdir = tempfile::tempdir().expect("tempdir");
5464 let manager =
5465 AutomationManager::open_for_test(tempdir.path().to_path_buf()).expect("manager");
5466
5467 let created = manager
5468 .create_automation(CreateAutomationRequest {
5469 destination_thread_id: None,
5470 name: "Delete me".to_string(),
5471 prompt: "prompt".to_string(),
5472 rrule: "FREQ=HOURLY;INTERVAL=1".to_string(),
5473 cwds: Vec::new(),
5474 model: None,
5475 model_provider: None,
5476 model_provider_id: None,
5477 mode: None,
5478 allow_shell: None,
5479 trust_mode: None,
5480 auto_approve: None,
5481 delivery_mode: None,
5482 status: Some(AutomationStatus::Active),
5483 disallowed_tools: Vec::new(),
5484 })
5485 .expect("create");
5486
5487 let run = AutomationRunRecord {
5488 schema_version: CURRENT_RUN_SCHEMA_VERSION,
5489 id: Uuid::new_v4().to_string(),
5490 automation_id: created.id.clone(),
5491 scheduled_for: Utc::now(),
5492 status: AutomationRunStatus::Queued,
5493 created_at: Utc::now(),
5494 started_at: None,
5495 ended_at: None,
5496 task_id: None,
5497 thread_id: None,
5498 turn_id: None,
5499 error: None,
5500 dispatch: None,
5501 };
5502 manager.save_run(&run).expect("save run");
5503 let settled = AutomationRunRecord {
5504 id: Uuid::new_v4().to_string(),
5505 status: AutomationRunStatus::Completed,
5506 created_at: run.created_at - Duration::minutes(1),
5507 ended_at: Some(Utc::now() - Duration::minutes(1)),
5508 ..run.clone()
5509 };
5510 manager.save_run(&settled).expect("save settled run");
5511 assert!(
5512 manager
5513 .runs_dir_for(&created.id)
5514 .expect("runs dir")
5515 .exists()
5516 );
5517
5518 // An unsettled receipt blocks deletion: the definition and both runs
5519 // survive untouched, and nothing is archived yet.
5520 let refused = manager
5521 .delete_automation(&created.id)
5522 .expect_err("active run must block deletion");
5523 assert!(refused.to_string().contains("Refusing to delete"));
5524 assert!(manager.get_automation(&created.id).is_ok());
5525 assert_eq!(
5526 manager
5527 .list_runs(&created.id, None)
5528 .expect("retained receipts")
5529 .len(),
5530 2
5531 );
5532 assert!(
5533 manager
5534 .list_archived_runs(&created.id)
5535 .expect("archive")
5536 .is_empty()
5537 );
5538
5539 // Once the receipt settles, deletion archives the terminal history
5540 // and removes the live paths.
5541 let mut settled_run = run.clone();
5542 settled_run.status = AutomationRunStatus::Completed;
5543 settled_run.started_at = Some(Utc::now());
5544 settled_run.ended_at = Some(Utc::now());
5545 manager.save_run(&settled_run).expect("settle run");
5546
5547 // A sortable record shadows its legacy path while listing. Make the
5548 // older receipt's legacy path a directory so live cleanup fails only
5549 // after both records are archived and the newer receipt is removed.
5550 let blocked_legacy = manager
5551 .legacy_run_path(&created.id, &settled.id)
5552 .expect("legacy path");
5553 fs::create_dir(&blocked_legacy).expect("block legacy cleanup");
5554 let failed = manager
5555 .delete_automation(&created.id)
5556 .expect_err("live cleanup must fail");
5557 assert!(failed.to_string().contains("Failed to delete run"));
5558 assert!(
5559 manager.get_automation(&created.id).is_ok(),
5560 "the definition must survive partial cleanup so deletion can retry"
5561 );
5562 assert!(
5563 !manager
5564 .run_path(&settled_run)
5565 .expect("newer run path")
5566 .exists(),
5567 "a newer receipt was already removed before the failure"
5568 );
5569 assert_eq!(
5570 manager
5571 .list_archived_runs(&created.id)
5572 .expect("partial archive")
5573 .len(),
5574 2,
5575 "both terminal records reached the archive before any live removal"
5576 );
5577 fs::remove_dir(&blocked_legacy).expect("unblock cleanup");
5578 manager
5579 .delete_automation(&created.id)
5580 .expect("retry deletion after partial cleanup");
5581
5582 assert!(manager.get_automation(&created.id).is_err());
5583 assert!(
5584 manager
5585 .list_runs(&created.id, None)
5586 .expect("live runs")
5587 .is_empty()
5588 );
5589 assert!(
5590 !manager
5591 .runs_dir_for(&created.id)
5592 .expect("runs dir")
5593 .exists()
5594 );
5595 let archived = manager
5596 .list_archived_runs(&created.id)
5597 .expect("archived runs");
5598 assert_eq!(
5599 archived.iter().map(|r| r.id.as_str()).collect::<Vec<_>>(),
5600 vec![settled_run.id.as_str(), settled.id.as_str()],
5601 "archive keeps both terminal runs, newest-ended first"
5602 );
5603 assert_eq!(archived[0].status, AutomationRunStatus::Completed);
5604 assert_eq!(archived[1].status, AutomationRunStatus::Completed);
5605 let archive_dir = tempdir.path().join("archive").join(&created.id);
5606 assert_eq!(
5607 fs::read_dir(&archive_dir)
5608 .expect("archive dir")
5609 .filter_map(Result::ok)
5610 .filter(|entry| entry.path().extension().is_some_and(|ext| ext == "json"))
5611 .count(),
5612 2,
5613 "one archived file per terminal run"
5614 );
5615 }
5616
5617 #[test]
5618 fn delete_refuses_automation_with_active_run() {
5619 let tempdir = tempfile::tempdir().expect("tempdir");
5620 let manager =
5621 AutomationManager::open_for_test(tempdir.path().to_path_buf()).expect("manager");
5622 let automation = automation_record_with_settings(None, None, None, None);
5623 manager.save_automation(&automation).expect("save");
5624 manager
5625 .save_run(&queued_run_for(&automation))
5626 .expect("save queued run");
5627
5628 let err = manager
5629 .delete_automation(&automation.id)
5630 .expect_err("delete must refuse while a run is active");
5631 assert!(err.to_string().contains("Refusing to delete"));
5632
5633 assert!(manager.get_automation(&automation.id).is_ok());
5634 assert!(
5635 manager
5636 .runs_dir_for(&automation.id)
5637 .expect("runs dir")
5638 .exists()
5639 );
5640 assert!(
5641 manager
5642 .list_archived_runs(&automation.id)
5643 .expect("archive")
5644 .is_empty()
5645 );
5646 }
5647
5648 #[test]
5649 fn delete_caps_archived_terminal_runs_at_retention_limit() {
5650 let tempdir = tempfile::tempdir().expect("tempdir");
5651 let manager =
5652 AutomationManager::open_for_test(tempdir.path().to_path_buf()).expect("manager");
5653 let automation = automation_record_with_settings(None, None, None, None);
5654 manager.save_automation(&automation).expect("save");
5655
5656 let base = Utc::now();
5657 let total = ARCHIVE_RETAINED_TERMINAL_RUNS + 5;
5658 let mut saved_ids = Vec::new();
5659 for i in 0..total {
5660 let mut run = run_created_at(&automation, base - Duration::minutes(i as i64));
5661 run.status = AutomationRunStatus::Completed;
5662 run.ended_at = Some(base - Duration::minutes(i as i64));
5663 manager.save_run(&run).expect("save run");
5664 saved_ids.push(run.id);
5665 }
5666
5667 manager.delete_automation(&automation.id).expect("delete");
5668
5669 let archived = manager
5670 .list_archived_runs(&automation.id)
5671 .expect("archived runs");
5672 assert_eq!(
5673 archived.len(),
5674 ARCHIVE_RETAINED_TERMINAL_RUNS,
5675 "archive keeps only the retention budget"
5676 );
5677 let retained: std::collections::BTreeSet<&str> =
5678 archived.iter().map(|r| r.id.as_str()).collect();
5679 // `saved_ids` is newest-first (i counts minutes into the past); the
5680 // `total - budget` oldest, at the tail, were dropped.
5681 for dropped in &saved_ids[ARCHIVE_RETAINED_TERMINAL_RUNS..] {
5682 assert!(!retained.contains(dropped.as_str()), "oldest run survived");
5683 }
5684 for kept in &saved_ids[..ARCHIVE_RETAINED_TERMINAL_RUNS] {
5685 assert!(retained.contains(kept.as_str()), "newer run was dropped");
5686 }
5687 }
5688
5689 #[test]
5690 fn scheduler_scan_ignores_archived_runs_after_delete() {
5691 let tempdir = tempfile::tempdir().expect("tempdir");
5692 let manager =
5693 AutomationManager::open_for_test(tempdir.path().to_path_buf()).expect("manager");
5694 let automation = fixture_due_automation(&manager, "archived", 1);
5695 let mut run = run_created_at(&automation, Utc::now());
5696 run.status = AutomationRunStatus::Completed;
5697 run.ended_at = Some(Utc::now());
5698 manager.save_run(&run).expect("save run");
5699
5700 // The due definition is collected before deletion and must not come
5701 // back from the archive afterwards.
5702 let due_before = manager
5703 .collect_due_runs(Utc::now())
5704 .expect("scheduler scan");
5705 assert!(
5706 due_before
5707 .iter()
5708 .any(|(record, _)| record.id == automation.id),
5709 "the fixture automation is due before deletion"
5710 );
5711
5712 manager.delete_automation(&automation.id).expect("delete");
5713 assert!(tempdir.path().join("archive").join(&automation.id).exists());
5714
5715 let due = manager
5716 .collect_due_runs(Utc::now())
5717 .expect("scheduler scan");
5718 assert!(
5719 due.iter().all(|(record, _)| record.id != automation.id),
5720 "the deleted automation must not come back due"
5721 );
5722 assert!(
5723 manager
5724 .list_runs(&automation.id, None)
5725 .expect("live runs")
5726 .is_empty(),
5727 "archived runs must not re-enter the live runs tree"
5728 );
5729 assert_eq!(
5730 manager
5731 .list_archived_runs(&automation.id)
5732 .expect("archived runs")
5733 .len(),
5734 1
5735 );
5736 }
5737
5738 #[test]
5739 fn automation_storage_rejects_traversal_ids() {
5740 let tempdir = tempfile::tempdir().expect("tempdir");
5741 let manager =
5742 AutomationManager::open_for_test(tempdir.path().join("root")).expect("manager");
5743 let escaped_file = tempdir.path().join("escape.json");
5744 let escaped_runs = tempdir.path().join("escape-runs");
5745
5746 let err = manager
5747 .get_automation("../escape")
5748 .expect_err("traversal automation ids must be rejected");
5749 assert!(err.to_string().contains("single path component"));
5750 assert!(!escaped_file.exists());
5751
5752 let err = manager
5753 .list_runs("../escape-runs", None)
5754 .expect_err("traversal run dirs must be rejected");
5755 assert!(err.to_string().contains("single path component"));
5756 assert!(!escaped_runs.exists());
5757
5758 let run = AutomationRunRecord {
5759 schema_version: CURRENT_RUN_SCHEMA_VERSION,
5760 id: "../escape-run".to_string(),
5761 automation_id: Uuid::new_v4().to_string(),
5762 scheduled_for: Utc::now(),
5763 status: AutomationRunStatus::Queued,
5764 created_at: Utc::now(),
5765 started_at: None,
5766 ended_at: None,
5767 task_id: None,
5768 thread_id: None,
5769 turn_id: None,
5770 error: None,
5771 dispatch: None,
5772 };
5773 let err = manager
5774 .save_run(&run)
5775 .expect_err("traversal run ids must be rejected");
5776 assert!(err.to_string().contains("single path component"));
5777 assert!(!tempdir.path().join("escape-run.json").exists());
5778 }
5779
5780 #[test]
5781 fn automation_task_settings_default_for_legacy_records() {
5782 let now = Utc::now().to_rfc3339();
5783 let record: AutomationRecord = serde_json::from_value(serde_json::json!({
5784 "schema_version": CURRENT_AUTOMATION_SCHEMA_VERSION,
5785 "id": Uuid::new_v4().to_string(),
5786 "name": "Legacy automation",
5787 "prompt": "Run legacy automation",
5788 "rrule": "FREQ=HOURLY;INTERVAL=1",
5789 "cwds": [],
5790 "status": "active",
5791 "created_at": now,
5792 "updated_at": now
5793 }))
5794 .expect("legacy automation record should deserialize");
5795
5796 assert_eq!(record.mode, None);
5797 assert_eq!(record.task_mode(), "agent");
5798 assert!(!record.task_allow_shell());
5799 assert!(!record.task_trust_mode());
5800 assert!(!record.task_auto_approve());
5801 assert_eq!(record.delivery_mode(), AutomationDeliveryMode::Task);
5802 }
5803
5804 #[test]
5805 fn automation_requests_pin_the_posture_its_bit_stands_for() {
5806 let now = Utc::now().to_rfc3339();
5807 let legacy: AutomationRecord = serde_json::from_value(serde_json::json!({
5808 "schema_version": CURRENT_AUTOMATION_SCHEMA_VERSION,
5809 "id": Uuid::new_v4().to_string(),
5810 "name": "Nightly",
5811 "prompt": "Run the nightly sweep",
5812 "rrule": "FREQ=DAILY",
5813 "cwds": [],
5814 "status": "active",
5815 "created_at": now,
5816 "updated_at": now
5817 }))
5818 .expect("legacy automation record");
5819
5820 // No session exists when a scheduler fires, so the request states the
5821 // posture the record's own authority means instead of leaving the
5822 // runtime to re-derive it from the bit.
5823 assert!(legacy.auto_approve.is_none());
5824 assert_eq!(
5825 automation_task_request(&legacy)
5826 .permission_posture
5827 .as_deref(),
5828 Some("ask")
5829 );
5830
5831 let elevated: AutomationRecord = serde_json::from_value(serde_json::json!({
5832 "schema_version": CURRENT_AUTOMATION_SCHEMA_VERSION,
5833 "id": Uuid::new_v4().to_string(),
5834 "name": "Nightly, unattended",
5835 "prompt": "Run the nightly sweep",
5836 "rrule": "FREQ=DAILY",
5837 "cwds": [],
5838 "auto_approve": true,
5839 "status": "active",
5840 "created_at": now,
5841 "updated_at": now
5842 }))
5843 .expect("elevated automation record");
5844 assert_eq!(
5845 automation_task_request(&elevated)
5846 .permission_posture
5847 .as_deref(),
5848 Some("full_access")
5849 );
5850 }
5851
5852 #[tokio::test]
5853 async fn automation_enqueue_uses_default_and_explicit_task_settings() -> Result<()> {
5854 let tempdir = tempfile::tempdir().expect("tempdir");
5855 let task_manager = TaskManager::start_with_executor(
5856 automation_task_config(tempdir.path().join("tasks")),
5857 std::sync::Arc::new(AutomationNoopExecutor),
5858 )
5859 .await?;
5860
5861 let default_automation = automation_record_with_settings(None, None, None, None);
5862 let mut default_run = queued_run_for(&default_automation);
5863 bind_run_dispatch(
5864 &mut default_run,
5865 &default_automation,
5866 &task_manager.data_dir(),
5867 false,
5868 )?;
5869 enqueue_run_task(&mut default_run, &task_manager).await;
5870 let default_task = task_manager
5871 .get_task(default_run.task_id.as_deref().expect("task id"))
5872 .await?;
5873 assert_eq!(default_task.model, "deepseek-v4-flash");
5874 assert_eq!(default_task.mode, "agent");
5875 assert!(!default_task.allow_shell);
5876 assert!(!default_task.trust_mode);
5877 assert!(!default_task.auto_approve);
5878
5879 let mut explicit_automation =
5880 automation_record_with_settings(Some("plan"), Some(false), Some(false), Some(false));
5881 explicit_automation.model = Some("scheduled-model".to_string());
5882 let mut explicit_run = queued_run_for(&explicit_automation);
5883 bind_run_dispatch(
5884 &mut explicit_run,
5885 &explicit_automation,
5886 &task_manager.data_dir(),
5887 false,
5888 )?;
5889 enqueue_run_task(&mut explicit_run, &task_manager).await;
5890 let explicit_task = task_manager
5891 .get_task(explicit_run.task_id.as_deref().expect("task id"))
5892 .await?;
5893 assert_eq!(explicit_task.model, "scheduled-model");
5894 assert_eq!(explicit_task.mode, "plan");
5895 assert!(!explicit_task.allow_shell);
5896 assert!(!explicit_task.trust_mode);
5897 assert!(!explicit_task.auto_approve);
5898
5899 task_manager.shutdown();
5900 Ok(())
5901 }
5902
5903 #[tokio::test]
5904 async fn unattended_elevated_automation_dispatch_is_refused() -> Result<()> {
5905 let tempdir = tempfile::tempdir().expect("tempdir");
5906 let task_manager = TaskManager::start_with_executor(
5907 automation_task_config(tempdir.path().join("tasks")),
5908 std::sync::Arc::new(AutomationNoopExecutor),
5909 )
5910 .await?;
5911
5912 for (label, allow_shell, trust_mode, auto_approve) in [
5913 ("auto_approve", Some(false), Some(false), Some(true)),
5914 ("trust_mode", Some(false), Some(true), Some(false)),
5915 ("allow_shell", Some(true), Some(false), Some(false)),
5916 ("all", Some(true), Some(true), Some(true)),
5917 ] {
5918 let automation = automation_record_with_settings(
5919 Some("agent"),
5920 allow_shell,
5921 trust_mode,
5922 auto_approve,
5923 );
5924 let mut run = queued_run_for(&automation);
5925 let err = bind_run_dispatch(&mut run, &automation, &task_manager.data_dir(), false)
5926 .expect_err(&format!("{label} must be refused at bind_run_dispatch"));
5927 assert!(
5928 err.to_string().contains("elevated permissions"),
5929 "{label}: {err}"
5930 );
5931 assert!(run.dispatch.is_none());
5932 assert!(run.task_id.is_none());
5933 }
5934
5935 let safe =
5936 automation_record_with_settings(Some("agent"), Some(false), Some(false), Some(false));
5937 let mut tampered_run = queued_run_for(&safe);
5938 bind_run_dispatch(&mut tampered_run, &safe, &task_manager.data_dir(), false)?;
5939 let tampered_task_id = tampered_run.task_id.clone().expect("task id");
5940 tampered_run
5941 .dispatch
5942 .as_mut()
5943 .expect("dispatch")
5944 .request
5945 .permission_posture = Some("FULL-ACCESS".to_string());
5946 tampered_run
5947 .dispatch
5948 .as_mut()
5949 .expect("dispatch")
5950 .request
5951 .owner_session_id = Some(" ".to_string());
5952 enqueue_run_task(&mut tampered_run, &task_manager).await;
5953 assert_eq!(tampered_run.status, AutomationRunStatus::Failed);
5954 assert!(
5955 tampered_run
5956 .error
5957 .as_deref()
5958 .is_some_and(|e| e.contains("Full Access, trust or shell")),
5959 "{:?}",
5960 tampered_run.error
5961 );
5962 assert!(!tampered_run.dispatch.as_ref().unwrap().accepted);
5963 assert!(task_manager.get_task(&tampered_task_id).await.is_err());
5964
5965 task_manager.shutdown();
5966 Ok(())
5967 }
5968
5969 #[tokio::test]
5970 async fn automation_provider_pin_survives_active_route_change_and_legacy_inherits() -> Result<()>
5971 {
5972 let _env = crate::test_support::lock_test_env();
5973 let root = tempfile::tempdir()?;
5974 let mut config: codewhale_runtime::config::Config = toml::from_str(
5975 r#"
5976 provider = "first"
5977 [providers.first]
5978 kind = "openai-compatible"
5979 base_url = "http://127.0.0.1:9/first/v1"
5980 api_key = "fixture-first"
5981 model = "private-model"
5982 [providers.second]
5983 kind = "openai-compatible"
5984 base_url = "http://127.0.0.1:9/second/v1"
5985 api_key = "fixture-second"
5986 model = "private-model"
5987 "#,
5988 )?;
5989 let automations = AutomationManager::open_for_test(root.path().join("schedules"))?;
5990 let mut record = automation_record_with_settings(None, None, None, None);
5991 record.schema_version = 1;
5992 record.model = Some("private-model".to_string());
5993 record.model_provider = Some("custom".to_string());
5994 record.model_provider_id = Some("first".to_string());
5995 automations.save_automation(&record)?;
5996 let record = automations.get_automation(&record.id)?;
5997 assert_eq!(
5998 record.schema_version, CURRENT_AUTOMATION_SCHEMA_VERSION,
5999 "a pin cannot be ignored by an older reader"
6000 );
6001
6002 let runtime = crate::runtime_threads::manager::RuntimeThreadManager::open(
6003 config.clone(),
6004 root.path().to_path_buf(),
6005 crate::runtime_threads::manager::RuntimeThreadManagerConfig::from_task_data_dir(
6006 root.path().join("runtime"),
6007 ),
6008 )?;
6009 config.provider = Some("second".to_string());
6010 runtime.reload_config(config).await?;
6011 let tasks = TaskManager::start_with_executor(
6012 automation_task_config(root.path().join("tasks")),
6013 std::sync::Arc::new(AutomationNoopExecutor),
6014 )
6015 .await?;
6016 let mut run = queued_run_for(&record);
6017 bind_run_dispatch(&mut run, &record, &tasks.data_dir(), false)?;
6018 enqueue_run_task(&mut run, &tasks).await;
6019 let task = tasks
6020 .get_task(run.task_id.as_deref().expect("task id"))
6021 .await?;
6022 let task: crate::task_manager::TaskRecord =
6023 serde_json::from_slice(&serde_json::to_vec(&task)?)?;
6024 assert_eq!(task.schema_version, 4);
6025 let thread = runtime
6026 .create_thread(ExecutionTask::from(&task).thread_request())
6027 .await?;
6028 assert_eq!(thread.model, "private-model");
6029 assert_eq!(thread.model_provider.as_deref(), Some("custom"));
6030 assert_eq!(thread.model_provider_id.as_deref(), Some("first"));
6031
6032 let mut legacy = serde_json::to_value(&record)?;
6033 let object = legacy.as_object_mut().unwrap();
6034 object.remove("model_provider");
6035 object.remove("model_provider_id");
6036 object.insert("schema_version".to_string(), serde_json::json!(1));
6037 let legacy: AutomationRecord = serde_json::from_value(legacy)?;
6038 assert_eq!(legacy.model_provider, None);
6039 let mut run = queued_run_for(&legacy);
6040 bind_run_dispatch(&mut run, &legacy, &tasks.data_dir(), false)?;
6041 enqueue_run_task(&mut run, &tasks).await;
6042 let task = tasks
6043 .get_task(run.task_id.as_deref().expect("legacy task id"))
6044 .await?;
6045 let mut value = serde_json::to_value(&task)?;
6046 value.as_object_mut().unwrap().remove("model_provider");
6047 value.as_object_mut().unwrap().remove("model_provider_id");
6048 value["schema_version"] = serde_json::json!(2);
6049 let task: crate::task_manager::TaskRecord = serde_json::from_value(value)?;
6050 let thread = runtime
6051 .create_thread(ExecutionTask::from(&task).thread_request())
6052 .await?;
6053 assert_eq!(thread.model_provider_id.as_deref(), Some("second"));
6054 assert_eq!(thread.model, "private-model");
6055 tasks.shutdown();
6056 Ok(())
6057 }
6058
6059 #[tokio::test]
6060 async fn delayed_trigger_fires_task_with_same_owner_and_skips_legacy_ownerless() -> Result<()> {
6061 let tempdir = tempfile::tempdir().expect("tempdir");
6062 let task_manager = TaskManager::start_with_executor(
6063 automation_task_config(tempdir.path().join("tasks")),
6064 std::sync::Arc::new(AutomationNoopExecutor),
6065 )
6066 .await?;
6067 let manager = AutomationManager::open_for_test(tempdir.path().join("automations"))?;
6068
6069 let mut owned = manager.create_trigger(CreateDelayedTriggerRequest {
6070 destination_thread_id: None,
6071 fire_at: Utc::now() + Duration::hours(1),
6072 message: "owned delayed continuation".to_string(),
6073 workspace: None,
6074 owner_session_id: Some("session-a".to_string()),
6075 parent_trigger_id: None,
6076 disallowed_tools: Vec::new(),
6077 })?;
6078 owned.fire_at = Utc::now() - Duration::minutes(1);
6079 manager.save_trigger(&owned)?;
6080
6081 let mut legacy = manager.create_trigger(CreateDelayedTriggerRequest {
6082 destination_thread_id: None,
6083 fire_at: Utc::now() + Duration::hours(1),
6084 message: "legacy delayed continuation".to_string(),
6085 workspace: None,
6086 owner_session_id: None,
6087 parent_trigger_id: None,
6088 disallowed_tools: Vec::new(),
6089 })?;
6090 legacy.fire_at = Utc::now() - Duration::minutes(1);
6091 manager.save_trigger(&legacy)?;
6092
6093 let shared = Arc::new(Mutex::new(manager));
6094 fire_due_triggers_shared(&shared, &task_manager).await?;
6095
6096 let manager = shared.lock().await;
6097 let fired = manager.get_trigger(&owned.trigger_id)?;
6098 assert_eq!(fired.status, DelayedTriggerStatus::Fired);
6099 let task = task_manager
6100 .get_task(fired.task_id.as_deref().expect("fired task id"))
6101 .await?;
6102 assert_eq!(task.owner_session_id.as_deref(), Some("session-a"));
6103
6104 let legacy_after = manager.get_trigger(&legacy.trigger_id)?;
6105 assert_eq!(legacy_after.status, DelayedTriggerStatus::Pending);
6106 assert!(legacy_after.task_id.is_none());
6107 drop(manager);
6108 task_manager.shutdown();
6109 Ok(())
6110 }
6111
6112 #[test]
6113 fn legacy_delayed_trigger_deserializes_without_owner() -> Result<()> {
6114 let now = Utc::now();
6115 let record: DelayedTriggerRecord = serde_json::from_value(serde_json::json!({
6116 "schema_version": CURRENT_TRIGGER_SCHEMA_VERSION,
6117 "trigger_id": "trig_legacy",
6118 "fire_at": (now + Duration::hours(1)).to_rfc3339(),
6119 "message": "legacy trigger",
6120 "status": "pending",
6121 "created_at": now.to_rfc3339(),
6122 "fired_at": null,
6123 "task_id": null,
6124 "thread_id": null,
6125 "error": null,
6126 "parent_trigger_id": null
6127 }))?;
6128 assert_eq!(record.owner_session_id, None);
6129 Ok(())
6130 }
6131
6132 #[test]
6133 fn denied_automation_and_run_use_v4_schema_while_open_stay_v3() -> Result<()> {
6134 let tempdir = tempfile::tempdir()?;
6135 let manager = AutomationManager::open_for_test(tempdir.path().join("automations"))?;
6136
6137 let open = manager.create_automation(CreateAutomationRequest {
6138 destination_thread_id: None,
6139 name: "Open".to_string(),
6140 prompt: "prompt".to_string(),
6141 rrule: "FREQ=HOURLY;INTERVAL=1".to_string(),
6142 cwds: Vec::new(),
6143 model: None,
6144 model_provider: None,
6145 model_provider_id: None,
6146 mode: None,
6147 allow_shell: None,
6148 trust_mode: None,
6149 auto_approve: None,
6150 delivery_mode: None,
6151 status: Some(AutomationStatus::Active),
6152 disallowed_tools: vec![" ".to_string()],
6153 })?;
6154 assert_eq!(open.schema_version, CURRENT_AUTOMATION_SCHEMA_VERSION);
6155 assert!(open.disallowed_tools.is_empty());
6156
6157 let open_disk: serde_json::Value =
6158 serde_json::from_str(&fs::read_to_string(manager.automation_path(&open.id)?)?)?;
6159 assert_eq!(
6160 open_disk["schema_version"],
6161 CURRENT_AUTOMATION_SCHEMA_VERSION
6162 );
6163 assert!(open_disk.get("disallowed_tools").is_none());
6164
6165 let mut open_run = new_run_record(&open.id, Utc::now(), Utc::now());
6166 bind_run_dispatch(&mut open_run, &open, tempdir.path(), true)?;
6167 manager.save_run(&open_run)?;
6168 let open_run_disk: serde_json::Value =
6169 serde_json::from_str(&fs::read_to_string(manager.run_path(&open_run)?)?)?;
6170 assert_eq!(open_run.schema_version, CURRENT_RUN_SCHEMA_VERSION);
6171 assert_eq!(open_run_disk["schema_version"], CURRENT_RUN_SCHEMA_VERSION);
6172
6173 let restricted = manager.create_automation(CreateAutomationRequest {
6174 destination_thread_id: None,
6175 name: "Restricted".to_string(),
6176 prompt: "prompt".to_string(),
6177 rrule: "FREQ=HOURLY;INTERVAL=1".to_string(),
6178 cwds: Vec::new(),
6179 model: None,
6180 model_provider: None,
6181 model_provider_id: None,
6182 mode: None,
6183 allow_shell: None,
6184 trust_mode: None,
6185 auto_approve: None,
6186 delivery_mode: None,
6187 status: Some(AutomationStatus::Active),
6188 disallowed_tools: vec![
6189 "shell".to_string(),
6190 " shell ".to_string(),
6191 "mcp_secret_*".to_string(),
6192 ],
6193 })?;
6194 assert_eq!(
6195 restricted.schema_version,
6196 DENY_RULES_AUTOMATION_SCHEMA_VERSION
6197 );
6198 assert_eq!(restricted.disallowed_tools, vec!["shell", "mcp_secret_*"]);
6199
6200 let updated = manager.update_automation(
6201 &restricted.id,
6202 UpdateAutomationRequest {
6203 allow_shell: Some(false),
6204 ..Default::default()
6205 },
6206 )?;
6207 assert_eq!(updated.schema_version, DENY_RULES_AUTOMATION_SCHEMA_VERSION);
6208 assert_eq!(updated.disallowed_tools, vec!["shell", "mcp_secret_*"]);
6209
6210 let auto_path = manager.automation_path(&restricted.id)?;
6211 let mut restricted_disk: serde_json::Value =
6212 serde_json::from_str(&fs::read_to_string(&auto_path)?)?;
6213 assert_eq!(
6214 restricted_disk["schema_version"],
6215 DENY_RULES_AUTOMATION_SCHEMA_VERSION
6216 );
6217 assert_eq!(
6218 restricted_disk["disallowed_tools"],
6219 serde_json::json!(["shell", "mcp_secret_*"])
6220 );
6221 assert_eq!(
6222 manager.get_automation(&restricted.id)?.schema_version,
6223 DENY_RULES_AUTOMATION_SCHEMA_VERSION
6224 );
6225
6226 let mut restricted_run = new_run_record(&restricted.id, Utc::now(), Utc::now());
6227 bind_run_dispatch(&mut restricted_run, &restricted, tempdir.path(), true)?;
6228 assert_eq!(restricted_run.schema_version, DENY_RULES_RUN_SCHEMA_VERSION);
6229 manager.save_run(&restricted_run)?;
6230 let run_path = manager.run_path(&restricted_run)?;
6231 let mut run_disk: serde_json::Value =
6232 serde_json::from_str(&fs::read_to_string(&run_path)?)?;
6233 assert_eq!(run_disk["schema_version"], DENY_RULES_RUN_SCHEMA_VERSION);
6234 assert_eq!(
6235 run_disk["dispatch"]["request"]["disallowed_tools"],
6236 serde_json::json!(["shell", "mcp_secret_*"])
6237 );
6238 assert_eq!(manager.list_runs(&restricted.id, None)?.len(), 1);
6239
6240 run_disk["schema_version"] = serde_json::json!(MAX_SUPPORTED_RUN_SCHEMA_VERSION + 1);
6241 fs::write(&run_path, serde_json::to_string_pretty(&run_disk)?)?;
6242 assert!(
6243 manager
6244 .list_runs(&restricted.id, None)
6245 .unwrap_err()
6246 .to_string()
6247 .contains("newer than supported")
6248 );
6249
6250 restricted_disk["schema_version"] =
6251 serde_json::json!(MAX_SUPPORTED_AUTOMATION_SCHEMA_VERSION + 1);
6252 fs::write(&auto_path, serde_json::to_string_pretty(&restricted_disk)?)?;
6253 assert!(
6254 manager
6255 .get_automation(&restricted.id)
6256 .unwrap_err()
6257 .to_string()
6258 .contains("newer than supported")
6259 );
6260 Ok(())
6261 }
6262
6263 #[tokio::test]
6264 async fn denied_delayed_trigger_uses_v4_and_preserves_deny_rules_when_fired() -> Result<()> {
6265 let tempdir = tempfile::tempdir()?;
6266 let task_dir = tempdir.path().join("tasks");
6267 let task_manager = TaskManager::start_with_executor(
6268 automation_task_config(task_dir.clone()),
6269 std::sync::Arc::new(AutomationNoopExecutor),
6270 )
6271 .await?;
6272 let manager = AutomationManager::open_for_test(tempdir.path().join("automations"))?;
6273
6274 let open = manager.create_trigger(CreateDelayedTriggerRequest {
6275 fire_at: Utc::now() + Duration::hours(1),
6276 message: "open later".to_string(),
6277 workspace: None,
6278 owner_session_id: Some("session-open".to_string()),
6279 parent_trigger_id: None,
6280 destination_thread_id: None,
6281 disallowed_tools: vec![" ".to_string()],
6282 })?;
6283 assert_eq!(open.schema_version, CURRENT_TRIGGER_SCHEMA_VERSION);
6284 assert!(open.disallowed_tools.is_empty());
6285 let open_disk: serde_json::Value = serde_json::from_str(&fs::read_to_string(
6286 manager.trigger_path(&open.trigger_id)?,
6287 )?)?;
6288 assert_eq!(open_disk["schema_version"], CURRENT_TRIGGER_SCHEMA_VERSION);
6289 assert!(open_disk.get("disallowed_tools").is_none());
6290
6291 let mut restricted = manager.create_trigger(CreateDelayedTriggerRequest {
6292 fire_at: Utc::now() + Duration::hours(1),
6293 message: "restricted later".to_string(),
6294 workspace: Some(tempdir.path().to_path_buf()),
6295 owner_session_id: Some("session-deny".to_string()),
6296 parent_trigger_id: None,
6297 destination_thread_id: None,
6298 disallowed_tools: vec!["shell".to_string(), " mcp_secret_* ".to_string()],
6299 })?;
6300 assert_eq!(restricted.schema_version, DENY_RULES_TRIGGER_SCHEMA_VERSION);
6301 assert_eq!(restricted.disallowed_tools, vec!["shell", "mcp_secret_*"]);
6302 restricted.fire_at = Utc::now() - Duration::minutes(1);
6303 manager.save_trigger(&restricted)?;
6304
6305 let trigger_path = manager.trigger_path(&restricted.trigger_id)?;
6306 let initial_disk: serde_json::Value =
6307 serde_json::from_str(&fs::read_to_string(&trigger_path)?)?;
6308 assert_eq!(
6309 initial_disk["schema_version"],
6310 DENY_RULES_TRIGGER_SCHEMA_VERSION
6311 );
6312 assert_eq!(
6313 initial_disk["disallowed_tools"],
6314 serde_json::json!(["shell", "mcp_secret_*"])
6315 );
6316
6317 let shared = Arc::new(Mutex::new(manager));
6318 fire_due_triggers_with(&shared, &task_dir, |claimed| async move {
6319 assert_eq!(claimed.status, DelayedTriggerStatus::Dispatching);
6320 assert_eq!(claimed.schema_version, DENY_RULES_TRIGGER_SCHEMA_VERSION);
6321 assert_eq!(
6322 claimed
6323 .dispatch
6324 .as_ref()
6325 .expect("dispatch")
6326 .request
6327 .disallowed_tools,
6328 vec!["shell", "mcp_secret_*"]
6329 );
6330 anyhow::bail!("pause at dispatching boundary")
6331 })
6332 .await?;
6333
6334 let dispatching_disk: serde_json::Value =
6335 serde_json::from_str(&fs::read_to_string(&trigger_path)?)?;
6336 assert_eq!(dispatching_disk["status"], "dispatching");
6337 assert_eq!(
6338 dispatching_disk["schema_version"],
6339 DENY_RULES_TRIGGER_SCHEMA_VERSION
6340 );
6341 assert_eq!(
6342 dispatching_disk["dispatch"]["request"]["disallowed_tools"],
6343 serde_json::json!(["shell", "mcp_secret_*"])
6344 );
6345
6346 fire_due_triggers_shared(&shared, &task_manager).await?;
6347
6348 let manager = shared.lock().await;
6349 let fired = manager.get_trigger(&restricted.trigger_id)?;
6350 assert_eq!(fired.status, DelayedTriggerStatus::Fired);
6351 assert_eq!(fired.schema_version, DENY_RULES_TRIGGER_SCHEMA_VERSION);
6352 assert_eq!(fired.disallowed_tools, vec!["shell", "mcp_secret_*"]);
6353 assert_eq!(
6354 fired
6355 .dispatch
6356 .as_ref()
6357 .expect("dispatch")
6358 .request
6359 .disallowed_tools,
6360 vec!["shell", "mcp_secret_*"]
6361 );
6362
6363 let task = task_manager
6364 .get_task(fired.task_id.as_deref().expect("fired task id"))
6365 .await?;
6366 assert_eq!(task.schema_version, 5);
6367 assert_eq!(task.disallowed_tools, vec!["shell", "mcp_secret_*"]);
6368
6369 let mut future_disk: serde_json::Value =
6370 serde_json::from_str(&fs::read_to_string(&trigger_path)?)?;
6371 future_disk["schema_version"] = serde_json::json!(MAX_SUPPORTED_TRIGGER_SCHEMA_VERSION + 1);
6372 fs::write(&trigger_path, serde_json::to_string_pretty(&future_disk)?)?;
6373 assert!(
6374 manager
6375 .get_trigger(&restricted.trigger_id)
6376 .unwrap_err()
6377 .to_string()
6378 .contains("newer than supported")
6379 );
6380 let listed = manager.list_triggers(None, None)?;
6381 assert_eq!(listed.len(), 1);
6382 assert_eq!(listed[0].trigger_id, open.trigger_id);
6383
6384 drop(manager);
6385 task_manager.shutdown();
6386 Ok(())
6387 }
6388
6389 fn write_legacy_run_file(manager: &AutomationManager, run: &AutomationRunRecord) {
6390 let dir = manager.runs_dir_for(&run.automation_id).expect("runs dir");
6391 fs::create_dir_all(&dir).expect("create runs dir");
6392 fs::write(
6393 dir.join(format!("{}.json", run.id)),
6394 serde_json::to_string_pretty(run).expect("serialize run"),
6395 )
6396 .expect("write legacy run");
6397 }
6398
6399 fn run_created_at(
6400 automation: &AutomationRecord,
6401 created_at: DateTime<Utc>,
6402 ) -> AutomationRunRecord {
6403 let mut run = queued_run_for(automation);
6404 run.created_at = created_at;
6405 run.scheduled_for = created_at;
6406 run
6407 }
6408
6409 #[test]
6410 fn interrupted_watcher_migration_deduplicates_before_visibility() -> Result<()> {
6411 for suppressed in [false, true] {
6412 let root = tempfile::tempdir()?;
6413 let manager = AutomationManager::open_for_test(root.path().join("automations"))?;
6414 let automation = automation_record_with_settings(None, None, None, None);
6415 let mut run = queued_run_for(&automation);
6416 write_legacy_run_file(&manager, &run);
6417 bind_run_dispatch(&mut run, &automation, root.path(), true)?;
6418 run.status = AutomationRunStatus::Completed;
6419 let dispatch = run.dispatch.as_mut().unwrap();
6420 dispatch.accepted = true;
6421 dispatch.delivery_mode = AutomationDeliveryMode::Watcher;
6422 dispatch.suppress_report = suppressed;
6423 // Persist the post-write/pre-legacy-removal crash boundary.
6424 write_json_atomic(&manager.run_path(&run)?, &run)?;
6425 let ids = std::collections::BTreeSet::from([run.id.clone()]);
6426 for visible in [
6427 manager.list_runs(&automation.id, None)?,
6428 manager.list_runs(&automation.id, Some(1))?,
6429 manager.get_runs_by_ids(&automation.id, &ids)?,
6430 ] {
6431 assert_eq!(visible.len(), usize::from(!suppressed));
6432 if let Some(receipt) = visible.first() {
6433 assert_eq!(receipt.status, AutomationRunStatus::Completed);
6434 assert_eq!(receipt.task_id, run.task_id);
6435 }
6436 }
6437 let durable = manager.list_runs_with_visibility(&automation.id, None, true)?;
6438 assert_eq!(durable.len(), 1);
6439 assert_eq!(durable[0].status, AutomationRunStatus::Completed);
6440 assert_eq!(
6441 durable[0].dispatch.as_ref().unwrap().suppress_report,
6442 suppressed
6443 );
6444 assert!(manager.collect_pending_runs()?.is_empty());
6445 }
6446 Ok(())
6447 }
6448
6449 #[test]
6450 fn save_run_uses_sortable_names_and_migrates_legacy_files() {
6451 let tempdir = tempfile::tempdir().expect("tempdir");
6452 let manager =
6453 AutomationManager::open_for_test(tempdir.path().to_path_buf()).expect("manager");
6454 let automation = automation_record_with_settings(None, None, None, None);
6455 let run = queued_run_for(&automation);
6456
6457 write_legacy_run_file(&manager, &run);
6458 manager.save_run(&run).expect("save run");
6459
6460 let dir = manager.runs_dir_for(&automation.id).expect("runs dir");
6461 let names: Vec<String> = fs::read_dir(&dir)
6462 .expect("read dir")
6463 .map(|entry| {
6464 entry
6465 .expect("entry")
6466 .file_name()
6467 .to_string_lossy()
6468 .into_owned()
6469 })
6470 .collect();
6471 let expected = format!("{}-{}.json", run_file_stamp(run.created_at), run.id);
6472 assert_eq!(names, vec![expected.clone()]);
6473 assert!(has_sortable_run_stem(expected.trim_end_matches(".json")));
6474 // Legacy uuid stems are not mistaken for sortable names.
6475 assert!(!has_sortable_run_stem(&run.id));
6476 }
6477
6478 #[test]
6479 fn finish_scheduled_run_persists_run_when_automation_deleted_mid_enqueue() {
6480 let tempdir = tempfile::tempdir().expect("tempdir");
6481 let manager =
6482 AutomationManager::open_for_test(tempdir.path().to_path_buf()).expect("manager");
6483 let automation = automation_record_with_settings(None, None, None, None);
6484 manager.save_automation(&automation).expect("save");
6485 let run = queued_run_for(&automation);
6486
6487 // Simulate the automation being deleted while the enqueue await ran
6488 // outside the lock. The task already exists in the task manager at
6489 // this point, so the run record must still be persisted — an early
6490 // return here orphans a real running task.
6491 manager.delete_automation(&automation.id).expect("delete");
6492 manager
6493 .finish_scheduled_run(&run, Utc::now())
6494 .expect("finish");
6495
6496 let runs = manager.list_runs(&automation.id, None).expect("list runs");
6497 assert_eq!(
6498 runs.iter().map(|r| r.id.as_str()).collect::<Vec<_>>(),
6499 vec![run.id.as_str()],
6500 "run must be persisted even though its automation was deleted"
6501 );
6502 assert!(
6503 manager.get_automation(&automation.id).is_err(),
6504 "the deleted automation must not be resurrected"
6505 );
6506 }
6507
6508 #[test]
6509 fn once_schedule_fires_once_and_auto_completes() {
6510 let tempdir = tempfile::tempdir().expect("tempdir");
6511 let manager =
6512 AutomationManager::open_for_test(tempdir.path().to_path_buf()).expect("manager");
6513 let due_at = Utc::now() - Duration::minutes(1);
6514 let automation = AutomationRecord {
6515 rrule: due_at
6516 .format("FREQ=ONCE;AT=%Y-%m-%dT%H:%M:%S+00:00")
6517 .to_string(),
6518 next_run_at: Some(due_at),
6519 created_at: due_at - Duration::minutes(5),
6520 updated_at: due_at - Duration::minutes(5),
6521 ..automation_record_with_settings(None, None, None, None)
6522 };
6523 manager
6524 .save_automation(&automation)
6525 .expect("save automation");
6526
6527 let due = manager
6528 .collect_due_runs(Utc::now())
6529 .expect("collect due runs");
6530 assert_eq!(due.len(), 1);
6531 let (observed, proposed) = &due[0];
6532 let run = manager
6533 .claim_scheduled_run(observed, proposed.clone(), tempdir.path())
6534 .expect("claim one-shot occurrence")
6535 .expect("due occurrence admitted");
6536 assert_eq!(run.scheduled_for, due_at);
6537
6538 manager
6539 .finish_scheduled_run(&run, Utc::now())
6540 .expect("finish one-shot run");
6541 let updated = manager
6542 .get_automation(&automation.id)
6543 .expect("updated automation");
6544 assert_eq!(updated.status, AutomationStatus::Paused);
6545 assert_eq!(updated.next_run_at, None);
6546 assert!(
6547 manager
6548 .collect_due_runs(Utc::now() + Duration::hours(1))
6549 .expect("later tick")
6550 .is_empty()
6551 );
6552 }
6553
6554 #[test]
6555 fn get_runs_by_ids_finds_live_runs_past_the_newest_window() {
6556 let tempdir = tempfile::tempdir().expect("tempdir");
6557 let manager =
6558 AutomationManager::open_for_test(tempdir.path().to_path_buf()).expect("manager");
6559 let automation = automation_record_with_settings(None, None, None, None);
6560 let base = Utc::now();
6561
6562 // The OLDEST run is the long-running task; 25 newer runs stack on
6563 // top of it while it is still Running.
6564 let long_running = run_created_at(&automation, base - Duration::minutes(60));
6565 let mut long_running = long_running;
6566 long_running.status = AutomationRunStatus::Running;
6567 long_running.started_at = Some(base - Duration::minutes(60));
6568 manager.save_run(&long_running).expect("save live run");
6569 for i in 0..25 {
6570 let mut newer = run_created_at(&automation, base - Duration::minutes(30 - i as i64));
6571 newer.status = AutomationRunStatus::Completed;
6572 newer.ended_at = Some(base - Duration::minutes(29 - i as i64));
6573 manager.save_run(&newer).expect("save newer settled run");
6574 }
6575
6576 let window = manager
6577 .list_runs(&automation.id, Some(25))
6578 .expect("windowed list");
6579 assert!(
6580 window.iter().all(|run| run.id != long_running.id),
6581 "the live run sits past the newest-25 window"
6582 );
6583
6584 let wanted: std::collections::BTreeSet<String> =
6585 [long_running.id.clone()].into_iter().collect();
6586 let found = manager
6587 .get_runs_by_ids(&automation.id, &wanted)
6588 .expect("re-read live run");
6589 assert_eq!(found.len(), 1, "the run is found wherever it sits");
6590 assert_eq!(found[0].id, long_running.id);
6591 assert_eq!(found[0].status, AutomationRunStatus::Running);
6592 }
6593
6594 #[test]
6595 fn get_runs_by_ids_ignores_non_json_noise() {
6596 let tempdir = tempfile::tempdir().expect("tempdir");
6597 let manager =
6598 AutomationManager::open_for_test(tempdir.path().to_path_buf()).expect("manager");
6599 let automation = automation_record_with_settings(None, None, None, None);
6600 let run = queued_run_for(&automation);
6601 manager.save_run(&run).expect("save json run");
6602
6603 let dir = manager.runs_dir_for(&automation.id).expect("runs dir");
6604 let json = dir
6605 .read_dir()
6606 .expect("list")
6607 .filter_map(|entry| entry.ok())
6608 .map(|entry| entry.path())
6609 .find(|path| path.extension().and_then(|ext| ext.to_str()) == Some("json"))
6610 .expect("json run file");
6611 let stem = json
6612 .file_stem()
6613 .and_then(|stem| stem.to_str())
6614 .expect("stem");
6615 fs::write(dir.join(format!("{stem}.tmp")), "not-json").expect("write tmp noise");
6616 fs::write(dir.join(format!("{stem}.json.bak")), "not-json").expect("write bak noise");
6617
6618 let wanted: std::collections::BTreeSet<String> = [run.id.clone()].into_iter().collect();
6619 let found = manager
6620 .get_runs_by_ids(&automation.id, &wanted)
6621 .expect("noise must not poison the re-read");
6622 assert_eq!(found.len(), 1);
6623 assert_eq!(found[0].id, run.id);
6624 }
6625
6626 #[test]
6627 fn list_runs_merges_legacy_and_sortable_files_newest_first() {
6628 let tempdir = tempfile::tempdir().expect("tempdir");
6629 let manager =
6630 AutomationManager::open_for_test(tempdir.path().to_path_buf()).expect("manager");
6631 let automation = automation_record_with_settings(None, None, None, None);
6632 let base = Utc::now();
6633
6634 // Legacy files sit at both ends of the timeline to prove the merge is
6635 // by created_at, not by file-name era.
6636 let legacy_oldest = run_created_at(&automation, base - Duration::minutes(30));
6637 let legacy_newest = run_created_at(&automation, base + Duration::minutes(30));
6638 write_legacy_run_file(&manager, &legacy_oldest);
6639 write_legacy_run_file(&manager, &legacy_newest);
6640
6641 let sortable_old = run_created_at(&automation, base - Duration::minutes(20));
6642 let sortable_new = run_created_at(&automation, base + Duration::minutes(20));
6643 manager.save_run(&sortable_old).expect("save old");
6644 manager.save_run(&sortable_new).expect("save new");
6645
6646 let all = manager.list_runs(&automation.id, None).expect("list all");
6647 let ids: Vec<&str> = all.iter().map(|run| run.id.as_str()).collect();
6648 assert_eq!(
6649 ids,
6650 vec![
6651 legacy_newest.id.as_str(),
6652 sortable_new.id.as_str(),
6653 sortable_old.id.as_str(),
6654 legacy_oldest.id.as_str(),
6655 ]
6656 );
6657
6658 let top_two = manager.list_runs(&automation.id, Some(2)).expect("list 2");
6659 let top_ids: Vec<&str> = top_two.iter().map(|run| run.id.as_str()).collect();
6660 assert_eq!(
6661 top_ids,
6662 vec![legacy_newest.id.as_str(), sortable_new.id.as_str()]
6663 );
6664 }
6665
6666 #[test]
6667 fn list_runs_with_limit_skips_older_sortable_files_entirely() {
6668 let tempdir = tempfile::tempdir().expect("tempdir");
6669 let manager =
6670 AutomationManager::open_for_test(tempdir.path().to_path_buf()).expect("manager");
6671 let automation = automation_record_with_settings(None, None, None, None);
6672 let base = Utc::now();
6673
6674 let newest = run_created_at(&automation, base);
6675 manager.save_run(&newest).expect("save newest");
6676
6677 // A corrupt sortable-named file older than the newest run: bounded
6678 // listing must never open it, while an unbounded listing fails.
6679 let dir = manager.runs_dir_for(&automation.id).expect("runs dir");
6680 let stale_stamp = run_file_stamp(base - Duration::minutes(5));
6681 fs::write(
6682 dir.join(format!("{stale_stamp}-{}.json", Uuid::new_v4())),
6683 "{ not json",
6684 )
6685 .expect("write corrupt run");
6686
6687 let bounded = manager
6688 .list_runs(&automation.id, Some(1))
6689 .expect("bounded list must not read files beyond the limit");
6690 assert_eq!(bounded.len(), 1);
6691 assert_eq!(bounded[0].id, newest.id);
6692
6693 assert!(manager.list_runs(&automation.id, None).is_err());
6694 }
6695
6696 #[tokio::test]
6697 async fn list_automations_completes_during_slow_enqueue() {
6698 let tempdir = tempfile::tempdir().expect("tempdir");
6699 let manager =
6700 AutomationManager::open_for_test(tempdir.path().to_path_buf()).expect("manager");
6701 let created = manager
6702 .create_automation(CreateAutomationRequest {
6703 destination_thread_id: None,
6704 name: "Slow enqueue".to_string(),
6705 prompt: "prompt".to_string(),
6706 rrule: "FREQ=HOURLY;INTERVAL=1".to_string(),
6707 cwds: Vec::new(),
6708 model: None,
6709 model_provider: None,
6710 model_provider_id: None,
6711 mode: None,
6712 allow_shell: None,
6713 trust_mode: None,
6714 auto_approve: None,
6715 delivery_mode: None,
6716 status: Some(AutomationStatus::Active),
6717 disallowed_tools: Vec::new(),
6718 })
6719 .expect("create");
6720 let shared: SharedAutomationManager = Arc::new(Mutex::new(manager));
6721
6722 let (entered_tx, entered_rx) = tokio::sync::oneshot::channel::<()>();
6723 let (release_tx, release_rx) = tokio::sync::oneshot::channel::<()>();
6724
6725 let run_task = tokio::spawn({
6726 let shared = Arc::clone(&shared);
6727 let automation_id = created.id.clone();
6728 let task_data_dir = tempdir.path().to_path_buf();
6729 async move {
6730 run_now_with(
6731 &shared,
6732 &automation_id,
6733 &task_data_dir,
6734 move |_, mut run| async move {
6735 // Delayed task-manager stub: stall the enqueue await until
6736 // the test has proven the manager mutex is free.
6737 let _ = entered_tx.send(());
6738 let _ = release_rx.await;
6739 run.status = AutomationRunStatus::Failed;
6740 run.ended_at = Some(Utc::now());
6741 run.error = Some("stubbed enqueue".to_string());
6742 run
6743 },
6744 )
6745 .await
6746 }
6747 });
6748
6749 entered_rx.await.expect("enqueue phase entered");
6750
6751 let listed = tokio::time::timeout(std::time::Duration::from_secs(2), async {
6752 shared.lock().await.list_automations()
6753 })
6754 .await
6755 .expect("list_automations must not block behind a slow enqueue")
6756 .expect("list automations");
6757 assert_eq!(listed.len(), 1);
6758
6759 release_tx.send(()).expect("release stub");
6760 let run = run_task.await.expect("join").expect("run now");
6761 assert!(matches!(run.status, AutomationRunStatus::Failed));
6762
6763 // The final run state was persisted after the lock was reacquired.
6764 let manager = shared.lock().await;
6765 let runs = manager.list_runs(&created.id, None).expect("list runs");
6766 assert_eq!(runs.len(), 1);
6767 assert_eq!(runs[0].id, run.id);
6768 assert!(matches!(runs[0].status, AutomationRunStatus::Failed));
6769 let automation = manager.get_automation(&created.id).expect("automation");
6770 assert!(automation.last_run_at.is_some());
6771 }
6772
6773 #[tokio::test]
6774 async fn watcher_noop_completion_hides_but_retains_consumed_occurrence() -> Result<()> {
6775 let tempdir = tempfile::tempdir().expect("tempdir");
6776 let task_manager = TaskManager::start_with_executor(
6777 automation_task_config(tempdir.path().join("tasks")),
6778 std::sync::Arc::new(AutomationWatcherNoopExecutor),
6779 )
6780 .await?;
6781 let mut automation = automation_record_with_settings(None, None, None, None);
6782 automation.delivery_mode = Some(AutomationDeliveryMode::Watcher);
6783 automation.next_run_at = Some(Utc::now() - Duration::seconds(1));
6784 let manager =
6785 AutomationManager::open_for_test(tempdir.path().join("automations")).expect("manager");
6786 manager
6787 .save_automation(&automation)
6788 .expect("save automation");
6789 let shared: SharedAutomationManager = Arc::new(Mutex::new(manager));
6790
6791 scheduler_tick_shared(&shared, &task_manager).await?;
6792 let initial = shared
6793 .lock()
6794 .await
6795 .list_runs_with_visibility(&automation.id, None, true)?;
6796 assert_eq!(initial.len(), 1);
6797 let bound_id = initial[0]
6798 .task_id
6799 .as_deref()
6800 .context("watcher task binding")?;
6801 let completed = crate::task_manager::wait_for_terminal_state(
6802 &task_manager,
6803 bound_id,
6804 std::time::Duration::from_secs(5),
6805 )
6806 .await?;
6807 assert_eq!(completed.status, TaskStatus::Completed);
6808 reconcile_run_statuses_shared(&shared, &task_manager).await?;
6809
6810 let manager = shared.lock().await;
6811 assert!(
6812 manager.list_runs(&automation.id, None)?.is_empty(),
6813 "watcher no-op must not leave a phantom run row"
6814 );
6815 let durable = manager.list_runs_with_visibility(&automation.id, None, true)?;
6816 assert_eq!(durable.len(), 1);
6817 assert_eq!(durable[0].status, AutomationRunStatus::Completed);
6818 assert!(durable[0].dispatch.as_ref().unwrap().suppress_report);
6819 let mut updated = manager.get_automation(&automation.id)?;
6820 assert!(
6821 updated.next_run_at.is_some(),
6822 "watcher should keep scheduling"
6823 );
6824 assert_eq!(
6825 updated.last_run_at, None,
6826 "no-op checks are not reportable runs"
6827 );
6828 // Revisit the consumed slot after a torn schedule write. A hidden
6829 // receipt still owns its occurrence and must prevent another task.
6830 updated.next_run_at = Some(durable[0].scheduled_for);
6831 manager.save_automation(&updated)?;
6832 drop(manager);
6833 scheduler_tick_shared(&shared, &task_manager).await?;
6834 assert_eq!(task_manager.list_tasks(None).await?.len(), 1);
6835 assert!(
6836 shared
6837 .lock()
6838 .await
6839 .list_runs(&automation.id, None)?
6840 .is_empty()
6841 );
6842 task_manager.shutdown();
6843 Ok(())
6844 }
6845
6846 #[test]
6847 fn default_automations_dir_honors_codewhale_home_as_hard_override() {
6848 let _lock = crate::test_support::lock_test_env();
6849 let tmp = tempfile::TempDir::new().unwrap();
6850 // SAFETY: serialised by lock_test_env.
6851 unsafe {
6852 std::env::remove_var("DEEPSEEK_AUTOMATIONS_DIR");
6853 std::env::set_var("CODEWHALE_HOME", tmp.path());
6854 }
6855 // $CODEWHALE_HOME IS the home dir (no ".codewhale" appended); the
6856 // legacy ~/.deepseek fallback is bypassed entirely.
6857 assert_eq!(default_automations_dir(), tmp.path().join("automations"));
6858 // SAFETY: cleanup under the same lock.
6859 unsafe {
6860 std::env::remove_var("CODEWHALE_HOME");
6861 }
6862 }
6863
6864 #[test]
6865 fn default_automations_dir_prefers_deepseek_automations_dir_over_codewhale_home() {
6866 let _lock = crate::test_support::lock_test_env();
6867 let tmp = tempfile::TempDir::new().unwrap();
6868 // SAFETY: serialised by lock_test_env.
6869 unsafe {
6870 std::env::set_var("DEEPSEEK_AUTOMATIONS_DIR", tmp.path());
6871 std::env::set_var("CODEWHALE_HOME", "/should/not/be/used");
6872 }
6873 // The most-specific override wins over the base-data-dir override.
6874 assert_eq!(default_automations_dir(), tmp.path());
6875 // SAFETY: cleanup under the same lock.
6876 unsafe {
6877 std::env::remove_var("DEEPSEEK_AUTOMATIONS_DIR");
6878 std::env::remove_var("CODEWHALE_HOME");
6879 }
6880 }
6881 mod elevated;
6882 mod ownership;
6883 mod recovery;
6884
6885 /// #6162: the projection's Canceled branch must record why. A cooperative
6886 /// cancel arrives with no error of its own and takes the derived text; a
6887 /// task that already carries the task manager's receipt keeps it; a legacy
6888 /// record with neither degrades to no detail instead of inventing one.
6889 fn canceled_task_record(
6890 error: Option<&str>,
6891 terminal_reason: Option<&str>,
6892 ) -> crate::task_manager::TaskRecord {
6893 serde_json::from_value(serde_json::json!({
6894 "id": "task_canceled",
6895 "prompt": "nightly report",
6896 "model": "deepseek-v4-pro",
6897 "workspace": "/tmp/automation-fixture",
6898 "mode": "agent",
6899 "allow_shell": false,
6900 "trust_mode": false,
6901 "status": "canceled",
6902 "created_at": "2026-09-14T10:00:00Z",
6903 "started_at": "2026-09-14T10:00:01Z",
6904 "ended_at": "2026-09-14T10:00:05Z",
6905 "duration_ms": 4000,
6906 "result_summary": null,
6907 "result_detail_path": null,
6908 "error": error,
6909 "terminal_reason": terminal_reason,
6910 "tool_calls": [],
6911 "timeline": [],
6912 }))
6913 .expect("a canceled task record fixture")
6914 }
6915
6916 #[test]
6917 fn a_cooperatively_canceled_task_names_the_cancellation_on_the_run() {
6918 let mut run = new_run_record("auto_1", Utc::now(), Utc::now());
6919 run.status = AutomationRunStatus::Running;
6920 let task = canceled_task_record(None, Some("canceled"));
6921 assert!(apply_task_status(&mut run, &task));
6922 assert_eq!(run.status, AutomationRunStatus::Canceled);
6923 assert_eq!(run.error.as_deref(), Some("canceled by request"));
6924 assert_eq!(run.started_at, task.started_at);
6925 assert_eq!(run.ended_at, task.ended_at);
6926 }
6927
6928 #[test]
6929 fn a_canceled_task_with_its_own_error_keeps_that_error_on_the_run() {
6930 let mut run = new_run_record("auto_1", Utc::now(), Utc::now());
6931 run.status = AutomationRunStatus::Running;
6932 let task = canceled_task_record(
6933 Some("Task canceled because the task manager shut down"),
6934 Some("shutdown"),
6935 );
6936 assert!(apply_task_status(&mut run, &task));
6937 assert_eq!(run.status, AutomationRunStatus::Canceled);
6938 assert_eq!(
6939 run.error.as_deref(),
6940 Some("Task canceled because the task manager shut down")
6941 );
6942 }
6943
6944 #[test]
6945 fn a_legacy_canceled_task_without_a_reason_records_no_detail() {
6946 let mut run = new_run_record("auto_1", Utc::now(), Utc::now());
6947 run.status = AutomationRunStatus::Running;
6948 let task = canceled_task_record(None, None);
6949 assert!(apply_task_status(&mut run, &task));
6950 assert_eq!(run.status, AutomationRunStatus::Canceled);
6951 assert_eq!(run.error, None);
6952 }
6953
6954 #[tokio::test]
6955 async fn trigger_wait_duration_clamps_and_cancel_wakes_notifier() -> Result<()> {
6956 let tempdir = tempfile::tempdir()?;
6957 let mut manager = AutomationManager::open_for_test(tempdir.path().to_path_buf())?;
6958 let max_wait = std::time::Duration::from_secs(60);
6959 let now = Utc::now();
6960 assert_eq!(manager.trigger_wait_duration(now, max_wait)?, max_wait);
6961
6962 let far = manager.create_trigger(CreateDelayedTriggerRequest {
6963 destination_thread_id: None,
6964 fire_at: now + Duration::seconds(120),
6965 message: "far".to_string(),
6966 workspace: None,
6967 owner_session_id: Some("session-a".to_string()),
6968 parent_trigger_id: None,
6969 disallowed_tools: Vec::new(),
6970 })?;
6971 assert_eq!(manager.trigger_wait_duration(now, max_wait)?, max_wait);
6972
6973 let wakeup = manager.trigger_wakeup();
6974 assert!(
6975 tokio::time::timeout(std::time::Duration::from_millis(100), wakeup.notified())
6976 .await
6977 .is_ok()
6978 );
6979
6980 let now = Utc::now();
6981 let subminute = manager.create_trigger(CreateDelayedTriggerRequest {
6982 destination_thread_id: None,
6983 fire_at: now + Duration::seconds(2),
6984 message: "subminute".to_string(),
6985 workspace: None,
6986 owner_session_id: Some("session-a".to_string()),
6987 parent_trigger_id: None,
6988 disallowed_tools: Vec::new(),
6989 })?;
6990 assert!(
6991 tokio::time::timeout(std::time::Duration::from_millis(100), wakeup.notified())
6992 .await
6993 .is_ok()
6994 );
6995 let sub_wait = manager.trigger_wait_duration(now, max_wait)?;
6996 assert!(sub_wait <= std::time::Duration::from_secs(2));
6997 assert!(sub_wait > std::time::Duration::ZERO);
6998
6999 let mut past = manager.create_trigger(CreateDelayedTriggerRequest {
7000 destination_thread_id: None,
7001 fire_at: now + Duration::seconds(30),
7002 message: "past".to_string(),
7003 workspace: None,
7004 owner_session_id: Some("session-a".to_string()),
7005 parent_trigger_id: None,
7006 disallowed_tools: Vec::new(),
7007 })?;
7008 assert!(
7009 tokio::time::timeout(std::time::Duration::from_millis(100), wakeup.notified())
7010 .await
7011 .is_ok()
7012 );
7013 past.fire_at = now - Duration::seconds(5);
7014 manager.save_trigger(&past)?;
7015 assert_eq!(
7016 manager.trigger_wait_duration(now, max_wait)?,
7017 std::time::Duration::ZERO
7018 );
7019 manager.cancel_trigger(&past.trigger_id)?;
7020 assert!(
7021 tokio::time::timeout(std::time::Duration::from_millis(100), wakeup.notified())
7022 .await
7023 .is_ok()
7024 );
7025
7026 let notified = tokio::spawn({
7027 let wakeup = Arc::clone(&wakeup);
7028 async move { wakeup.notified().await }
7029 });
7030 tokio::task::yield_now().await;
7031 manager.cancel_trigger(&subminute.trigger_id)?;
7032 assert!(
7033 tokio::time::timeout(std::time::Duration::from_millis(100), notified)
7034 .await
7035 .is_ok()
7036 );
7037 assert_eq!(manager.trigger_wait_duration(now, max_wait)?, max_wait);
7038
7039 let now = Utc::now();
7040 let mut ownerless = manager.create_trigger(CreateDelayedTriggerRequest {
7041 destination_thread_id: None,
7042 fire_at: now + Duration::seconds(1),
7043 message: "ownerless".to_string(),
7044 workspace: None,
7045 owner_session_id: None,
7046 parent_trigger_id: None,
7047 disallowed_tools: Vec::new(),
7048 })?;
7049 ownerless.fire_at = now - Duration::seconds(1);
7050 manager.save_trigger(&ownerless)?;
7051 manager.execution_scope = Some("other-scope".to_string());
7052 let now = Utc::now();
7053 let mut foreign = manager.create_trigger(CreateDelayedTriggerRequest {
7054 destination_thread_id: None,
7055 fire_at: now + Duration::seconds(1),
7056 message: "foreign".to_string(),
7057 workspace: None,
7058 owner_session_id: Some("session-b".to_string()),
7059 parent_trigger_id: None,
7060 disallowed_tools: Vec::new(),
7061 })?;
7062 foreign.fire_at = now - Duration::seconds(1);
7063 manager.save_trigger(&foreign)?;
7064 manager.execution_scope = far.execution_scope.clone();
7065 assert_eq!(manager.trigger_wait_duration(now, max_wait)?, max_wait);
7066 Ok(())
7067 }
7068
7069 #[tokio::test]
7070 async fn scheduler_wakes_for_subminute_trigger_before_its_tick() -> Result<()> {
7071 let tempdir = tempfile::tempdir()?;
7072 let task_manager = TaskManager::start_with_executor(
7073 automation_task_config(tempdir.path().join("tasks")),
7074 std::sync::Arc::new(AutomationNoopExecutor),
7075 )
7076 .await?;
7077 let mut manager = AutomationManager::open(tempdir.path().join("automations"))?;
7078 manager.bind_task_manager(&task_manager)?;
7079 let shared = Arc::new(Mutex::new(manager));
7080 let cancel = CancellationToken::new();
7081 let handle = spawn_scheduler(
7082 Arc::clone(&shared),
7083 Arc::clone(&task_manager),
7084 cancel.clone(),
7085 AutomationSchedulerConfig {
7086 tick_interval_secs: 60,
7087 },
7088 );
7089
7090 tokio::time::sleep(std::time::Duration::from_millis(50)).await;
7091 let start = std::time::Instant::now();
7092 let trigger = {
7093 let guard = shared.lock().await;
7094 guard.create_trigger(CreateDelayedTriggerRequest {
7095 destination_thread_id: None,
7096 fire_at: Utc::now() + Duration::milliseconds(60),
7097 message: "sub-second notify wakeup".to_string(),
7098 workspace: None,
7099 owner_session_id: Some("session-notify".to_string()),
7100 parent_trigger_id: None,
7101 disallowed_tools: Vec::new(),
7102 })?
7103 };
7104
7105 let mut fired = None;
7106 while start.elapsed() < std::time::Duration::from_secs(10) {
7107 tokio::time::sleep(std::time::Duration::from_millis(10)).await;
7108 let current = shared.lock().await.get_trigger(&trigger.trigger_id)?;
7109 if current.status == DelayedTriggerStatus::Fired {
7110 fired = Some(current);
7111 break;
7112 }
7113 }
7114 let elapsed = start.elapsed();
7115
7116 cancel.cancel();
7117 let _ = tokio::time::timeout(std::time::Duration::from_secs(2), handle).await;
7118 task_manager.shutdown();
7119
7120 let fired = fired.expect("sub-minute trigger must fire via Notify before the 60s tick");
7121 assert!(
7122 elapsed < std::time::Duration::from_secs(10),
7123 "expected wakeup and fire well before the 60s tick, took {elapsed:?}"
7124 );
7125 assert!(fired.task_id.is_some());
7126 Ok(())
7127 }
7128 }
7129
7129 lines RUST