opencrabs 0.3.80

The autonomous, self-improving AI agent. Single Rust binary. Every channel. Recommended: the 40MB prebuilt binary for macOS, Linux and Windows: https://github.com/adolfousier/opencrabs/releases
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
//! Cron Manage Tool
//!
//! Allows the agent to create, list, update, delete, enable, and disable cron
//! jobs. Jobs run in isolated sessions with configurable provider/model/thinking.

use super::error::Result;
use super::r#trait::{Tool, ToolCapability, ToolExecutionContext, ToolResult};
use crate::db::models::CronJob;
use crate::db::{CronJobPatch, CronJobRepository};
use async_trait::async_trait;
use serde_json::Value;

/// Tool for managing cron jobs via the agent.
pub struct CronManageTool {
    repo: CronJobRepository,
}

impl CronManageTool {
    pub fn new(repo: CronJobRepository) -> Self {
        Self { repo }
    }
}

#[async_trait]
impl Tool for CronManageTool {
    fn name(&self) -> &str {
        "cron_manage"
    }

    fn description(&self) -> &str {
        "Manage scheduled cron jobs. Jobs run in isolated sessions with configurable provider/model. \
         Use 'create' to schedule a new job, 'list' to see all jobs, 'update' to change fields of an \
         existing job in place (only the fields you pass are touched), 'delete' to remove one, \
         'enable'/'disable' to toggle a job without deleting it."
    }

    fn input_schema(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "action": {
                    "type": "string",
                    "enum": ["create", "list", "delete", "update", "enable", "disable", "test"],
                    "description": "Action to perform. 'test' triggers a job immediately (runs on next scheduler tick within 60s)"
                },
                "name": {
                    "type": "string",
                    "description": "Job name (required for create, optional new name for update)"
                },
                "cron": {
                    "type": "string",
                    "description": "Cron expression, 5-field: 'min hour dom mon dow'. Required for create, optional for update. Day-of-week is 1-7 = Sun-Sat (1=Sunday, 7=Saturday; 0 is INVALID) — prefer day NAMES (Sun, Mon..Sat, ranges like Mon-Fri) to avoid off-by-one mistakes. Month also accepts names (Jan-Mar). No @daily/@hourly macros. Examples: '0 9 * * *' (daily 9am), '*/30 * * * *' (every 30min), '0 9 * * Mon-Fri' (weekdays 9am), '0 22 * * Sun' (Sundays 10pm). The create/update reply shows the next run times — verify them."
                },
                "tz": {
                    "type": "string",
                    "description": "IANA timezone (default: UTC) — the schedule runs in this zone's local wall clock, DST-aware. Examples: America/New_York, Europe/London, Asia/Tokyo. An unknown zone is rejected."
                },
                "prompt": {
                    "type": "string",
                    "description": "Instructions for the agent to execute (required for create, optional for update; omitted on update keeps the existing prompt)"
                },
                "provider": {
                    "type": "string",
                    "description": "Override provider (e.g. 'anthropic', 'openai'). Omit for current default. On update, pass an empty string to clear the override back to the default."
                },
                "model": {
                    "type": "string",
                    "description": "Override model (e.g. 'claude-sonnet-4-20250514'). Omit for provider default. On update, pass an empty string to clear the override."
                },
                "thinking": {
                    "type": "string",
                    "enum": ["off", "on", "budget"],
                    "description": "Thinking mode (default: off)"
                },
                "auto_approve": {
                    "type": "boolean",
                    "description": "Auto-approve tool executions (default: true for cron)"
                },
                "deliver_to": {
                    "type": "string",
                    "description": "Where to deliver results. Format: 'telegram:chat_id', 'discord:channel_id', 'slack:channel_id', or an HTTP(S) URL for webhook delivery. On update, pass an empty string to clear delivery."
                },
                "deliver_api_key": {
                    "type": "string",
                    "description": "Optional Bearer token for HTTP webhook delivery. Added as Authorization: Bearer <key> header when delivering to an HTTP(S) URL. On update, pass an empty string to clear it."
                },
                "job_id": {
                    "type": "string",
                    "description": "Job ID or name (required for delete/update/enable/disable)"
                },
                "enabled": {
                    "type": "boolean",
                    "description": "Whether the job is enabled (for create, default: true; for update, sets the enabled state)"
                },
                "confirm": {
                    "type": "boolean",
                    "description": "Must be true to actually delete a job. Without it, delete only shows job details as a safety check."
                }
            },
            "required": ["action"]
        })
    }

    fn capabilities(&self) -> Vec<ToolCapability> {
        vec![ToolCapability::SystemModification]
    }

    fn requires_approval_for_input(&self, input: &Value) -> bool {
        // create, update, delete, disable, and test need approval; list/enable are safe
        matches!(
            input.get("action").and_then(|v| v.as_str()),
            Some("create") | Some("update") | Some("delete") | Some("disable") | Some("test")
        )
    }

    async fn execute(&self, input: Value, _context: &ToolExecutionContext) -> Result<ToolResult> {
        let action = input
            .get("action")
            .and_then(|v| v.as_str())
            .unwrap_or("list");

        match action {
            "create" => self.create_job(&input).await,
            "list" => self.list_jobs().await,
            "delete" => self.delete_job(&input).await,
            "update" => self.update_job(&input).await,
            "enable" => self.toggle_job(&input, true).await,
            "disable" => self.toggle_job(&input, false).await,
            "test" => self.test_job(&input).await,
            unknown => Ok(ToolResult::error(format!(
                "Unknown action '{unknown}'. Valid: create, list, delete, update, enable, disable, test"
            ))),
        }
    }
}

impl CronManageTool {
    async fn create_job(&self, input: &Value) -> Result<ToolResult> {
        let name = match input.get("name").and_then(|v| v.as_str()) {
            Some(n) if !n.is_empty() => n,
            _ => {
                return Ok(ToolResult::error(
                    "'name' is required for create".to_string(),
                ));
            }
        };

        let cron_expr = match input.get("cron").and_then(|v| v.as_str()) {
            Some(c) if !c.is_empty() => c,
            _ => {
                return Ok(ToolResult::error(
                    "'cron' expression is required for create".to_string(),
                ));
            }
        };

        // Validate cron expression (user provides 5-field, we prepend "0" for seconds)
        let cron_with_secs = format!("0 {cron_expr}");
        if let Err(e) = cron_with_secs.parse::<cron::Schedule>() {
            return Ok(ToolResult::error(format!(
                "Invalid cron expression '{cron_expr}': {e}. Use 5-field format: 'min hour dom mon dow'. \
                 Day-of-week is 1-7 = Sun-Sat (1=Sunday, 7=Saturday; 0 is invalid) — prefer names like \
                 Mon-Fri or Sun to avoid mistakes. Example: '0 9 * * *' = daily 9am, '0 9 * * Mon-Fri' = weekdays 9am."
            )));
        }

        let prompt = match input.get("prompt").and_then(|v| v.as_str()) {
            Some(p) if !p.is_empty() => p,
            _ => {
                return Ok(ToolResult::error(
                    "'prompt' is required for create".to_string(),
                ));
            }
        };

        // Check for duplicate name
        if let Ok(Some(_)) = self.repo.find_by_name(name).await {
            return Ok(ToolResult::error(format!(
                "A cron job named '{name}' already exists. Use a different name or delete the existing one first."
            )));
        }

        let tz = input
            .get("tz")
            .and_then(|v| v.as_str())
            .unwrap_or("UTC")
            .to_string();
        // Validate the timezone now — it's honored by the scheduler (jobs run
        // in this zone's wall clock, DST-aware), so an unknown zone must be
        // rejected here rather than silently falling back to UTC.
        let parsed_tz = match crate::cron::parse_timezone(&tz) {
            Some(t) => t,
            None => {
                return Ok(ToolResult::error(format!(
                    "Unknown timezone '{tz}'. Use an IANA name like 'America/New_York', 'Europe/London', 'Asia/Tokyo', or 'UTC'."
                )));
            }
        };
        let provider = input
            .get("provider")
            .and_then(|v| v.as_str())
            .map(String::from);
        let model = input
            .get("model")
            .and_then(|v| v.as_str())
            .map(String::from);
        let thinking = input
            .get("thinking")
            .and_then(|v| v.as_str())
            .unwrap_or("off")
            .to_string();
        let auto_approve = input
            .get("auto_approve")
            .and_then(|v| v.as_bool())
            .unwrap_or(true);
        let deliver_to = input
            .get("deliver_to")
            .and_then(|v| v.as_str())
            .map(String::from);
        let deliver_api_key = input
            .get("deliver_api_key")
            .and_then(|v| v.as_str())
            .map(String::from);

        let job = CronJob::new(
            name.to_string(),
            cron_expr.to_string(),
            tz,
            prompt.to_string(),
            provider,
            model,
            thinking,
            auto_approve,
            deliver_to.clone(),
            deliver_api_key,
        );

        let job_id = job.id.to_string();

        self.repo
            .insert(&job)
            .await
            .map_err(|e| super::error::ToolError::Execution(e.to_string()))?;

        let delivery = deliver_to
            .as_deref()
            .unwrap_or("none (results logged only)");

        // Confirmation feedback: show the next few fire times in the job's
        // timezone so the agent (and user) can verify the schedule means what
        // they intended before treating it as done — this is what catches a
        // day-of-week mistake that still parses fine.
        let next_runs = crate::cron::format_upcoming(cron_expr, parsed_tz, 3, chrono::Utc::now());

        Ok(ToolResult::success(format!(
            "Cron job created:\n  ID: {job_id}\n  Name: {name}\n  Schedule: {cron_expr}\n  Timezone: {}\n  Deliver to: {delivery}\n  Enabled: true\n  Next runs:\n{next_runs}\n\nVerify the Next runs match what you intended (day-of-week is Sun-Sat, DST handled) before confirming to the user.",
            job.timezone
        )))
    }

    async fn update_job(&self, input: &Value) -> Result<ToolResult> {
        let job_id = match input.get("job_id").and_then(|v| v.as_str()) {
            Some(id) if !id.is_empty() => id,
            _ => {
                return Ok(ToolResult::error(
                    "'job_id' is required for update".to_string(),
                ));
            }
        };

        // Resolve by ID first, then by name (same resolution as delete/test).
        let job = match self.repo.find_by_id(job_id).await {
            Ok(Some(j)) => j,
            Ok(None) => match self.repo.find_by_name(job_id).await {
                Ok(Some(j)) => j,
                _ => {
                    return Ok(ToolResult::error(format!(
                        "No cron job found with ID or name '{job_id}'."
                    )));
                }
            },
            Err(e) => {
                return Ok(ToolResult::error(format!("Error looking up cron job: {e}")));
            }
        };

        let mut patch = CronJobPatch::default();
        let mut changed: Vec<String> = Vec::new();
        let mut provided = 0usize;

        // Name (a rename checks for a collision with another job).
        if let Some(name) = input.get("name").and_then(|v| v.as_str()) {
            provided += 1;
            if name.is_empty() {
                return Ok(ToolResult::error("'name' cannot be empty".to_string()));
            }
            if name != job.name {
                let taken = matches!(
                    self.repo.find_by_name(name).await,
                    Ok(Some(other)) if other.id != job.id
                );
                if taken {
                    return Ok(ToolResult::error(format!(
                        "A cron job named '{name}' already exists. Use a different name."
                    )));
                }
                patch.name = Some(name.to_string());
                changed.push(format!("name -> {name}"));
            }
        }

        // Cron schedule: validated exactly like create.
        let mut schedule_changed = false;
        if let Some(cron_expr) = input.get("cron").and_then(|v| v.as_str()) {
            provided += 1;
            if cron_expr.is_empty() {
                return Ok(ToolResult::error("'cron' cannot be empty".to_string()));
            }
            let cron_with_secs = format!("0 {cron_expr}");
            if let Err(e) = cron_with_secs.parse::<cron::Schedule>() {
                return Ok(ToolResult::error(format!(
                    "Invalid cron expression '{cron_expr}': {e}. Use 5-field format: 'min hour dom mon dow'. \
                     Day-of-week is 1-7 = Sun-Sat (1=Sunday, 7=Saturday; 0 is invalid) — prefer names like \
                     Mon-Fri or Sun to avoid mistakes. Example: '0 9 * * *' = daily 9am, '0 9 * * Mon-Fri' = weekdays 9am."
                )));
            }
            if cron_expr != job.cron_expr {
                patch.cron_expr = Some(cron_expr.to_string());
                schedule_changed = true;
                changed.push(format!("schedule -> {cron_expr}"));
            }
        }

        // Timezone: validated exactly like create.
        let mut tz_changed = false;
        let effective_tz = if let Some(tz) = input.get("tz").and_then(|v| v.as_str()) {
            provided += 1;
            if tz.is_empty() {
                return Ok(ToolResult::error("'tz' cannot be empty".to_string()));
            }
            if crate::cron::parse_timezone(tz).is_none() {
                return Ok(ToolResult::error(format!(
                    "Unknown timezone '{tz}'. Use an IANA name like 'America/New_York', 'Europe/London', 'Asia/Tokyo', or 'UTC'."
                )));
            }
            if tz != job.timezone {
                patch.timezone = Some(tz.to_string());
                tz_changed = true;
                changed.push(format!("timezone -> {tz}"));
            }
            tz.to_string()
        } else {
            job.timezone.clone()
        };

        // Prompt: omitting it keeps the existing one (the whole point of a
        // patch-style update).
        if let Some(prompt) = input.get("prompt").and_then(|v| v.as_str()) {
            provided += 1;
            if prompt.is_empty() {
                return Ok(ToolResult::error("'prompt' cannot be empty".to_string()));
            }
            if prompt != job.prompt {
                patch.prompt = Some(prompt.to_string());
                changed.push(format!("prompt -> {}", truncate(prompt, 60)));
            }
        }

        // Optional string overrides: present = set, empty string = clear.
        for (key, current) in [
            ("provider", job.provider.as_deref()),
            ("model", job.model.as_deref()),
            ("deliver_to", job.deliver_to.as_deref()),
            ("deliver_api_key", job.deliver_api_key.as_deref()),
        ] {
            let (was_provided, value, line) = override_change(input, key, current);
            if !was_provided {
                continue;
            }
            provided += 1;
            let value = value.expect("provided override_change always returns Some");
            if !line.is_empty() {
                changed.push(line);
            }
            match key {
                "provider" => patch.provider = Some(value),
                "model" => patch.model = Some(value),
                "deliver_to" => patch.deliver_to = Some(value),
                _ => patch.deliver_api_key = Some(value),
            }
        }

        if let Some(thinking) = input.get("thinking").and_then(|v| v.as_str()) {
            provided += 1;
            if !matches!(thinking, "off" | "on" | "budget") {
                return Ok(ToolResult::error(format!(
                    "Invalid thinking mode '{thinking}'. Valid: off, on, budget."
                )));
            }
            if thinking != job.thinking {
                patch.thinking = Some(thinking.to_string());
                changed.push(format!("thinking -> {thinking}"));
            }
        }

        if let Some(auto) = input.get("auto_approve").and_then(|v| v.as_bool()) {
            provided += 1;
            if auto != job.auto_approve {
                patch.auto_approve = Some(auto);
                changed.push(format!("auto_approve -> {auto}"));
            }
        }

        if let Some(enabled) = input.get("enabled").and_then(|v| v.as_bool()) {
            provided += 1;
            if enabled != job.enabled {
                patch.enabled = Some(enabled);
                changed.push(format!("enabled -> {enabled}"));
            }
        }

        if provided == 0 {
            return Ok(ToolResult::error(
                "Nothing to update: provide at least one field to change (name, cron, tz, prompt, \
                 provider, model, thinking, auto_approve, deliver_to, deliver_api_key, enabled)."
                    .to_string(),
            ));
        }

        if changed.is_empty() {
            return Ok(ToolResult::success(format!(
                "Cron job '{}' (id={}) unchanged: every provided value already matches.",
                job.name, job.id
            )));
        }

        // A changed schedule or timezone must recompute the next fire time:
        // NULL it and let the scheduler recalculate on the next tick.
        patch.reset_next_run = schedule_changed || tz_changed;

        let updated = self
            .repo
            .update_fields(&job.id.to_string(), patch)
            .await
            .map_err(|e| super::error::ToolError::Execution(e.to_string()))?;

        if !updated {
            return Ok(ToolResult::error(format!(
                "Failed to update cron job '{}' (id={}).",
                job.name, job.id
            )));
        }

        let mut out = format!("Cron job '{}' (id={}) updated:\n", job.name, job.id);
        for line in &changed {
            out.push_str(&format!("  {line}\n"));
        }

        if schedule_changed || tz_changed {
            let effective_cron = input
                .get("cron")
                .and_then(|v| v.as_str())
                .unwrap_or(&job.cron_expr);
            // Both were validated above, so this cannot fail.
            if let Some(tz) = crate::cron::parse_timezone(&effective_tz) {
                let next_runs =
                    crate::cron::format_upcoming(effective_cron, tz, 3, chrono::Utc::now());
                out.push_str(&format!(
                    "  Next runs (recomputed):\n{next_runs}\n\nVerify the Next runs match what you intended (day-of-week is Sun-Sat, DST handled) before confirming to the user."
                ));
            }
        }

        Ok(ToolResult::success(out))
    }

    async fn list_jobs(&self) -> Result<ToolResult> {
        let jobs = self
            .repo
            .list_all()
            .await
            .map_err(|e| super::error::ToolError::Execution(e.to_string()))?;

        if jobs.is_empty() {
            return Ok(ToolResult::success("No cron jobs configured.".to_string()));
        }

        let lines: Vec<String> = jobs
            .iter()
            .map(|j| {
                let status = if j.enabled { "enabled" } else { "disabled" };
                let deliver = j.deliver_to.as_deref().unwrap_or("none");
                let last = j
                    .last_run_at
                    .map(|d| d.format("%Y-%m-%d %H:%M UTC").to_string())
                    .unwrap_or_else(|| "never".to_string());
                format!(
                    "- [{}] {} (id={})\n    Schedule: {} ({})\n    Deliver: {}\n    Last run: {}\n    Prompt: {}",
                    status,
                    j.name,
                    j.id,
                    j.cron_expr,
                    j.timezone,
                    deliver,
                    last,
                    truncate(&j.prompt, 80),
                )
            })
            .collect();

        Ok(ToolResult::success(format!(
            "Cron jobs ({}):\n{}",
            jobs.len(),
            lines.join("\n")
        )))
    }

    async fn delete_job(&self, input: &Value) -> Result<ToolResult> {
        let job_id = match input.get("job_id").and_then(|v| v.as_str()) {
            Some(id) if !id.is_empty() => id,
            _ => {
                return Ok(ToolResult::error(
                    "'job_id' is required for delete".to_string(),
                ));
            }
        };

        // Step 1: Look up the job to show what will be deleted
        let job = match self.repo.find_by_id(job_id).await {
            Ok(Some(j)) => j,
            Ok(None) => {
                // Try by name
                match self.repo.find_by_name(job_id).await {
                    Ok(Some(j)) => j,
                    _ => {
                        return Ok(ToolResult::error(format!(
                            "No cron job found with ID or name '{job_id}'."
                        )));
                    }
                }
            }
            Err(e) => {
                return Ok(ToolResult::error(format!("Error looking up cron job: {e}")));
            }
        };

        let confirm = input
            .get("confirm")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        if !confirm {
            // Safety check: show job details, do NOT delete
            let deliver = job.deliver_to.as_deref().unwrap_or("none");
            return Ok(ToolResult::success(format!(
                "⚠️  DELETE REQUEST (not yet executed)\n\n\
                 Job: {} (id={})\n\
                 Schedule: {} ({})\n\
                 Deliver: {}\n\
                 Prompt: {}\n\n\
                 To confirm deletion, call again with confirm=true.\n\
                 Use 'disable' to temporarily pause without losing the job.",
                job.name,
                job.id,
                job.cron_expr,
                job.timezone,
                deliver,
                truncate(&job.prompt, 120)
            )));
        }

        // Step 2: Back up all jobs before deleting
        if let Ok(all_jobs) = self.repo.list_all().await {
            self.backup_jobs(&all_jobs).await;
        }

        // Step 3: Actually delete
        let deleted = self
            .repo
            .delete(&job.id.to_string())
            .await
            .map_err(|e| super::error::ToolError::Execution(e.to_string()))?;

        if deleted {
            Ok(ToolResult::success(format!(
                "Cron job '{}' (id={}) deleted. Backup saved to ~/.opencrabs/backups/cron/",
                job.name, job.id
            )))
        } else {
            Ok(ToolResult::error(format!(
                "Failed to delete cron job '{}' (id={}).",
                job.name, job.id
            )))
        }
    }

    async fn backup_jobs(&self, jobs: &[CronJob]) {
        use std::fs;
        use std::path::PathBuf;

        let home = dirs::home_dir().unwrap_or_else(|| PathBuf::from("."));
        let backup_dir = home.join(".opencrabs/backups/cron");
        if fs::create_dir_all(&backup_dir).is_err() {
            return;
        }

        let timestamp = chrono::Utc::now().format("%Y%m%d-%H%M%S");
        let backup_path = backup_dir.join(format!("cron-jobs-{timestamp}.json"));

        if let Ok(json) = serde_json::to_string_pretty(jobs) {
            let _ = fs::write(&backup_path, json);
        }

        // Rotate: keep only the 10 most recent backups
        if let Ok(entries) = fs::read_dir(&backup_dir) {
            let mut files: Vec<_> = entries
                .filter_map(|e| e.ok())
                .filter(|e| {
                    e.file_name()
                        .to_str()
                        .map(|n| n.starts_with("cron-jobs-") && n.ends_with(".json"))
                        .unwrap_or(false)
                })
                .collect();
            files.sort_by_key(|e| e.file_name());
            if files.len() > 10 {
                for old in &files[..files.len() - 10] {
                    let _ = fs::remove_file(old.path());
                }
            }
        }
    }

    async fn toggle_job(&self, input: &Value, enabled: bool) -> Result<ToolResult> {
        let job_id = match input.get("job_id").and_then(|v| v.as_str()) {
            Some(id) if !id.is_empty() => id,
            _ => {
                return Ok(ToolResult::error(
                    "'job_id' is required for enable/disable".to_string(),
                ));
            }
        };

        let updated = self
            .repo
            .set_enabled(job_id, enabled)
            .await
            .map_err(|e| super::error::ToolError::Execution(e.to_string()))?;

        if updated {
            let state = if enabled { "enabled" } else { "disabled" };
            Ok(ToolResult::success(format!("Cron job {job_id} {state}.")))
        } else {
            Ok(ToolResult::error(format!(
                "No cron job found with ID '{job_id}'."
            )))
        }
    }

    async fn test_job(&self, input: &Value) -> Result<ToolResult> {
        let job_id = match input.get("job_id").and_then(|v| v.as_str()) {
            Some(id) if !id.is_empty() => id,
            _ => {
                // Also accept name
                match input.get("name").and_then(|v| v.as_str()) {
                    Some(name) if !name.is_empty() => {
                        if let Ok(Some(job)) = self.repo.find_by_name(name).await {
                            return self.trigger_by_id(&job.id.to_string(), &job.name).await;
                        }
                        return Ok(ToolResult::error(format!(
                            "No cron job found with name '{name}'."
                        )));
                    }
                    _ => {
                        return Ok(ToolResult::error(
                            "'job_id' or 'name' is required for test".to_string(),
                        ));
                    }
                }
            }
        };

        // Try ID first, then name
        if let Ok(Some(job)) = self.repo.find_by_id(job_id).await {
            return self.trigger_by_id(&job.id.to_string(), &job.name).await;
        }
        if let Ok(Some(job)) = self.repo.find_by_name(job_id).await {
            return self.trigger_by_id(&job.id.to_string(), &job.name).await;
        }

        Ok(ToolResult::error(format!(
            "No cron job found with ID or name '{job_id}'."
        )))
    }

    async fn trigger_by_id(&self, id: &str, name: &str) -> Result<ToolResult> {
        let triggered = self
            .repo
            .trigger_now(id)
            .await
            .map_err(|e| super::error::ToolError::Execution(e.to_string()))?;

        if triggered {
            Ok(ToolResult::success(format!(
                "Cron job '{name}' (id={id}) triggered. It will execute on the next scheduler tick (within 60 seconds). Check logs for execution status."
            )))
        } else {
            Ok(ToolResult::error(format!(
                "Failed to trigger cron job '{id}'."
            )))
        }
    }
}

fn truncate(s: &str, max: usize) -> String {
    if s.chars().count() <= max {
        s.to_string()
    } else {
        format!("{}...", s.chars().take(max).collect::<String>())
    }
}

/// Helper for the optional string overrides on update (provider, model,
/// deliver_to, deliver_api_key). Returns whether the field was provided, the
/// tri-state value to store in the patch (`Some(None)` = clear back to NULL,
/// `Some(Some(v))` = set), and a human-readable change line that stays empty
/// when the value is unchanged.
fn override_change(
    input: &Value,
    key: &str,
    current: Option<&str>,
) -> (bool, Option<Option<String>>, String) {
    let Some(raw) = input.get(key).and_then(|v| v.as_str()) else {
        return (false, None, String::new());
    };
    let new_val: Option<String> = if raw.is_empty() {
        None
    } else {
        Some(raw.to_string())
    };
    let differs = match (&new_val, current) {
        (Some(n), Some(c)) => n != c,
        (None, None) => false,
        _ => true,
    };
    let line = if differs {
        match &new_val {
            Some(n) => format!("{key} -> {n}"),
            None => format!("{key} -> (cleared)"),
        }
    } else {
        String::new()
    };
    (true, Some(new_val), line)
}