qontinui-types 0.6.0

Canonical DTO types for Qontinui. Rust is the source of truth; TypeScript and Python are generated from JSON Schema emitted by schemars.
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
//! Scheduler DTO types.
//!
//! Wire-format types for the CI/CD scheduler: schedule expressions, task
//! definitions, execution records, and the API request/response envelopes used
//! to create and update scheduled tasks.
//!
//! These types are a port of the shape-bearing portion of
//! `qontinui-runner/src-tauri/src/scheduler.rs`. Behavior (constructors,
//! condition evaluation, rearm checks, next-run computation) stays in the
//! runner — this crate is data-only.

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

// ============================================================================
// Schedule Expression Types
// ============================================================================

/// How a task should be scheduled.
///
/// Serialized with the external tag `type` and payload under `value` so that
/// `Once("...")`, `Cron("...")`, and `Interval(60)` round-trip as
/// `{ "type": "Once", "value": "..." }` etc. The `Condition` variant wraps a
/// [`ConditionScheduleConfig`] rather than a scalar, but uses the same
/// `{ type, value }` envelope.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", content = "value")]
pub enum ScheduleExpression {
    /// Run once at a specific datetime (ISO 8601).
    Once(String),
    /// Cron expression (e.g., `"0 9 * * *"` for 9 AM daily). The runner
    /// accepts both 5-field and 6/7-field cron forms and normalizes internally.
    Cron(String),
    /// Interval in seconds between runs (for testing/debugging).
    Interval(u64),
    /// Condition-only schedule: no time trigger, runs whenever the attached
    /// [`ScheduleConditions`] on the task are met.
    Condition(ConditionScheduleConfig),
}

/// Configuration for condition-only schedules.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
#[schemars(deny_unknown_fields)]
pub struct ConditionScheduleConfig {
    /// Minutes to wait after an execution completes before re-evaluating
    /// conditions for another run.
    #[serde(default = "default_rearm_delay", alias = "rearm_delay_minutes")]
    pub rearm_delay_minutes: u32,
}

impl Default for ConditionScheduleConfig {
    fn default() -> Self {
        Self {
            rearm_delay_minutes: default_rearm_delay(),
        }
    }
}

fn default_rearm_delay() -> u32 {
    60
}

// ============================================================================
// Schedule Conditions
// ============================================================================

/// Condition that requires the runner to be idle (not executing workflows or
/// AI tasks) before the task may run.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
#[serde(rename_all = "camelCase")]
#[schemars(deny_unknown_fields)]
pub struct IdleCondition {
    /// Whether this condition is active.
    #[serde(alias = "enabled")]
    pub enabled: bool,
}

/// A single repository to monitor for inactivity.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
#[schemars(deny_unknown_fields)]
pub struct RepositoryWatch {
    /// Path to the repository directory.
    #[serde(alias = "path")]
    pub path: String,
    /// Minutes of inactivity required before the watch is considered met.
    #[serde(alias = "inactive_minutes")]
    pub inactive_minutes: u32,
}

/// Condition that requires repositories to have no file modifications for a
/// period. ALL configured repositories must be inactive for the overall
/// condition to be met.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
#[serde(rename_all = "camelCase")]
#[schemars(deny_unknown_fields)]
pub struct RepositoryInactiveCondition {
    /// Whether this condition is active.
    #[serde(alias = "enabled")]
    pub enabled: bool,
    /// List of repositories to watch. ALL must be inactive simultaneously.
    #[serde(default, alias = "repositories")]
    pub repositories: Vec<RepositoryWatch>,
}

/// Conditions that must ALL be met before task execution.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
#[serde(rename_all = "camelCase")]
#[schemars(deny_unknown_fields)]
pub struct ScheduleConditions {
    /// Require the runner to be idle.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "require_idle"
    )]
    pub require_idle: Option<IdleCondition>,
    /// Require repository file inactivity across one or more paths.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "require_repo_inactive"
    )]
    pub require_repo_inactive: Option<RepositoryInactiveCondition>,
    /// Maximum time to wait for conditions (minutes). `None` = wait
    /// indefinitely.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "timeout_minutes"
    )]
    pub timeout_minutes: Option<u32>,
}

/// Status of condition checking for a deferred task.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
#[schemars(deny_unknown_fields)]
pub struct ConditionStatus {
    /// ISO 8601 timestamp when conditions began being evaluated.
    #[serde(alias = "waiting_since")]
    pub waiting_since: String,
    /// Current idle-condition result. `None` if not yet checked,
    /// `Some(true)` if idle, `Some(false)` if busy.
    #[serde(default, skip_serializing_if = "Option::is_none", alias = "idle_met")]
    pub idle_met: Option<bool>,
    /// Current repository-inactive status per repository: `(path, is_inactive)`.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "repo_inactive_met"
    )]
    pub repo_inactive_met: Option<Vec<(String, bool)>>,
    /// Whether the overall condition-wait timeout has been exceeded.
    #[serde(default, alias = "timed_out")]
    pub timed_out: bool,
}

// ============================================================================
// Task Type Definitions
// ============================================================================

/// Type of task to schedule.
///
/// Internally tagged by `task_type`: the variant fields are inlined alongside
/// the discriminator rather than nested under a `value` key.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "task_type")]
pub enum ScheduledTaskType {
    /// Run a workflow — either a legacy workflow-by-name from a loaded config
    /// or a unified workflow by ID.
    Workflow {
        /// Display name (also used to look up legacy workflows).
        workflow_name: String,
        /// Optional path to a workflow config file.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        config_path: Option<String>,
        /// Optional monitor index to target.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        monitor_index: Option<i32>,
        /// If set, run a unified workflow by ID instead of a legacy workflow
        /// by name.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        workflow_id: Option<String>,
    },
    /// Run a prompt from the Prompt Library.
    Prompt {
        /// ID of the prompt to run.
        prompt_id: String,
        /// Optional override for `max_sessions`. `None` uses the prompt's own
        /// setting.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        max_sessions: Option<u32>,
    },
    /// Trigger auto-fix: check findings and fix any auto-fixable items.
    AutoFix {
        /// Whether to check the findings queue before running.
        #[serde(default = "default_true")]
        check_findings: bool,
        /// Force a run even if no findings are present.
        #[serde(default)]
        force_run: bool,
    },
    /// Execute a watcher (screenpipe-inspired reactive AI agent). Queries the
    /// activity timeline, reasons with AI, and triggers an action.
    Watcher {
        /// ID of the watcher definition in PostgreSQL.
        watcher_id: String,
    },
    /// Continuous background capture (screenpipe-style). Periodically
    /// captures screen state and stores it in the activity timeline.
    BackgroundCapture {
        /// Optional monitor index to capture.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        monitor_index: Option<i32>,
        /// Seconds between successive captures.
        #[serde(default = "default_capture_interval")]
        capture_interval_secs: u64,
        /// Whether to also trigger a capture on window focus change.
        #[serde(default = "default_true")]
        capture_on_focus_change: bool,
    },
    /// Run an ad-hoc Claude agent prompt without pre-registering it in the
    /// Prompt Library. Reuses the runner's existing `POST /prompts/run`
    /// ad-hoc surface — no separate Claude CLI plumbing required.
    RemoteAgent {
        /// The prompt content to send to the Claude session.
        prompt: String,
        /// Working directory for the spawned session. `None` means the
        /// runner's project root. Stored as a string (not `PathBuf`) to keep
        /// this crate JSON-Schema-friendly.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        working_directory: Option<String>,
        /// Allowed tool names (e.g. `["Bash", "Read", "Write", "Edit"]`).
        /// Empty = use the runner's default tool allow-list.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        allowed_tools: Vec<String>,
        /// Optional model override. `None` = runner default
        /// (typically `claude-sonnet-4-6`).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        model: Option<String>,
        /// Optional MCP connection references resolved at dispatch time
        /// against the runner's existing MCP config. Empty = inherit
        /// whatever the runner currently has configured.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        mcp_connections: Vec<McpConnectionRef>,
        /// Hard cap on Claude turns per run (safety bound). `None` =
        /// runner's default cap (typically 50).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        max_turns: Option<u32>,
        /// Wall-clock timeout in seconds. `None` = runner default
        /// (typically 600s = 10 min).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        timeout_seconds: Option<u64>,
    },
}

/// Lightweight reference to an MCP connection for [`ScheduledTaskType::RemoteAgent`].
///
/// `name` is the MCP server name as registered in the runner's MCP config.
/// `url` is an optional override; when omitted the runner resolves the URL
/// from its existing MCP config at dispatch time.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
#[schemars(deny_unknown_fields)]
pub struct McpConnectionRef {
    /// MCP server name as registered in the runner's MCP config.
    pub name: String,
    /// Optional URL override; falls back to the runner's MCP config when
    /// `None`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
}

/// Catch-up policy applied when the runner restarts after missing one or
/// more scheduled slots.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum CatchUpPolicy {
    /// Run the missed slot once for each occurrence that was skipped.
    Run,
    /// Skip all missed slots; emit `MissedRunnerDown` history rows for
    /// audit but do not execute.
    Skip,
    /// Collapse multiple missed slots into a single catch-up run.
    #[default]
    RunOnce,
}

fn default_catch_up_policy() -> CatchUpPolicy {
    CatchUpPolicy::RunOnce
}

fn default_catch_up_grace_seconds() -> u32 {
    300
}

fn default_consecutive_launch_failures() -> u32 {
    0
}

fn default_launch_failure_backoff_seconds() -> u32 {
    60
}

fn default_true() -> bool {
    true
}

fn default_catch_up_run() -> bool {
    false
}

fn default_capture_interval() -> u64 {
    30
}

// ============================================================================
// Task Status
// ============================================================================

/// Status of a scheduled task execution.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum ScheduledTaskStatus {
    /// Scheduled and waiting to run.
    #[default]
    Pending,
    /// Currently executing.
    Running,
    /// Finished successfully.
    Completed,
    /// Finished with an error after the task had started running.
    Failed,
    /// The task could not even start (workflow file missing, prompt resolve
    /// failure, ai_session spawn error, etc.). Distinct from `Failed` because
    /// it drives the launch-failure backoff in
    /// [`ScheduledTask::launch_failure_backoff_seconds`].
    LaunchFailed,
    /// Skipped because the task had already completed successfully and
    /// `skip_if_completed` is `true`.
    Skipped,
    /// Cancelled before or during execution.
    Cancelled,
    /// Slot detected as missed during catch-up reconciliation while the
    /// runner was offline. Recorded as a history row when
    /// [`CatchUpPolicy::Skip`] is in effect; never returned for currently
    /// queued tasks.
    MissedRunnerDown,
}

// ============================================================================
// Execution Record
// ============================================================================

/// Record of a single task execution.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
#[schemars(deny_unknown_fields)]
pub struct TaskExecutionRecord {
    /// Unique ID for this execution (UUID v4 string).
    #[serde(alias = "execution_id")]
    pub execution_id: String,
    /// Session ID if this execution triggered an AI session, used for
    /// downstream success tracking.
    #[serde(default, skip_serializing_if = "Option::is_none", alias = "session_id")]
    pub session_id: Option<String>,
    /// ISO 8601 timestamp when execution started.
    #[serde(alias = "started_at")]
    pub started_at: String,
    /// ISO 8601 timestamp when execution ended.
    #[serde(default, skip_serializing_if = "Option::is_none", alias = "ended_at")]
    pub ended_at: Option<String>,
    /// Current status of this execution.
    #[serde(alias = "status")]
    pub status: ScheduledTaskStatus,
    /// Whether the task succeeded, read from the session checkpoint.
    #[serde(default, alias = "success")]
    pub success: bool,
    /// Error message if the execution failed.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "error_message"
    )]
    pub error_message: Option<String>,
    /// Whether auto-fix was triggered after this execution.
    #[serde(default, alias = "triggered_auto_fix")]
    pub triggered_auto_fix: bool,
    /// Session ID of the auto-fix session, if one was triggered.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "auto_fix_session_id"
    )]
    pub auto_fix_session_id: Option<String>,
    /// ISO 8601 timestamp of the *scheduled* slot this execution covers,
    /// distinct from `started_at` (which is the actual launch time). Allows
    /// detecting "ran X minutes late" and is consumed by the missed-run
    /// reconciler. Optional for backward compatibility with execution rows
    /// written before this field existed.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "scheduled_for"
    )]
    pub scheduled_for: Option<String>,
    /// Whether this execution record was created by the catch-up reconciler
    /// (rather than the normal scheduling tick).
    #[serde(default = "default_catch_up_run", alias = "catch_up_run")]
    pub catch_up_run: bool,
}

// ============================================================================
// Scheduled Task
// ============================================================================

/// A scheduled task definition — the full persisted frame, including computed
/// fields (`last_run`, `next_run`) and condition-evaluation state
/// (`conditions`, `condition_status`).
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
#[schemars(deny_unknown_fields)]
pub struct ScheduledTask {
    /// Unique identifier (UUID v4 string).
    #[serde(alias = "id")]
    pub id: String,
    /// Display name for the task.
    #[serde(alias = "name")]
    pub name: String,
    /// Optional human-readable description.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "description"
    )]
    pub description: Option<String>,
    /// Whether the task is enabled and eligible to run.
    #[serde(default = "default_true", alias = "enabled")]
    pub enabled: bool,
    /// Schedule configuration.
    #[serde(alias = "schedule")]
    pub schedule: ScheduleExpression,
    /// Task type and its per-type configuration.
    #[serde(alias = "task")]
    pub task: ScheduledTaskType,
    /// Skip future runs once the task has succeeded at least once.
    #[serde(default, alias = "skip_if_completed")]
    pub skip_if_completed: bool,
    /// Automatically trigger auto-fix when this task fails.
    #[serde(default, alias = "auto_fix_on_failure")]
    pub auto_fix_on_failure: bool,
    /// Free-form description of success criteria, for human reference.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "success_criteria"
    )]
    pub success_criteria: Option<String>,
    /// ISO 8601 timestamp of creation.
    #[serde(alias = "created_at")]
    pub created_at: String,
    /// ISO 8601 timestamp of last modification.
    #[serde(alias = "modified_at")]
    pub modified_at: String,
    /// Record of the most recent execution.
    #[serde(default, skip_serializing_if = "Option::is_none", alias = "last_run")]
    pub last_run: Option<TaskExecutionRecord>,
    /// Next scheduled run time (ISO 8601), computed by the runner.
    #[serde(default, skip_serializing_if = "Option::is_none", alias = "next_run")]
    pub next_run: Option<String>,
    /// Optional conditions that must be met before execution.
    #[serde(default, skip_serializing_if = "Option::is_none", alias = "conditions")]
    pub conditions: Option<ScheduleConditions>,
    /// Present while the task is waiting for its conditions to be met.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "condition_status"
    )]
    pub condition_status: Option<ConditionStatus>,
    /// Catch-up policy applied when the runner restarts after missing one
    /// or more scheduled slots.
    #[serde(default = "default_catch_up_policy", alias = "catch_up_policy")]
    pub catch_up_policy: CatchUpPolicy,
    /// Slots within this number of seconds of "now" are not treated as
    /// missed (the normal scheduler will pick them up). Default 300s.
    #[serde(
        default = "default_catch_up_grace_seconds",
        alias = "catch_up_grace_seconds"
    )]
    pub catch_up_grace_seconds: u32,
    /// Number of consecutive launch failures since the task last started
    /// successfully. Drives exponential backoff. Reset to 0 on the next
    /// successful launch.
    #[serde(
        default = "default_consecutive_launch_failures",
        alias = "consecutive_launch_failures"
    )]
    pub consecutive_launch_failures: u32,
    /// **Base** backoff in seconds for launch failures (not the current
    /// accumulated backoff). The runner computes the effective delay as
    /// `min(base * 2^(consecutive_launch_failures - 1), 86400)`.
    /// Default 60s.
    #[serde(
        default = "default_launch_failure_backoff_seconds",
        alias = "launch_failure_backoff_seconds"
    )]
    pub launch_failure_backoff_seconds: u32,
}

// ============================================================================
// Scheduler Settings
// ============================================================================

/// Global scheduler settings.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
#[schemars(deny_unknown_fields)]
pub struct SchedulerSettings {
    /// Whether the scheduler is enabled globally.
    #[serde(default = "default_true", alias = "enabled")]
    pub enabled: bool,
    /// Maximum number of scheduled tasks allowed to run concurrently.
    #[serde(default = "default_max_concurrent", alias = "max_concurrent")]
    pub max_concurrent: u32,
    /// Default `auto_fix_on_failure` value for newly created tasks.
    #[serde(default, alias = "default_auto_fix_on_failure")]
    pub default_auto_fix_on_failure: bool,
    /// Timezone for schedule interpretation (IANA name). `None` = local time.
    #[serde(default, skip_serializing_if = "Option::is_none", alias = "timezone")]
    pub timezone: Option<String>,
}

fn default_max_concurrent() -> u32 {
    1
}

impl Default for SchedulerSettings {
    fn default() -> Self {
        Self {
            enabled: true,
            max_concurrent: default_max_concurrent(),
            default_auto_fix_on_failure: false,
            timezone: None,
        }
    }
}

// ============================================================================
// Scheduler Status (API responses)
// ============================================================================

/// Summary of the scheduler's current runtime state, returned from the status
/// API.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
#[schemars(deny_unknown_fields)]
pub struct SchedulerStatus {
    /// Whether the scheduler is enabled.
    #[serde(alias = "enabled")]
    pub enabled: bool,
    /// Number of tasks currently running.
    #[serde(alias = "running_tasks")]
    pub running_tasks: u32,
    /// Number of tasks scheduled but not yet running.
    #[serde(alias = "pending_tasks")]
    pub pending_tasks: u32,
    /// The next task scheduled to run, if any.
    #[serde(default, skip_serializing_if = "Option::is_none", alias = "next_task")]
    pub next_task: Option<NextTaskInfo>,
}

/// Minimal description of the next task due to run.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
#[schemars(deny_unknown_fields)]
pub struct NextTaskInfo {
    /// Task ID.
    #[serde(alias = "id")]
    pub id: String,
    /// Task display name.
    #[serde(alias = "name")]
    pub name: String,
    /// ISO 8601 timestamp of the next scheduled run.
    #[serde(alias = "next_run")]
    pub next_run: String,
}

// ============================================================================
// API Request/Response Types
// ============================================================================

/// Request body for creating a new scheduled task.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
#[schemars(deny_unknown_fields)]
pub struct CreateScheduledTaskRequest {
    /// Display name.
    #[serde(alias = "name")]
    pub name: String,
    /// Optional description.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "description"
    )]
    pub description: Option<String>,
    /// Schedule configuration.
    #[serde(alias = "schedule")]
    pub schedule: ScheduleExpression,
    /// Task type and its per-type configuration.
    #[serde(alias = "task")]
    pub task: ScheduledTaskType,
    /// Skip future runs once the task has succeeded.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "skip_if_completed"
    )]
    pub skip_if_completed: Option<bool>,
    /// Trigger auto-fix on failure.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "auto_fix_on_failure"
    )]
    pub auto_fix_on_failure: Option<bool>,
    /// Free-form success criteria description.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "success_criteria"
    )]
    pub success_criteria: Option<String>,
    /// Optional conditions that must be met before execution.
    #[serde(default, skip_serializing_if = "Option::is_none", alias = "conditions")]
    pub conditions: Option<ScheduleConditions>,
    /// Optional catch-up policy override. `None` = runner default
    /// ([`CatchUpPolicy::RunOnce`]).
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "catch_up_policy"
    )]
    pub catch_up_policy: Option<CatchUpPolicy>,
    /// Optional catch-up grace window override (seconds). `None` =
    /// runner default (300s).
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "catch_up_grace_seconds"
    )]
    pub catch_up_grace_seconds: Option<u32>,
    /// Optional override for the launch-failure backoff base (seconds).
    /// `None` = runner default (60s).
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "launch_failure_backoff_seconds"
    )]
    pub launch_failure_backoff_seconds: Option<u32>,
}

/// Request body for updating an existing scheduled task. All fields are
/// optional; only those supplied are applied.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
#[serde(rename_all = "camelCase")]
#[schemars(deny_unknown_fields)]
pub struct UpdateScheduledTaskRequest {
    /// New display name.
    #[serde(default, skip_serializing_if = "Option::is_none", alias = "name")]
    pub name: Option<String>,
    /// New description (pass `null` to clear).
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "description"
    )]
    pub description: Option<String>,
    /// Enable/disable the task.
    #[serde(default, skip_serializing_if = "Option::is_none", alias = "enabled")]
    pub enabled: Option<bool>,
    /// Replace the schedule expression.
    #[serde(default, skip_serializing_if = "Option::is_none", alias = "schedule")]
    pub schedule: Option<ScheduleExpression>,
    /// Replace the task definition.
    #[serde(default, skip_serializing_if = "Option::is_none", alias = "task")]
    pub task: Option<ScheduledTaskType>,
    /// Update `skip_if_completed`.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "skip_if_completed"
    )]
    pub skip_if_completed: Option<bool>,
    /// Update `auto_fix_on_failure`.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "auto_fix_on_failure"
    )]
    pub auto_fix_on_failure: Option<bool>,
    /// Update the success criteria (pass `null` to clear).
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "success_criteria"
    )]
    pub success_criteria: Option<String>,
    /// Replace the conditions block (pass `null` to clear).
    #[serde(default, skip_serializing_if = "Option::is_none", alias = "conditions")]
    pub conditions: Option<ScheduleConditions>,
    /// Update the catch-up policy.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "catch_up_policy"
    )]
    pub catch_up_policy: Option<CatchUpPolicy>,
    /// Update the catch-up grace window (seconds).
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "catch_up_grace_seconds"
    )]
    pub catch_up_grace_seconds: Option<u32>,
    /// Update the launch-failure backoff base (seconds).
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "launch_failure_backoff_seconds"
    )]
    pub launch_failure_backoff_seconds: Option<u32>,
}