zeph-scheduler 0.22.1

Cron-based periodic task scheduler with SQLite persistence for Zeph
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

use std::borrow::Cow;
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::str::FromStr;

use chrono::{DateTime, Utc};
use cron::Schedule as CronSchedule;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::error::SchedulerError;

/// Normalise a cron expression to the 6-field format required by the `cron` crate.
///
/// Standard 5-field expressions (`min hour day month weekday`) are prepended with `"0 "` to
/// default seconds to zero. 6-field expressions are passed through unchanged. Any other field
/// count is also passed through unchanged and will produce an error from the `cron` crate at
/// parse time.
///
/// # Examples
///
/// ```
/// use zeph_scheduler::normalize_cron_expr;
///
/// // 5-field: seconds are defaulted to 0.
/// assert_eq!(normalize_cron_expr("*/5 * * * *").as_ref(), "0 */5 * * * *");
///
/// // 6-field: passed through unchanged.
/// assert_eq!(normalize_cron_expr("0 */5 * * * *").as_ref(), "0 */5 * * * *");
/// ```
#[must_use]
pub fn normalize_cron_expr(expr: &str) -> Cow<'_, str> {
    if expr.split_whitespace().count() == 5 {
        Cow::Owned(format!("0 {expr}"))
    } else {
        Cow::Borrowed(expr)
    }
}

/// A validated cron expression that can only be constructed from a well-formed cron string.
///
/// `CronExpr` guarantees that the wrapped string is accepted by both [`normalize_cron_expr`]
/// and `cron::Schedule::from_str`. Constructing one via [`TryFrom`] validates the expression
/// eagerly, so any code that holds a `CronExpr` can assume the schedule is syntactically valid.
///
/// The raw `String` stored in the database column is not changed — `CronExpr` is a type-level
/// wrapper that enforces validity at the boundary where cron strings enter the system.
///
/// # Examples
///
/// ```
/// use zeph_scheduler::CronExpr;
///
/// // Valid 6-field expression.
/// let expr: CronExpr = "0 0 3 * * *".try_into().expect("valid cron");
/// assert_eq!(expr.as_ref(), "0 0 3 * * *");
///
/// // Valid 5-field expression (auto-normalised to 6-field).
/// let expr: CronExpr = "0 3 * * *".try_into().expect("valid 5-field cron");
/// assert_eq!(expr.as_ref(), "0 0 3 * * *");
///
/// // Invalid expression returns an error.
/// assert!(CronExpr::try_from("not a cron").is_err());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CronExpr(String);

impl CronExpr {
    /// Return the validated cron expression string.
    ///
    /// The returned string is always in the normalised 6-field form accepted by the `cron` crate.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl AsRef<str> for CronExpr {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for CronExpr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl TryFrom<String> for CronExpr {
    type Error = SchedulerError;

    /// Validate and normalise a cron expression string.
    ///
    /// Accepts both 5-field and 6-field expressions. Returns [`SchedulerError::InvalidCron`]
    /// if the expression is not accepted by the `cron` parser after normalisation.
    fn try_from(s: String) -> Result<Self, Self::Error> {
        let normalized = normalize_cron_expr(&s);
        CronSchedule::from_str(&normalized)
            .map_err(|e| SchedulerError::InvalidCron(format!("{s}: {e}")))?;
        // Store the normalised form so the string round-trips consistently.
        Ok(Self(normalized.into_owned()))
    }
}

impl TryFrom<&str> for CronExpr {
    type Error = SchedulerError;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        Self::try_from(s.to_owned())
    }
}

impl Serialize for CronExpr {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.0)
    }
}

impl<'de> Deserialize<'de> for CronExpr {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        Self::try_from(s).map_err(serde::de::Error::custom)
    }
}

/// Trust level assigned to a scheduled task, used by the RTW-A re-entry defense.
///
/// Provenance determines how strictly the tick-fence and injection-detection
/// mechanisms are applied when a task is dispatched.
///
/// # Invariants
///
/// - `Static` tasks have their config set at binary startup and are never
///   overwritten by DB writes between ticks.
/// - `External` tasks originate from out-of-process writes (CLI, direct SQL)
///   and are subject to the full quarantine and injection-detection pipeline.
/// - `UserAdded` tasks are user-initiated via the control channel and
///   receive a single-tick quarantine before their prompt enters the LLM.
///
/// # Examples
///
/// ```
/// use zeph_scheduler::TaskProvenance;
///
/// assert_eq!(TaskProvenance::Static.as_str(), "static");
/// assert_eq!(TaskProvenance::from_provenance_str("external"), TaskProvenance::External);
/// assert_eq!(TaskProvenance::from_provenance_str("unknown_value"), TaskProvenance::External);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum TaskProvenance {
    /// Registered at binary startup via [`crate::Scheduler::add_task`] — config is immutable.
    Static,
    /// Added via the runtime control channel (e.g. CLI `zeph schedule add`) — user-originated.
    UserAdded,
    /// Loaded from the DB on hydration or written by an external process — untrusted.
    External,
}

impl TaskProvenance {
    /// Return the stable persistence string for this provenance level.
    ///
    /// # Examples
    ///
    /// ```
    /// use zeph_scheduler::TaskProvenance;
    ///
    /// assert_eq!(TaskProvenance::Static.as_str(), "static");
    /// assert_eq!(TaskProvenance::UserAdded.as_str(), "user_added");
    /// assert_eq!(TaskProvenance::External.as_str(), "external");
    /// ```
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Static => "static",
            Self::UserAdded => "user_added",
            Self::External => "external",
        }
    }

    /// Parse a provenance string from the database.
    ///
    /// Unknown strings default to [`TaskProvenance::External`] — the most restrictive
    /// level — so future schema additions degrade safely.
    ///
    /// # Examples
    ///
    /// ```
    /// use zeph_scheduler::TaskProvenance;
    ///
    /// assert_eq!(TaskProvenance::from_provenance_str("static"), TaskProvenance::Static);
    /// assert_eq!(TaskProvenance::from_provenance_str("user_added"), TaskProvenance::UserAdded);
    /// assert_eq!(TaskProvenance::from_provenance_str("external"), TaskProvenance::External);
    /// // Unknown values fall back to External (most restrictive).
    /// assert_eq!(TaskProvenance::from_provenance_str("hydrated"), TaskProvenance::External);
    /// ```
    #[must_use]
    pub fn from_provenance_str(s: &str) -> Self {
        match s {
            "static" => Self::Static,
            "user_added" => Self::UserAdded,
            _ => Self::External,
        }
    }

    /// Returns `true` if this task originated from a potentially untrusted external source.
    ///
    /// # Examples
    ///
    /// ```
    /// use zeph_scheduler::TaskProvenance;
    ///
    /// assert!(TaskProvenance::External.is_external());
    /// assert!(!TaskProvenance::Static.is_external());
    /// assert!(!TaskProvenance::UserAdded.is_external());
    /// ```
    #[must_use]
    pub fn is_external(&self) -> bool {
        matches!(self, Self::External)
    }
}

/// Identifies what type of work a scheduled task performs.
///
/// Built-in variants map to well-known agent subsystems. [`TaskKind::Custom`]
/// carries an arbitrary string so callers can define their own task kinds without
/// modifying this enum.
///
/// # Persistence
///
/// Each variant serialises to a stable `snake_case` string via [`TaskKind::as_str`]
/// and deserialises via [`TaskKind::from_str_kind`]. These strings are stored in
/// the `kind` column of the `scheduled_jobs` table.
///
/// # Examples
///
/// ```
/// use zeph_scheduler::TaskKind;
///
/// assert_eq!(TaskKind::HealthCheck.as_str(), "health_check");
/// assert_eq!(TaskKind::from_str_kind("memory_cleanup"), TaskKind::MemoryCleanup);
/// assert_eq!(TaskKind::from_str_kind("my_custom"), TaskKind::Custom("my_custom".into()));
/// ```
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TaskKind {
    /// Triggers the memory subsystem's cleanup / compaction routine.
    MemoryCleanup,
    /// Reloads skills from the skill registry.
    SkillRefresh,
    /// Runs a liveness or readiness probe for the agent.
    HealthCheck,
    /// Checks the GitHub releases API for a newer Zeph version.
    UpdateCheck,
    /// Runs an experiment task (used by `zeph-experiments`).
    Experiment,
    /// An application-defined task kind. The string is the persistence key.
    Custom(String),
}

impl TaskKind {
    /// Parse a task kind from its persistence string.
    ///
    /// Unknown strings are wrapped in [`TaskKind::Custom`] rather than returning
    /// an error, so new built-in variants added in future versions do not break
    /// existing stored jobs loaded with an older build.
    ///
    /// # Examples
    ///
    /// ```
    /// use zeph_scheduler::TaskKind;
    ///
    /// assert_eq!(TaskKind::from_str_kind("health_check"), TaskKind::HealthCheck);
    /// assert_eq!(TaskKind::from_str_kind("unknown"), TaskKind::Custom("unknown".into()));
    /// ```
    #[must_use]
    pub fn from_str_kind(s: &str) -> Self {
        match s {
            "memory_cleanup" => Self::MemoryCleanup,
            "skill_refresh" => Self::SkillRefresh,
            "health_check" => Self::HealthCheck,
            "update_check" => Self::UpdateCheck,
            "experiment" => Self::Experiment,
            other => Self::Custom(other.to_owned()),
        }
    }

    /// Return the stable string key used for database persistence.
    ///
    /// # Examples
    ///
    /// ```
    /// use zeph_scheduler::TaskKind;
    ///
    /// assert_eq!(TaskKind::SkillRefresh.as_str(), "skill_refresh");
    /// assert_eq!(TaskKind::Custom("my_job".into()).as_str(), "my_job");
    /// ```
    #[must_use]
    pub fn as_str(&self) -> &str {
        match self {
            Self::MemoryCleanup => "memory_cleanup",
            Self::SkillRefresh => "skill_refresh",
            Self::HealthCheck => "health_check",
            Self::UpdateCheck => "update_check",
            Self::Experiment => "experiment",
            Self::Custom(s) => s,
        }
    }
}

/// Execution mode for a scheduled task.
///
/// Determines how the scheduler decides when to run a task and what to do after it
/// completes:
///
/// - [`TaskMode::Periodic`] re-computes `next_run` from the cron schedule after
///   each successful execution and never removes the task from memory.
/// - [`TaskMode::OneShot`] fires once when `now >= run_at` and then removes the
///   task from the in-memory task list and marks it `done` in the store.
#[non_exhaustive]
pub enum TaskMode {
    /// Run on a repeating cron schedule.
    Periodic {
        /// Parsed cron schedule that drives `next_run` computation.
        schedule: Box<CronSchedule>,
    },
    /// Run once at the specified UTC timestamp.
    OneShot {
        /// The earliest UTC time at which the task should execute.
        run_at: DateTime<Utc>,
    },
}

/// Descriptor sent over the control channel to register tasks at runtime.
///
/// Send a `SchedulerMessage::Add` wrapping a boxed `TaskDescriptor` to add a
/// new task (or replace an existing one with the same name) without stopping the
/// scheduler loop.
pub struct TaskDescriptor {
    /// Unique name for the task. Replaces any existing task with the same name.
    pub name: String,
    /// Execution mode (periodic or one-shot).
    pub mode: TaskMode,
    /// The category of work this task performs.
    pub kind: TaskKind,
    /// Arbitrary JSON configuration forwarded to the [`TaskHandler`] at execution time.
    pub config: serde_json::Value,
    /// Trust level for RTW-A re-entry defense.
    ///
    /// Tasks sent via the runtime channel default to [`TaskProvenance::UserAdded`].
    pub provenance: TaskProvenance,
}

/// A task held in memory by the [`crate::Scheduler`].
///
/// Use [`ScheduledTask::new`] / [`ScheduledTask::periodic`] for cron-based tasks
/// and [`ScheduledTask::oneshot`] for tasks that run at a fixed point in time.
///
/// # Examples
///
/// ```
/// use zeph_scheduler::{ScheduledTask, TaskKind};
///
/// let task = ScheduledTask::new(
///     "daily-cleanup",
///     "0 3 * * *",           // every day at 03:00 UTC (5-field cron)
///     TaskKind::MemoryCleanup,
///     serde_json::Value::Null,
/// )
/// .expect("valid cron expression");
///
/// assert_eq!(task.task_mode_str(), "periodic");
/// assert!(task.cron_schedule().is_some());
/// ```
pub struct ScheduledTask {
    /// Unique task name used as the primary key in the job store.
    pub name: String,
    /// Execution mode (periodic or one-shot).
    pub mode: TaskMode,
    /// The category of work this task performs.
    pub kind: TaskKind,
    /// Arbitrary JSON configuration forwarded to the [`TaskHandler`] at execution time.
    pub config: serde_json::Value,
    /// Trust level for RTW-A re-entry defense.
    pub provenance: TaskProvenance,
}

impl ScheduledTask {
    /// Create a new periodic task from a cron expression string.
    ///
    /// The resulting task has [`TaskProvenance::Static`] provenance.
    ///
    /// # Errors
    ///
    /// Returns `SchedulerError::InvalidCron` if the expression is not valid.
    pub fn new(
        name: impl Into<String>,
        cron_expr: &str,
        kind: TaskKind,
        config: serde_json::Value,
    ) -> Result<Self, SchedulerError> {
        Self::periodic(name, cron_expr, kind, config)
    }

    /// Create a periodic task from a cron expression.
    ///
    /// The resulting task has [`TaskProvenance::Static`] provenance. To create a task with
    /// different provenance, use [`ScheduledTask::periodic_with_provenance`].
    ///
    /// # Errors
    ///
    /// Returns `SchedulerError::InvalidCron` if the expression is not valid.
    pub fn periodic(
        name: impl Into<String>,
        cron_expr: &str,
        kind: TaskKind,
        config: serde_json::Value,
    ) -> Result<Self, SchedulerError> {
        Self::periodic_with_provenance(name, cron_expr, kind, config, TaskProvenance::Static)
    }

    /// Create a periodic task from a cron expression with explicit provenance.
    ///
    /// # Errors
    ///
    /// Returns `SchedulerError::InvalidCron` if the expression is not valid.
    pub fn periodic_with_provenance(
        name: impl Into<String>,
        cron_expr: &str,
        kind: TaskKind,
        config: serde_json::Value,
        provenance: TaskProvenance,
    ) -> Result<Self, SchedulerError> {
        let normalized = normalize_cron_expr(cron_expr);
        let schedule = CronSchedule::from_str(&normalized)
            .map_err(|e| SchedulerError::InvalidCron(format!("{cron_expr}: {e}")))?;
        Ok(Self {
            name: name.into(),
            mode: TaskMode::Periodic {
                schedule: Box::new(schedule),
            },
            kind,
            config,
            provenance,
        })
    }

    /// Create a one-shot task that runs at a specific point in time.
    ///
    /// The resulting task has [`TaskProvenance::Static`] provenance.
    #[must_use]
    pub fn oneshot(
        name: impl Into<String>,
        run_at: DateTime<Utc>,
        kind: TaskKind,
        config: serde_json::Value,
    ) -> Self {
        Self {
            name: name.into(),
            mode: TaskMode::OneShot { run_at },
            kind,
            config,
            provenance: TaskProvenance::Static,
        }
    }

    /// Returns the cron schedule if this is a periodic task.
    #[must_use]
    pub fn cron_schedule(&self) -> Option<&CronSchedule> {
        if let TaskMode::Periodic { schedule } = &self.mode {
            Some(schedule.as_ref())
        } else {
            None
        }
    }

    /// Returns the canonical 6-field cron expression string for DB persistence.
    ///
    /// Returns an empty string for one-shot tasks, which do not have a cron schedule.
    #[must_use]
    pub fn cron_expr_string(&self) -> String {
        match &self.mode {
            TaskMode::Periodic { schedule } => schedule.to_string(),
            TaskMode::OneShot { .. } => String::new(),
        }
    }

    /// Returns the `task_mode` string used for DB persistence.
    ///
    /// Returns `"periodic"` or `"oneshot"`.
    #[must_use]
    pub fn task_mode_str(&self) -> &'static str {
        match &self.mode {
            TaskMode::Periodic { .. } => "periodic",
            TaskMode::OneShot { .. } => "oneshot",
        }
    }
}

/// Trait for types that can execute a scheduled task.
///
/// Implementations receive the per-task JSON configuration stored in
/// [`ScheduledTask::config`] and return `Ok(())` on success or a
/// [`SchedulerError`] on failure. Failures are logged as warnings; the scheduler
/// continues running and will retry on the next due tick.
///
/// Because async trait methods in Edition 2024 require returning a pinned boxed
/// future for object safety, implementations must wrap their async work in
/// `Box::pin(async move { … })`.
///
/// # Example
///
/// ```rust
/// use std::future::Future;
/// use std::pin::Pin;
/// use zeph_scheduler::{SchedulerError, TaskHandler};
///
/// struct NoopHandler;
///
/// impl TaskHandler for NoopHandler {
///     fn execute(
///         &self,
///         _config: &serde_json::Value,
///     ) -> Pin<Box<dyn Future<Output = Result<(), SchedulerError>> + Send + '_>> {
///         Box::pin(async move { Ok(()) })
///     }
/// }
/// ```
pub trait TaskHandler: Send + Sync {
    /// Execute the task with the provided configuration.
    ///
    /// # Errors
    ///
    /// Return [`SchedulerError::TaskFailed`] (or any other variant) to indicate
    /// that the task could not complete successfully. The error is logged but does
    /// not stop the scheduler.
    fn execute(
        &self,
        config: &serde_json::Value,
    ) -> Pin<Box<dyn Future<Output = Result<(), SchedulerError>> + Send + '_>>;

    /// Returns `true` when [`execute`](TaskHandler::execute) reads content that originates
    /// outside the scheduler's own trusted config or in-process state — e.g. a network/HTTP
    /// response, an MCP tool result, a file loaded from a plugin-marketplace skill directory,
    /// or stored memory/graph facts that may themselves have been populated from such an
    /// external source.
    ///
    /// RTW-A Mechanism 4 (capability attenuation, see
    /// [`crate::Scheduler::with_reentry_defense`]) reads this flag to decide whether the
    /// *current tick* counts as an external-read tick and should therefore suppress any
    /// custom-prompt injection dispatched later in the same tick.
    ///
    /// Defaults to `false` so a handler must explicitly opt in — treating "unknown" as
    /// "safe" would silently exempt any handler that reads untrusted content from
    /// attenuation, defeating the purpose of the mechanism. Override this to `true` for any
    /// handler whose `execute` performs network I/O, reads MCP/tool output, reloads skills
    /// from disk, or surfaces previously stored content that may have originated from a
    /// less-trusted source.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::future::Future;
    /// use std::pin::Pin;
    /// use zeph_scheduler::{SchedulerError, TaskHandler};
    ///
    /// struct FetchesRemoteData;
    ///
    /// impl TaskHandler for FetchesRemoteData {
    ///     fn execute(
    ///         &self,
    ///         _config: &serde_json::Value,
    ///     ) -> Pin<Box<dyn Future<Output = Result<(), SchedulerError>> + Send + '_>> {
    ///         Box::pin(async move { Ok(()) })
    ///     }
    ///
    ///     fn reads_external_content(&self) -> bool {
    ///         true
    ///     }
    /// }
    ///
    /// assert!(FetchesRemoteData.reads_external_content());
    /// ```
    fn reads_external_content(&self) -> bool {
        false
    }

    /// Returns `true` when [`execute`](TaskHandler::execute) injects an operator- or
    /// externally-supplied prompt into the agent loop (e.g. by sending it on a channel the
    /// agent reads as a new user message), as opposed to doing purely internal work (memory
    /// consolidation, a health probe, a network poll with no agent-facing output, etc.).
    ///
    /// RTW-A Mechanism 4 (capability attenuation, see
    /// [`crate::Scheduler::with_reentry_defense`]) reads this flag on the scheduler's normal
    /// handler-dispatch path (`register_handler` + `execute_handler`) to decide whether to
    /// suppress this handler's `execute` for the remainder of a tick that already contained an
    /// external-read task (see [`reads_external_content`](TaskHandler::reads_external_content)).
    /// Without this declaration, a handler registered for `TaskKind::Custom` that injects
    /// prompts (e.g. the built-in `CustomTaskHandler`) would bypass Mechanism 4 entirely, since
    /// suppression only guarded the no-handler-registered fallback path.
    ///
    /// Defaults to `false` for the same reason [`reads_external_content`] defaults to `false`:
    /// a handler must explicitly declare that it performs agent-facing prompt injection, so
    /// unrelated handlers (health checks, memory daemons, experiment runs) are never
    /// unnecessarily suppressed.
    ///
    /// [`reads_external_content`]: TaskHandler::reads_external_content
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::future::Future;
    /// use std::pin::Pin;
    /// use zeph_scheduler::{SchedulerError, TaskHandler};
    ///
    /// struct InjectsAgentPrompt;
    ///
    /// impl TaskHandler for InjectsAgentPrompt {
    ///     fn execute(
    ///         &self,
    ///         _config: &serde_json::Value,
    ///     ) -> Pin<Box<dyn Future<Output = Result<(), SchedulerError>> + Send + '_>> {
    ///         Box::pin(async move { Ok(()) })
    ///     }
    ///
    ///     fn injects_agent_prompt(&self) -> bool {
    ///         true
    ///     }
    /// }
    ///
    /// assert!(InjectsAgentPrompt.injects_agent_prompt());
    /// ```
    fn injects_agent_prompt(&self) -> bool {
        false
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn task_kind_roundtrip() {
        assert_eq!(
            TaskKind::from_str_kind("memory_cleanup"),
            TaskKind::MemoryCleanup
        );
        assert_eq!(TaskKind::MemoryCleanup.as_str(), "memory_cleanup");
        assert_eq!(
            TaskKind::from_str_kind("skill_refresh"),
            TaskKind::SkillRefresh
        );
        assert_eq!(TaskKind::SkillRefresh.as_str(), "skill_refresh");
        assert_eq!(
            TaskKind::from_str_kind("health_check"),
            TaskKind::HealthCheck
        );
        assert_eq!(
            TaskKind::from_str_kind("update_check"),
            TaskKind::UpdateCheck
        );
        assert_eq!(TaskKind::UpdateCheck.as_str(), "update_check");
        assert_eq!(
            TaskKind::from_str_kind("custom_job"),
            TaskKind::Custom("custom_job".into())
        );
        assert_eq!(TaskKind::Custom("x".into()).as_str(), "x");
    }

    #[test]
    fn task_kind_experiment_roundtrip() {
        assert_eq!(
            TaskKind::from_str_kind("experiment"),
            TaskKind::Experiment,
            "from_str_kind must map 'experiment' to Experiment variant, not Custom"
        );
        assert_eq!(TaskKind::Experiment.as_str(), "experiment");
    }

    #[test]
    fn normalize_five_field_prepends_zero() {
        assert_eq!(normalize_cron_expr("*/5 * * * *"), "0 */5 * * * *");
        assert_eq!(normalize_cron_expr("0 3 * * *"), "0 0 3 * * *");
    }

    #[test]
    fn normalize_six_field_passthrough() {
        assert_eq!(normalize_cron_expr("0 0 3 * * *"), "0 0 3 * * *");
        assert_eq!(normalize_cron_expr("* * * * * *"), "* * * * * *");
    }

    #[test]
    fn normalize_other_field_count_passthrough() {
        assert_eq!(normalize_cron_expr("not_cron"), "not_cron");
        assert_eq!(normalize_cron_expr("0 0 0 0"), "0 0 0 0");
    }

    #[test]
    fn normalize_empty_string_passthrough() {
        assert_eq!(normalize_cron_expr(""), "");
    }

    #[test]
    fn normalize_whitespace_only_passthrough() {
        assert_eq!(normalize_cron_expr("   "), "   ");
    }

    #[test]
    fn valid_cron_creates_task() {
        let task = ScheduledTask::new(
            "test",
            "0 0 * * * *",
            TaskKind::HealthCheck,
            serde_json::Value::Null,
        );
        assert!(task.is_ok());
    }

    #[test]
    fn five_field_cron_creates_task() {
        let task = ScheduledTask::new(
            "five-field",
            "*/5 * * * *",
            TaskKind::HealthCheck,
            serde_json::Value::Null,
        );
        assert!(task.is_ok(), "5-field cron must be accepted");
    }

    #[test]
    fn invalid_cron_returns_error() {
        let task = ScheduledTask::new(
            "test",
            "not_cron",
            TaskKind::HealthCheck,
            serde_json::Value::Null,
        );
        assert!(task.is_err());
    }

    #[test]
    fn oneshot_task_creates_correctly() {
        let run_at = Utc::now() + chrono::Duration::hours(1);
        let task =
            ScheduledTask::oneshot("t", run_at, TaskKind::HealthCheck, serde_json::Value::Null);
        assert_eq!(task.task_mode_str(), "oneshot");
        assert!(task.cron_schedule().is_none());
    }

    #[test]
    fn periodic_task_mode_str() {
        let task = ScheduledTask::periodic(
            "p",
            "0 * * * * *",
            TaskKind::HealthCheck,
            serde_json::Value::Null,
        )
        .unwrap();
        assert_eq!(task.task_mode_str(), "periodic");
        assert!(task.cron_schedule().is_some());
    }

    #[test]
    fn task_provenance_roundtrip() {
        assert_eq!(
            TaskProvenance::from_provenance_str("static"),
            TaskProvenance::Static
        );
        assert_eq!(
            TaskProvenance::from_provenance_str("user_added"),
            TaskProvenance::UserAdded
        );
        assert_eq!(
            TaskProvenance::from_provenance_str("external"),
            TaskProvenance::External
        );
        // Unknown values fall back to External (most restrictive fail-safe).
        assert_eq!(
            TaskProvenance::from_provenance_str("hydrated"),
            TaskProvenance::External
        );
        assert_eq!(TaskProvenance::Static.as_str(), "static");
        assert_eq!(TaskProvenance::UserAdded.as_str(), "user_added");
        assert_eq!(TaskProvenance::External.as_str(), "external");
    }

    #[test]
    fn task_provenance_is_external() {
        assert!(TaskProvenance::External.is_external());
        assert!(!TaskProvenance::Static.is_external());
        assert!(!TaskProvenance::UserAdded.is_external());
    }

    #[test]
    fn cron_expr_valid_six_field() {
        let expr = CronExpr::try_from("0 0 3 * * *").expect("valid 6-field");
        assert_eq!(expr.as_ref(), "0 0 3 * * *");
    }

    #[test]
    fn cron_expr_valid_five_field_normalised() {
        let expr = CronExpr::try_from("0 3 * * *").expect("valid 5-field");
        // 5-field is normalised by prepending "0 "
        assert_eq!(expr.as_ref(), "0 0 3 * * *");
    }

    #[test]
    fn cron_expr_invalid_returns_error() {
        assert!(CronExpr::try_from("not a cron").is_err());
        assert!(CronExpr::try_from("").is_err());
    }

    #[test]
    fn cron_expr_display_and_as_str_consistent() {
        let expr = CronExpr::try_from("* * * * * *").expect("wildcard cron");
        assert_eq!(expr.as_str(), expr.to_string());
    }

    #[test]
    fn cron_expr_clone_and_eq() {
        let a = CronExpr::try_from("0 0 * * * *").expect("valid");
        let b = a.clone();
        assert_eq!(a, b);
    }

    #[test]
    fn cron_expr_serialize_deserialize_roundtrip() {
        let expr = CronExpr::try_from("0 0 3 * * *").expect("valid");
        let json = serde_json::to_string(&expr).expect("serialize");
        assert_eq!(json, r#""0 0 3 * * *""#);
        let decoded: CronExpr = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(expr, decoded);
    }

    #[test]
    fn cron_expr_deserialize_invalid_returns_error() {
        let result: Result<CronExpr, _> = serde_json::from_str(r#""not-a-cron""#);
        assert!(result.is_err());
    }

    #[test]
    fn new_task_has_static_provenance() {
        let task = ScheduledTask::new(
            "test",
            "0 * * * * *",
            TaskKind::HealthCheck,
            serde_json::Value::Null,
        )
        .unwrap();
        assert_eq!(task.provenance, TaskProvenance::Static);
    }

    #[test]
    fn periodic_with_provenance_sets_provenance() {
        let task = ScheduledTask::periodic_with_provenance(
            "ext",
            "0 * * * * *",
            TaskKind::HealthCheck,
            serde_json::Value::Null,
            TaskProvenance::External,
        )
        .unwrap();
        assert_eq!(task.provenance, TaskProvenance::External);
    }
}