beads_rust 0.5.3

Agent-first issue tracker (SQLite + JSONL)
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
//! Time and date parsing utilities.

use crate::error::{BeadsError, Result};
use chrono::{DateTime, Duration, Local, NaiveDate, NaiveTime, TimeZone, Utc};
use std::num::IntErrorKind;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RelativeTimeError {
    InvalidUnit,
    OutOfRange,
}

/// Parse a flexible time specification into a `DateTime<Utc>`.
///
/// Supports:
/// - RFC3339: `2025-01-15T12:00:00Z`, `2025-01-15T12:00:00+00:00`
/// - Simple date: `2025-01-15` (defaults to 9:00 AM local time)
/// - Relative duration: `+1h`, `+2d`, `+1w`, `+30m`
/// - Keywords: `tomorrow`, `next-week`
///
/// # Errors
///
/// Returns an error if:
/// - The time format is invalid or unrecognized
/// - A relative duration has an invalid unit (only m, h, d, w supported)
/// - The local time is ambiguous (e.g., during DST transitions)
///
/// # Panics
///
/// This function does not panic. The internal `unwrap()` calls on `from_hms_opt(9, 0, 0)`
/// are safe because 9:00:00 is always a valid time.
pub fn parse_flexible_timestamp(s: &str, field_name: &str) -> Result<DateTime<Utc>> {
    let s = s.trim();

    // Try RFC3339 first
    if let Some(dt) = parse_rfc3339_timestamp(s) {
        return Ok(dt);
    }

    // Try simple date (YYYY-MM-DD) - default to 9:00 AM local time
    if let Ok(date) = NaiveDate::parse_from_str(s, "%Y-%m-%d") {
        let time = NaiveTime::from_hms_opt(9, 0, 0).unwrap();
        let naive_dt = date.and_time(time);
        return local_to_utc(&naive_dt, field_name);
    }

    match parse_relative_timestamp(s) {
        Ok(Some(dt)) => return Ok(dt),
        Ok(None) => {}
        Err(RelativeTimeError::InvalidUnit) => {
            return Err(BeadsError::validation(
                field_name,
                "invalid unit (use m, h, d, w)",
            ));
        }
        Err(RelativeTimeError::OutOfRange) => {
            return Err(BeadsError::validation(
                field_name,
                "relative duration is out of supported range",
            ));
        }
    }

    // Try keywords
    let now = Local::now();
    match s.to_lowercase().as_str() {
        "today" => {
            let time = NaiveTime::from_hms_opt(17, 0, 0).unwrap();
            let naive_dt = now.date_naive().and_time(time);
            Ok(local_to_utc(&naive_dt, field_name)?)
        }
        "yesterday" => {
            let yesterday = now.date_naive() - Duration::days(1);
            let time = NaiveTime::from_hms_opt(9, 0, 0).unwrap();
            let naive_dt = yesterday.and_time(time);
            Ok(local_to_utc(&naive_dt, field_name)?)
        }
        "tomorrow" => {
            let tomorrow = now.date_naive() + Duration::days(1);
            let time = NaiveTime::from_hms_opt(9, 0, 0).unwrap();
            let naive_dt = tomorrow.and_time(time);
            Ok(local_to_utc(&naive_dt, field_name)?)
        }
        "next-week" | "nextweek" => {
            let next_week = now.date_naive() + Duration::weeks(1);
            let time = NaiveTime::from_hms_opt(9, 0, 0).unwrap();
            let naive_dt = next_week.and_time(time);
            Ok(local_to_utc(&naive_dt, field_name)?)
        }
        _ => Err(BeadsError::validation(
            field_name,
            "invalid time format (try: +1h, -7d, tomorrow, next-week, or 2025-01-15)",
        )),
    }
}

/// Parse a relative time expression into a `DateTime<Utc>`.
///
/// Supports:
/// - Relative duration: `+1h`, `+2d`, `+1w`, `+30m`, `-7d`
/// - Keywords: `today`, `yesterday`, `tomorrow`, `next-week`
///
/// Returns `None` if the input cannot be parsed as a relative time.
#[must_use]
pub fn parse_relative_time(s: &str) -> Option<DateTime<Utc>> {
    let s = s.trim();

    if let Ok(Some(dt)) = parse_relative_timestamp(s) {
        return Some(dt);
    }

    // Try keywords
    let now = Local::now();
    match s.to_lowercase().as_str() {
        "today" => {
            let time = NaiveTime::from_hms_opt(17, 0, 0)?;
            let naive_dt = now.date_naive().and_time(time);
            local_to_utc_opt(&naive_dt)
        }
        "yesterday" => {
            let yesterday = now.date_naive() - Duration::days(1);
            let time = NaiveTime::from_hms_opt(9, 0, 0)?;
            let naive_dt = yesterday.and_time(time);
            local_to_utc_opt(&naive_dt)
        }
        "tomorrow" => {
            let tomorrow = now.date_naive() + Duration::days(1);
            let time = NaiveTime::from_hms_opt(9, 0, 0)?;
            let naive_dt = tomorrow.and_time(time);
            local_to_utc_opt(&naive_dt)
        }
        "next-week" | "nextweek" => {
            let next_week = now.date_naive() + Duration::weeks(1);
            let time = NaiveTime::from_hms_opt(9, 0, 0)?;
            let naive_dt = next_week.and_time(time);
            local_to_utc_opt(&naive_dt)
        }
        _ => None,
    }
}

fn parse_rfc3339_timestamp(s: &str) -> Option<DateTime<Utc>> {
    if let Ok(dt) = DateTime::parse_from_rfc3339(s) {
        return Some(dt.with_timezone(&Utc));
    }

    let normalized = strip_zero_offset_seconds(s)?;
    DateTime::parse_from_rfc3339(&normalized)
        .ok()
        .map(|dt| dt.with_timezone(&Utc))
}

fn strip_zero_offset_seconds(s: &str) -> Option<String> {
    let bytes = s.as_bytes();
    let sign_pos = bytes.len().checked_sub(9)?;
    if !matches!(bytes.get(sign_pos), Some(b'+' | b'-'))
        || bytes.get(sign_pos + 3) != Some(&b':')
        || bytes.get(sign_pos + 6) != Some(&b':')
    {
        return None;
    }

    let offset_digits = [
        bytes.get(sign_pos + 1)?,
        bytes.get(sign_pos + 2)?,
        bytes.get(sign_pos + 4)?,
        bytes.get(sign_pos + 5)?,
        bytes.get(sign_pos + 7)?,
        bytes.get(sign_pos + 8)?,
    ];
    if !offset_digits.iter().all(|byte| byte.is_ascii_digit())
        || bytes.get(sign_pos + 7..sign_pos + 9) != Some(b"00")
    {
        return None;
    }

    Some(s[..bytes.len() - 3].to_string())
}

fn parse_relative_timestamp(
    s: &str,
) -> std::result::Result<Option<DateTime<Utc>>, RelativeTimeError> {
    let Some(rest) = s.strip_prefix(['+', '-'].as_ref()) else {
        return Ok(None);
    };
    let Some(unit_char) = rest.chars().last() else {
        return Ok(None);
    };

    let amount_end = s.len() - unit_char.len_utf8();
    let amount_str = &s[..amount_end];
    let amount = match amount_str.parse::<i64>() {
        Ok(amount) => amount,
        Err(err)
            if matches!(
                err.kind(),
                IntErrorKind::PosOverflow | IntErrorKind::NegOverflow
            ) =>
        {
            return Err(RelativeTimeError::OutOfRange);
        }
        Err(_) => return Ok(None),
    };

    let duration = match unit_char {
        'm' => Duration::try_minutes(amount),
        'h' => Duration::try_hours(amount),
        'd' => Duration::try_days(amount),
        'w' => Duration::try_weeks(amount),
        _ => return Err(RelativeTimeError::InvalidUnit),
    }
    .ok_or(RelativeTimeError::OutOfRange)?;

    Utc::now()
        .checked_add_signed(duration)
        .ok_or(RelativeTimeError::OutOfRange)
        .map(Some)
}

/// Format a duration as a human-readable relative time string (e.g., "2 days ago").
#[must_use]
pub fn format_relative_time(dt: DateTime<Utc>, now: DateTime<Utc>) -> String {
    let duration = if dt > now {
        dt.signed_duration_since(now)
    } else {
        now.signed_duration_since(dt)
    };

    let suffix = if dt > now { "from now" } else { "ago" };

    let seconds = duration.num_seconds();
    if seconds < 60 {
        return "just now".to_string();
    }

    let minutes = duration.num_minutes();
    if minutes < 60 {
        return format!(
            "{} minute{} {}",
            minutes,
            if minutes == 1 { "" } else { "s" },
            suffix
        );
    }

    let hours = duration.num_hours();
    if hours < 24 {
        return format!(
            "{} hour{} {}",
            hours,
            if hours == 1 { "" } else { "s" },
            suffix
        );
    }

    let days = duration.num_days();
    if days < 30 {
        return format!(
            "{} day{} {}",
            days,
            if days == 1 { "" } else { "s" },
            suffix
        );
    }

    if days < 365 {
        #[allow(clippy::cast_possible_truncation)]
        let months = (days as f64 / 30.44).round() as i64;
        let months = months.max(1);
        if months >= 12 {
            return format!("1 year {suffix}");
        }
        return format!(
            "{} month{} {}",
            months,
            if months == 1 { "" } else { "s" },
            suffix
        );
    }

    let years = days / 365;
    let years = years.max(1);
    format!(
        "{} year{} {}",
        years,
        if years == 1 { "" } else { "s" },
        suffix
    )
}

fn local_to_utc(naive_dt: &chrono::NaiveDateTime, field_name: &str) -> Result<DateTime<Utc>> {
    use chrono::LocalResult;
    match Local.from_local_datetime(naive_dt) {
        LocalResult::Single(dt) | LocalResult::Ambiguous(dt, _) => Ok(dt.with_timezone(&Utc)),
        LocalResult::None => {
            // Time doesn't exist (DST gap), push forward by 1 hour
            let shifted = *naive_dt + Duration::hours(1);
            match Local.from_local_datetime(&shifted) {
                LocalResult::Single(dt) | LocalResult::Ambiguous(dt, _) => {
                    Ok(dt.with_timezone(&Utc))
                }
                LocalResult::None => Err(BeadsError::validation(
                    field_name,
                    "invalid local time around DST transition",
                )),
            }
        }
    }
}

fn local_to_utc_opt(naive_dt: &chrono::NaiveDateTime) -> Option<DateTime<Utc>> {
    use chrono::LocalResult;
    match Local.from_local_datetime(naive_dt) {
        LocalResult::Single(dt) | LocalResult::Ambiguous(dt, _) => Some(dt.with_timezone(&Utc)),
        LocalResult::None => {
            let shifted = *naive_dt + Duration::hours(1);
            match Local.from_local_datetime(&shifted) {
                LocalResult::Single(dt) | LocalResult::Ambiguous(dt, _) => {
                    Some(dt.with_timezone(&Utc))
                }
                LocalResult::None => None,
            }
        }
    }
}

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

    #[test]
    fn test_parse_flexible_rfc3339() {
        let result = parse_flexible_timestamp("2025-01-15T12:00:00Z", "test").unwrap();
        assert_eq!(result.year(), 2025);
    }

    #[test]
    fn test_parse_flexible_rfc3339_zero_offset_spellings() {
        let z = parse_flexible_timestamp("2025-01-15T12:00:00Z", "test").unwrap();
        let short_offset = parse_flexible_timestamp("2025-01-15T12:00:00+00:00", "test").unwrap();
        let long_offset = parse_flexible_timestamp("2025-01-15T12:00:00+00:00:00", "test").unwrap();

        assert_eq!(short_offset, z);
        assert_eq!(long_offset, z);
    }

    #[test]
    fn test_parse_flexible_rfc3339_preserves_pre_epoch_nanoseconds() {
        let result = parse_flexible_timestamp("1969-12-31T23:59:59.123456789Z", "test").unwrap();

        assert_eq!(result.timestamp(), -1);
        assert_eq!(result.timestamp_subsec_nanos(), 123_456_789);
    }

    #[test]
    fn test_parse_flexible_rfc3339_rejects_nonzero_offset_seconds() {
        let err = parse_flexible_timestamp("2025-01-15T12:00:00+00:00:01", "test")
            .expect_err("nonzero offset seconds are not supported");

        assert!(err.to_string().contains("invalid time format"));
    }

    #[test]
    fn test_parse_flexible_simple_date() {
        let result = parse_flexible_timestamp("2025-06-20", "test").unwrap();
        assert_eq!(result.year(), 2025);
        assert_eq!(result.month(), 6);
        assert_eq!(result.day(), 20);
    }

    #[test]
    fn test_parse_flexible_relative() {
        let result = parse_flexible_timestamp("+1h", "test").unwrap();
        assert!(result > Utc::now());
    }

    #[test]
    fn test_parse_flexible_relative_negative() {
        let result = parse_flexible_timestamp("-1d", "test").unwrap();
        assert!(result < Utc::now());
    }

    #[test]
    fn test_parse_flexible_relative_does_not_silently_clamp_large_valid_offsets() {
        let before = Utc::now();
        let result = parse_flexible_timestamp("+600000h", "test").unwrap();
        let after = Utc::now();

        assert!(result >= before + Duration::hours(600_000));
        assert!(result <= after + Duration::hours(600_000));
    }

    #[test]
    fn test_parse_flexible_relative_rejects_out_of_range_offsets() {
        let err = parse_flexible_timestamp("+9999999999999999999d", "test")
            .expect_err("overflowing relative duration should be rejected");

        assert!(
            err.to_string()
                .contains("relative duration is out of supported range"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn test_parse_flexible_keywords() {
        let result = parse_flexible_timestamp("tomorrow", "test").unwrap();
        assert!(result > Utc::now());
    }

    #[test]
    fn test_parse_relative_time_positive() {
        let result = parse_relative_time("+1h").unwrap();
        assert!(result > Utc::now());
    }

    #[test]
    fn test_parse_relative_time_negative() {
        let result = parse_relative_time("-7d").unwrap();
        assert!(result < Utc::now());
    }

    #[test]
    fn test_parse_relative_time_does_not_silently_clamp_large_valid_offsets() {
        let before = Utc::now();
        let result = parse_relative_time("+600000m").unwrap();
        let after = Utc::now();

        assert!(result >= before + Duration::minutes(600_000));
        assert!(result <= after + Duration::minutes(600_000));
    }

    #[test]
    fn test_parse_relative_time_rejects_out_of_range_offsets() {
        assert!(parse_relative_time("+9999999999999999999d").is_none());
    }

    #[test]
    fn test_parse_relative_time_invalid() {
        assert!(parse_relative_time("invalid").is_none());
        assert!(parse_relative_time("2025-01-15").is_none());
    }

    #[test]
    fn test_format_relative_time_normalizes_twelve_months_to_year() {
        let now = Utc::now();
        let dt = now - Duration::days(364);
        assert_eq!(format_relative_time(dt, now), "1 year ago");
    }

    #[test]
    fn test_format_relative_time_keeps_midrange_months() {
        let now = Utc::now();
        let dt = now - Duration::days(330);
        assert_eq!(format_relative_time(dt, now), "11 months ago");
    }
}