supercode-harness 0.4.2

The optional native Supercode agent and tool harness
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
//! Deterministic execution cursor for imported Claude cron and wakeup state.
//!
//! This module never reads the system clock and never sleeps. Callers supply
//! integer Unix seconds to activation, inspection, reconciliation, and claim
//! operations. Cron fields are interpreted in UTC. Claude's native scheduler
//! may use a local wall-clock timezone; that offset is not present in the
//! imported runtime records, so UTC is the explicit persisted residue here.

use std::collections::{BTreeMap, BTreeSet};

use serde::{Deserialize, Serialize};

use crate::claude_runtime_state::{
    ClaudeCronJob, ClaudeRuntimeExecutionState, ClaudeRuntimeManifest, ClaudeWakeup,
};
use crate::{Error, Result};

fn default_timezone() -> String {
    "UTC".to_string()
}

/// Persisted scheduler cursor. Empty/default state keeps pre-scheduler
/// manifests backward compatible and inert.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ClaudeRuntimeSchedulerState {
    /// Explicit activation instant supplied by the embedding harness.
    #[serde(default)]
    pub activated_at_unix: Option<i64>,
    /// Cron interpretation timezone. Currently always `UTC`; persisted so
    /// the limitation is visible rather than implicit.
    #[serde(default = "default_timezone")]
    pub timezone: String,
    /// Per-cron next-fire and expiry cursors.
    #[serde(default)]
    pub cron_jobs: Vec<ClaudeCronScheduleState>,
    /// Per-wakeup one-shot due cursors.
    #[serde(default)]
    pub wakeups: Vec<ClaudeWakeupScheduleState>,
    /// Claimed prompts awaiting a completed provider turn. Persisting these
    /// before delivery closes the crash window that would otherwise lose a
    /// one-shot job after its cursor was removed.
    #[serde(default)]
    pub deliveries: Vec<ClaudeRuntimeDeliveryState>,
}

impl Default for ClaudeRuntimeSchedulerState {
    fn default() -> Self {
        Self {
            activated_at_unix: None,
            timezone: default_timezone(),
            cron_jobs: Vec::new(),
            wakeups: Vec::new(),
            deliveries: Vec::new(),
        }
    }
}

/// Persisted execution cursor for one Claude cron.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ClaudeCronScheduleState {
    /// Claude-assigned cron identifier.
    pub id: String,
    /// Next minute eligible for a claim, as Unix seconds.
    pub next_due_unix: i64,
    /// Absolute expiry instant, when the native job carried one.
    #[serde(default)]
    pub expires_at_unix: Option<i64>,
}

/// Persisted execution cursor for one Claude scheduled wakeup.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ClaudeWakeupScheduleState {
    /// Tool-use identifier of the native `ScheduleWakeup` call.
    pub tool_use_id: String,
    /// One-shot due instant as Unix seconds.
    pub due_unix: i64,
}

/// Stable trigger ordering: due time, then kind, then source id.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ClaudeRuntimeTriggerKind {
    /// A queued user prompt remained pending at the import boundary.
    Queue,
    /// A `CronCreate` job became due.
    Cron,
    /// A `ScheduleWakeup` request became due.
    Wakeup,
}

/// One prompt made executable by an explicit scheduler claim.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ClaudeRuntimeTrigger {
    /// Original scheduler deadline as Unix seconds.
    pub due_unix: i64,
    /// Native scheduler primitive that produced the prompt.
    pub kind: ClaudeRuntimeTriggerKind,
    /// Queue ordinal, cron id, or wakeup tool-use id.
    pub id: String,
    /// Prompt to inject; wakeups without prompt/reason remain `None`.
    pub prompt: Option<String>,
}

/// Persisted claimed-but-unacknowledged prompt.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ClaudeRuntimeDeliveryState {
    /// Native trigger retained byte-for-byte until acknowledgement.
    pub trigger: ClaudeRuntimeTrigger,
    /// Earliest retry instant after a delivery failure/interruption.
    pub retry_at_unix: i64,
}

impl ClaudeRuntimeTrigger {
    fn order_key(&self) -> (i64, ClaudeRuntimeTriggerKind, &str) {
        (self.due_unix, self.kind, self.id.as_str())
    }
}

impl ClaudeRuntimeManifest {
    /// Validate every imported schedule and activate it at `now_unix`.
    /// Existing cron history is never replayed: each first cron cursor is the
    /// first matching UTC minute strictly after activation. Pending queue
    /// prompts and overdue wakeups become due exactly at activation and
    /// therefore claim once immediately.
    pub fn activate_scheduler(&mut self, now_unix: i64) -> Result<()> {
        if self.execution_state == ClaudeRuntimeExecutionState::Active {
            return Err(Error::Other(
                "Claude runtime scheduler is already active".into(),
            ));
        }
        let (scheduler, retained_crons) = build_scheduler(self, now_unix, false)?;
        self.active_crons = retained_crons;
        self.scheduler = scheduler;
        self.execution_state = ClaudeRuntimeExecutionState::Active;
        Ok(())
    }

    /// Reconcile active scheduler metadata after a deterministic in-memory
    /// CronCreate/CronDelete/ScheduleWakeup mutation. Existing cursors are
    /// preserved; only new jobs/wakeups are seeded from `now_unix`, and
    /// deleted/expired entries disappear.
    pub fn reconcile_scheduler(&mut self, now_unix: i64) -> Result<()> {
        self.require_active()?;
        let (scheduler, retained_crons) = build_scheduler(self, now_unix, true)?;
        self.active_crons = retained_crons;
        self.scheduler = scheduler;
        Ok(())
    }

    /// Return the earliest executable trigger without mutating state.
    pub fn next_due(&self, now_unix: i64) -> Result<Option<ClaudeRuntimeTrigger>> {
        self.require_active()?;
        let mut due = scheduler_triggers(self, now_unix, false)?;
        due.extend(self.scheduler.deliveries.iter().map(|delivery| {
            let mut trigger = delivery.trigger.clone();
            trigger.due_unix = delivery.retry_at_unix;
            trigger
        }));
        due.sort_by(|a, b| a.order_key().cmp(&b.order_key()));
        Ok(due.into_iter().next())
    }

    /// Claim every trigger due at or before `now_unix`, in stable order.
    /// Recurring crons advance once to the first tick strictly after `now`
    /// (no missed-tick catch-up); queued prompts, one-shot crons, and wakeups
    /// are removed from their source state after becoming durable deliveries.
    pub fn claim_due(&mut self, now_unix: i64) -> Result<Vec<ClaudeRuntimeTrigger>> {
        self.require_active()?;
        let mut claimed: Vec<_> = self
            .scheduler
            .deliveries
            .iter()
            .filter(|delivery| delivery.retry_at_unix <= now_unix)
            .map(|delivery| delivery.trigger.clone())
            .collect();
        let mut newly_claimed = scheduler_triggers(self, now_unix, true)?;
        newly_claimed.sort_by(|a, b| a.order_key().cmp(&b.order_key()));

        let claimed_crons: BTreeSet<String> = newly_claimed
            .iter()
            .filter(|item| item.kind == ClaudeRuntimeTriggerKind::Cron)
            .map(|item| item.id.clone())
            .collect();
        let claimed_queue: BTreeSet<String> = newly_claimed
            .iter()
            .filter(|item| item.kind == ClaudeRuntimeTriggerKind::Queue)
            .map(|item| item.id.clone())
            .collect();
        let claimed_wakeups: BTreeSet<String> = newly_claimed
            .iter()
            .filter(|item| item.kind == ClaudeRuntimeTriggerKind::Wakeup)
            .map(|item| item.id.clone())
            .collect();

        let mut next_crons = Vec::new();
        let mut retained_jobs = Vec::new();
        for job in std::mem::take(&mut self.active_crons) {
            let Some(cursor) = self.scheduler.cron_jobs.iter().find(|c| c.id == job.id) else {
                return Err(Error::Other(format!(
                    "active Claude cron `{}` has no scheduler cursor",
                    job.id
                )));
            };
            if cursor
                .expires_at_unix
                .is_some_and(|expiry| now_unix >= expiry)
            {
                continue;
            }
            if !claimed_crons.contains(&job.id) {
                next_crons.push(cursor.clone());
                retained_jobs.push(job);
                continue;
            }
            if !job.recurring {
                continue;
            }
            let parsed = CronSchedule::parse(&job.schedule)?;
            let next = parsed.next_after(now_unix)?;
            if cursor.expires_at_unix.is_some_and(|expiry| next >= expiry) {
                continue;
            }
            next_crons.push(ClaudeCronScheduleState {
                id: job.id.clone(),
                next_due_unix: next,
                expires_at_unix: cursor.expires_at_unix,
            });
            retained_jobs.push(job);
        }
        self.active_crons = retained_jobs;
        self.scheduler.cron_jobs = next_crons;
        self.pending_wakeups
            .retain(|wakeup| !claimed_wakeups.contains(&wakeup.tool_use_id));
        self.scheduler
            .wakeups
            .retain(|wakeup| !claimed_wakeups.contains(&wakeup.tool_use_id));
        if !claimed_queue.is_empty() {
            let expected: BTreeSet<String> = (0..self.queue.pending.len())
                .map(|index| queue_trigger_id(&self.queue, index))
                .collect::<Result<_>>()?;
            if claimed_queue != expected {
                return Err(Error::Other(
                    "Claude queue claim did not cover the complete pending FIFO".into(),
                ));
            }
            self.queue.pending.clear();
        }
        for trigger in &newly_claimed {
            self.scheduler.deliveries.push(ClaudeRuntimeDeliveryState {
                trigger: trigger.clone(),
                retry_at_unix: now_unix,
            });
        }
        self.scheduler
            .deliveries
            .sort_by(|a, b| a.trigger.order_key().cmp(&b.trigger.order_key()));
        claimed.extend(newly_claimed);
        claimed.sort_by(|a, b| a.order_key().cmp(&b.order_key()));
        Ok(claimed)
    }

    /// Acknowledge one successful scheduled turn and remove its durable
    /// delivery record.
    pub fn complete_delivery(&mut self, kind: ClaudeRuntimeTriggerKind, id: &str) -> Result<()> {
        self.require_active()?;
        let before = self.scheduler.deliveries.len();
        self.scheduler
            .deliveries
            .retain(|delivery| delivery.trigger.kind != kind || delivery.trigger.id != id);
        if self.scheduler.deliveries.len() == before {
            return Err(Error::Other(format!(
                "unknown Claude runtime delivery `{kind:?}` `{id}`"
            )));
        }
        Ok(())
    }

    /// Retain a failed/interrupted delivery and delay its next attempt.
    pub fn defer_delivery(
        &mut self,
        kind: ClaudeRuntimeTriggerKind,
        id: &str,
        retry_at_unix: i64,
    ) -> Result<()> {
        self.require_active()?;
        let Some(delivery) = self
            .scheduler
            .deliveries
            .iter_mut()
            .find(|delivery| delivery.trigger.kind == kind && delivery.trigger.id == id)
        else {
            return Err(Error::Other(format!(
                "unknown Claude runtime delivery `{kind:?}` `{id}`"
            )));
        };
        delivery.retry_at_unix = retry_at_unix;
        Ok(())
    }

    fn require_active(&self) -> Result<()> {
        if self.execution_state != ClaudeRuntimeExecutionState::Active {
            return Err(Error::Other(
                "Claude runtime scheduler is paused; activate it explicitly first".into(),
            ));
        }
        if self.scheduler.activated_at_unix.is_none() {
            return Err(Error::Other(
                "active Claude runtime manifest has no scheduler activation metadata".into(),
            ));
        }
        Ok(())
    }
}

fn build_scheduler(
    manifest: &ClaudeRuntimeManifest,
    now_unix: i64,
    preserve_existing: bool,
) -> Result<(ClaudeRuntimeSchedulerState, Vec<ClaudeCronJob>)> {
    for index in 0..manifest.queue.pending.len() {
        queue_trigger_id(&manifest.queue, index)?;
    }
    let old_crons: BTreeMap<&str, &ClaudeCronScheduleState> = manifest
        .scheduler
        .cron_jobs
        .iter()
        .map(|cursor| (cursor.id.as_str(), cursor))
        .collect();
    let old_wakeups: BTreeMap<&str, &ClaudeWakeupScheduleState> = manifest
        .scheduler
        .wakeups
        .iter()
        .map(|cursor| (cursor.tool_use_id.as_str(), cursor))
        .collect();

    let mut seen = BTreeSet::new();
    let mut cron_jobs = Vec::new();
    let mut retained_crons = Vec::new();
    for job in &manifest.active_crons {
        if !seen.insert(job.id.as_str()) {
            return Err(Error::Other(format!(
                "duplicate active Claude cron id `{}`",
                job.id
            )));
        }
        let parsed = CronSchedule::parse(&job.schedule)?;
        let expires_at_unix = expiry_for(job)?;
        if expires_at_unix.is_some_and(|expiry| now_unix >= expiry) {
            continue;
        }
        let next_due_unix = if preserve_existing {
            old_crons
                .get(job.id.as_str())
                .map(|cursor| cursor.next_due_unix)
                .unwrap_or(parsed.next_after(now_unix)?)
        } else {
            parsed.next_after(now_unix)?
        };
        if expires_at_unix.is_some_and(|expiry| next_due_unix >= expiry) {
            continue;
        }
        cron_jobs.push(ClaudeCronScheduleState {
            id: job.id.clone(),
            next_due_unix,
            expires_at_unix,
        });
        retained_crons.push(job.clone());
    }

    let mut wakeups = Vec::new();
    let mut seen_wakeups = BTreeSet::new();
    for wakeup in &manifest.pending_wakeups {
        if !seen_wakeups.insert(wakeup.tool_use_id.as_str()) {
            return Err(Error::Other(format!(
                "duplicate pending Claude wakeup id `{}`",
                wakeup.tool_use_id
            )));
        }
        let due_unix = if preserve_existing {
            old_wakeups
                .get(wakeup.tool_use_id.as_str())
                .map(|cursor| cursor.due_unix)
                .unwrap_or(wakeup_due(wakeup, now_unix)?)
        } else {
            wakeup_due(wakeup, now_unix)?
        };
        wakeups.push(ClaudeWakeupScheduleState {
            tool_use_id: wakeup.tool_use_id.clone(),
            due_unix,
        });
    }
    cron_jobs.sort_by(|a, b| a.id.cmp(&b.id));
    wakeups.sort_by(|a, b| a.tool_use_id.cmp(&b.tool_use_id));
    Ok((
        ClaudeRuntimeSchedulerState {
            activated_at_unix: Some(
                manifest
                    .scheduler
                    .activated_at_unix
                    .filter(|_| preserve_existing)
                    .unwrap_or(now_unix),
            ),
            timezone: default_timezone(),
            cron_jobs,
            wakeups,
            deliveries: if preserve_existing {
                manifest.scheduler.deliveries.clone()
            } else {
                Vec::new()
            },
        },
        retained_crons,
    ))
}

fn expiry_for(job: &ClaudeCronJob) -> Result<Option<i64>> {
    let Some(seconds) = job.expires_after_seconds else {
        return Ok(None);
    };
    let created = parse_created(job.created_at.as_deref(), "cron", &job.id)?;
    let seconds = i64::try_from(seconds).map_err(|_| {
        Error::Other(format!(
            "Claude cron `{}` expiry exceeds supported Unix time",
            job.id
        ))
    })?;
    created.checked_add(seconds).map(Some).ok_or_else(|| {
        Error::Other(format!(
            "Claude cron `{}` expiry overflows Unix time",
            job.id
        ))
    })
}

fn wakeup_due(wakeup: &ClaudeWakeup, now_unix: i64) -> Result<i64> {
    let created = parse_created(wakeup.created_at.as_deref(), "wakeup", &wakeup.tool_use_id)?;
    let delay = i64::try_from(wakeup.delay_seconds).map_err(|_| {
        Error::Other(format!(
            "Claude wakeup `{}` delay exceeds supported Unix time",
            wakeup.tool_use_id
        ))
    })?;
    let due = created.checked_add(delay).ok_or_else(|| {
        Error::Other(format!(
            "Claude wakeup `{}` due time overflows Unix time",
            wakeup.tool_use_id
        ))
    })?;
    Ok(due.max(now_unix))
}

fn parse_created(value: Option<&str>, kind: &str, id: &str) -> Result<i64> {
    let value = value.ok_or_else(|| {
        Error::Other(format!(
            "Claude {kind} `{id}` has no creation timestamp for deterministic activation"
        ))
    })?;
    crate::sidecar::rfc3339_to_ms(value)
        .map(|ms| ms.div_euclid(1000))
        .ok_or_else(|| {
            Error::Other(format!(
                "Claude {kind} `{id}` has invalid RFC3339 timestamp `{value}`"
            ))
        })
}

fn scheduler_triggers(
    manifest: &ClaudeRuntimeManifest,
    now_unix: i64,
    only_due: bool,
) -> Result<Vec<ClaudeRuntimeTrigger>> {
    let jobs: BTreeMap<&str, &ClaudeCronJob> = manifest
        .active_crons
        .iter()
        .map(|job| (job.id.as_str(), job))
        .collect();
    let wakeups: BTreeMap<&str, &ClaudeWakeup> = manifest
        .pending_wakeups
        .iter()
        .map(|wakeup| (wakeup.tool_use_id.as_str(), wakeup))
        .collect();
    let mut out = Vec::new();
    let queue_due = manifest.scheduler.activated_at_unix.ok_or_else(|| {
        Error::Other("active Claude runtime manifest has no scheduler activation metadata".into())
    })?;
    if !only_due || queue_due <= now_unix {
        for (index, prompt) in manifest.queue.pending.iter().enumerate() {
            out.push(ClaudeRuntimeTrigger {
                due_unix: queue_due,
                kind: ClaudeRuntimeTriggerKind::Queue,
                id: queue_trigger_id(&manifest.queue, index)?,
                prompt: Some(prompt.clone()),
            });
        }
    }
    for cursor in &manifest.scheduler.cron_jobs {
        let job = jobs.get(cursor.id.as_str()).ok_or_else(|| {
            Error::Other(format!(
                "scheduler cursor references missing Claude cron `{}`",
                cursor.id
            ))
        })?;
        if cursor
            .expires_at_unix
            .is_some_and(|expiry| now_unix >= expiry)
        {
            continue;
        }
        if !only_due || cursor.next_due_unix <= now_unix {
            out.push(ClaudeRuntimeTrigger {
                due_unix: cursor.next_due_unix,
                kind: ClaudeRuntimeTriggerKind::Cron,
                id: cursor.id.clone(),
                prompt: Some(job.prompt.clone()),
            });
        }
    }
    for cursor in &manifest.scheduler.wakeups {
        let wakeup = wakeups.get(cursor.tool_use_id.as_str()).ok_or_else(|| {
            Error::Other(format!(
                "scheduler cursor references missing Claude wakeup `{}`",
                cursor.tool_use_id
            ))
        })?;
        if !only_due || cursor.due_unix <= now_unix {
            out.push(ClaudeRuntimeTrigger {
                due_unix: cursor.due_unix,
                kind: ClaudeRuntimeTriggerKind::Wakeup,
                id: cursor.tool_use_id.clone(),
                prompt: wakeup.prompt.clone().or_else(|| wakeup.reason.clone()),
            });
        }
    }
    Ok(out)
}

fn queue_trigger_id(
    queue: &crate::claude_runtime_state::ClaudeQueueState,
    index: usize,
) -> Result<String> {
    let pending = u64::try_from(queue.pending.len())
        .map_err(|_| Error::Other("Claude pending queue length exceeds u64".into()))?;
    let index = u64::try_from(index)
        .map_err(|_| Error::Other("Claude pending queue index exceeds u64".into()))?;
    let first_ordinal = queue.enqueued.checked_sub(pending).ok_or_else(|| {
        Error::Other(format!(
            "Claude queue has {} pending prompts but only {} enqueue records",
            queue.pending.len(),
            queue.enqueued
        ))
    })?;
    let ordinal = first_ordinal
        .checked_add(index)
        .ok_or_else(|| Error::Other("Claude queue ordinal overflows u64".into()))?;
    Ok(format!("queue-{ordinal:020}"))
}

#[derive(Debug, Clone)]
struct CronField {
    allowed: Vec<bool>,
}

impl CronField {
    fn parse(text: &str, min: u32, max: u32, dow: bool) -> Result<Self> {
        if text.is_empty() {
            return Err(Error::Other("empty cron field".into()));
        }
        let mut allowed = vec![false; (max - min + 1) as usize];
        for item in text.split(',') {
            if item.is_empty() {
                return Err(Error::Other(format!(
                    "invalid empty item in cron field `{text}`"
                )));
            }
            let mut parts = item.split('/');
            let base = parts.next().unwrap_or_default();
            let step = parts
                .next()
                .map(|value| value.parse::<u32>())
                .transpose()
                .map_err(|_| Error::Other(format!("invalid cron step in `{item}`")))?
                .unwrap_or(1);
            if parts.next().is_some() || step == 0 {
                return Err(Error::Other(format!("invalid cron step in `{item}`")));
            }
            let (start, end) = if base == "*" {
                (min, max)
            } else if let Some((start, end)) = base.split_once('-') {
                (
                    parse_cron_num(start, min, max, dow)?,
                    parse_cron_num(end, min, max, dow)?,
                )
            } else {
                let start = parse_cron_num(base, min, max, dow)?;
                (start, if item.contains('/') { max } else { start })
            };
            if start > end {
                return Err(Error::Other(format!(
                    "descending cron range `{base}` is unsupported"
                )));
            }
            let mut value = start;
            while value <= end {
                let normalized = if dow && value == 7 { 0 } else { value };
                allowed[(normalized - min) as usize] = true;
                let Some(next) = value.checked_add(step) else {
                    break;
                };
                value = next;
            }
        }
        if !allowed.iter().any(|allowed| *allowed) {
            return Err(Error::Other(format!(
                "cron field `{text}` matches no values"
            )));
        }
        Ok(Self { allowed })
    }

    fn contains(&self, value: u32, min: u32) -> bool {
        self.allowed
            .get((value - min) as usize)
            .copied()
            .unwrap_or(false)
    }

    fn unrestricted(&self) -> bool {
        self.allowed.iter().all(|allowed| *allowed)
    }
}

fn parse_cron_num(text: &str, min: u32, max: u32, dow: bool) -> Result<u32> {
    let value = text
        .parse::<u32>()
        .map_err(|_| Error::Other(format!("invalid cron number `{text}`")))?;
    let upper = if dow { 7 } else { max };
    if value < min || value > upper {
        return Err(Error::Other(format!(
            "cron number `{value}` is outside {min}..={upper}"
        )));
    }
    Ok(value)
}

#[derive(Debug, Clone)]
struct CronSchedule {
    minute: CronField,
    hour: CronField,
    day_of_month: CronField,
    month: CronField,
    day_of_week: CronField,
}

impl CronSchedule {
    fn parse(schedule: &str) -> Result<Self> {
        let fields: Vec<&str> = schedule.split_whitespace().collect();
        if fields.len() != 5 {
            return Err(Error::Other(format!(
                "invalid Claude cron `{schedule}`: expected exactly 5 fields"
            )));
        }
        Ok(Self {
            minute: CronField::parse(fields[0], 0, 59, false)?,
            hour: CronField::parse(fields[1], 0, 23, false)?,
            day_of_month: CronField::parse(fields[2], 1, 31, false)?,
            month: CronField::parse(fields[3], 1, 12, false)?,
            day_of_week: CronField::parse(fields[4], 0, 6, true)?,
        })
    }

    fn next_after(&self, after_unix: i64) -> Result<i64> {
        let start_minute = after_unix
            .div_euclid(60)
            .checked_add(1)
            .ok_or_else(|| Error::Other("cron search overflows Unix time".into()))?;
        // Eight years covers the Gregorian leap cycle plus a safety margin.
        // If no minute matches, the expression is calendar-impossible.
        const SEARCH_MINUTES: i64 = 8 * 366 * 24 * 60;
        for delta in 0..SEARCH_MINUTES {
            let unix = start_minute
                .checked_add(delta)
                .and_then(|minute| minute.checked_mul(60))
                .ok_or_else(|| Error::Other("cron search overflows Unix time".into()))?;
            if self.matches(unix) {
                return Ok(unix);
            }
        }
        Err(Error::Other(
            "cron expression has no matching UTC minute within eight years".into(),
        ))
    }

    fn matches(&self, unix: i64) -> bool {
        let days = unix.div_euclid(86_400);
        let seconds = unix.rem_euclid(86_400);
        let (year, month, day) = civil_from_days(days);
        let _ = year;
        let hour = (seconds / 3600) as u32;
        let minute = ((seconds % 3600) / 60) as u32;
        let dow = (days + 4).rem_euclid(7) as u32;
        let dom_match = self.day_of_month.contains(day, 1);
        let dow_match = self.day_of_week.contains(dow, 0);
        let day_match = match (
            self.day_of_month.unrestricted(),
            self.day_of_week.unrestricted(),
        ) {
            (true, true) => true,
            (true, false) => dow_match,
            (false, true) => dom_match,
            (false, false) => dom_match || dow_match,
        };
        self.minute.contains(minute, 0)
            && self.hour.contains(hour, 0)
            && self.month.contains(month, 1)
            && day_match
    }
}

// Howard Hinnant's public-domain civil calendar conversion.
fn civil_from_days(days: i64) -> (i64, u32, u32) {
    let z = days + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 }.div_euclid(146_097);
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let mut year = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let day = doy - (153 * mp + 2) / 5 + 1;
    let month = if mp < 10 { mp + 3 } else { mp - 9 };
    year += (month <= 2) as i64;
    (year, month as u32, day as u32)
}