omni-dev 0.46.0

AI-powered git commit rewriter, PR generator, and MCP server for Jira, Confluence, Datadog, Gmail, and Drive.
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
//! Shared message selection over `manifest.jsonl` for `gmail insert` and
//! `gmail render --archive-dir` (see [`crate::cli::gmail::render`], #1656).
//! This is deliberately **not** Gmail's search query syntax: it filters
//! records already captured locally in `manifest.jsonl`, with no server
//! round-trip, so it only needs a handful of independent predicates rather
//! than a query-language parser. Factored out as its own module (rather
//! than inlined into `insert.rs`) precisely so a second caller could adopt
//! it without duplicating the flags or the validation.

use std::collections::HashSet;
use std::io::Read as _;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use chrono::{DateTime, NaiveDate, NaiveTime, Utc};
use clap::Args;

use crate::cli::gmail::sync::manifest::{Manifest, ManifestRecord};

/// CLI flags selecting which archived messages `gmail insert` acts on, and
/// (with `--archive-dir`) which ones `gmail render` renders.
///
/// Flattened into [`crate::cli::gmail::insert::InsertCommand`] and
/// [`crate::cli::gmail::render::RenderCommand`] via `#[command(flatten)]`.
/// At least one of `all`/`since`/`until`/`id`/`ids_from`/`source_label` is
/// required — enforced in [`Selection::from_args`], not via a
/// `clap::ArgGroup`, since `--id` is a repeatable `Vec` whose "was this flag
/// given at all" state clap groups don't distinguish cleanly from "given
/// with zero values". `--all` combined with any other selector is also
/// rejected there: it means "everything", so pairing it with a narrowing
/// filter is a contradiction worth failing loudly on rather than silently
/// picking a interpretation.
#[derive(Args, Debug, Clone, Default)]
pub struct SelectionArgs {
    /// Selects every non-deleted archived message.
    #[arg(long)]
    pub all: bool,

    /// Selects messages with an internal date on or after this UTC date
    /// (`YYYY-MM-DD`).
    #[arg(long, value_name = "DATE")]
    pub since: Option<String>,

    /// Selects messages with an internal date on or before this UTC date
    /// (`YYYY-MM-DD`), inclusive of the whole day.
    #[arg(long, value_name = "DATE")]
    pub until: Option<String>,

    /// Selects one specific archived message id. Repeatable.
    #[arg(long = "id", value_name = "ID")]
    pub ids: Vec<String>,

    /// Selects message ids listed one per line in FILE (`-` for stdin);
    /// blank lines and `#`-prefixed comments are skipped — the same shape a
    /// `--dry-run` report's ids can be piped back through.
    #[arg(long, value_name = "FILE")]
    pub ids_from: Option<PathBuf>,

    /// Selects messages carrying this Gmail label id in the archived
    /// manifest (a raw label id, e.g. `Label_1` — not the destination
    /// `--label` tag `gmail insert` itself applies).
    #[arg(long, value_name = "LABEL_ID")]
    pub source_label: Option<String>,
}

impl SelectionArgs {
    /// Whether any selector flag was actually given, as opposed to a bare
    /// `SelectionArgs::default()`. `gmail render` uses this to reject
    /// selector flags passed alongside its bare-file-paths mode (which has
    /// no `Selection` involvement at all) rather than silently ignoring
    /// them.
    pub(crate) fn any_given(&self) -> bool {
        self.all
            || self.since.is_some()
            || self.until.is_some()
            || !self.ids.is_empty()
            || self.ids_from.is_some()
            || self.source_label.is_some()
    }
}

/// A validated, ready-to-apply selection — every fallible part of
/// [`SelectionArgs`] (date parsing, `--ids-from` file/stdin reads) is
/// resolved once up front in [`Self::from_args`], so a mistyped `--since`
/// fails in milliseconds rather than after hundreds of inserts.
#[derive(Debug, Default)]
pub(crate) struct Selection {
    all: bool,
    since: Option<DateTime<Utc>>,
    until: Option<DateTime<Utc>>,
    ids: HashSet<String>,
    source_label: Option<String>,
}

impl Selection {
    pub(crate) fn from_args(args: &SelectionArgs) -> Result<Self> {
        let mut ids: HashSet<String> = args.ids.iter().cloned().collect();
        if let Some(path) = &args.ids_from {
            ids.extend(read_ids_from(path)?);
        }

        let narrowing = args.since.is_some()
            || args.until.is_some()
            || !ids.is_empty()
            || args.source_label.is_some();
        anyhow::ensure!(
            !(args.all && narrowing),
            "--all cannot be combined with a narrowing selector (--since/--until/--id/\
             --ids-from/--source-label) — it already means \"everything\""
        );
        anyhow::ensure!(
            args.all || narrowing,
            "at least one selector is required: --all, --since, --until, --id, --ids-from, \
             or --source-label"
        );

        let since = args
            .since
            .as_deref()
            .map(parse_date_bound_start)
            .transpose()?;
        let until = args
            .until
            .as_deref()
            .map(parse_date_bound_end)
            .transpose()?;

        Ok(Self {
            all: args.all,
            since,
            until,
            ids,
            source_label: args.source_label.clone(),
        })
    }

    /// Ensures every id named via `--id`/`--ids-from` is actually selectable
    /// — present in `manifest` **and** not soft-deleted — since a
    /// soft-deleted record is dropped by [`crate::cli::gmail::sync::manifest::Manifest::records_not_deleted`]
    /// before [`Self::matches`] ever runs on it. An id the caller named
    /// explicitly but that can never be selected is an error, never a
    /// silent drop from the result set, which is why this is checked up
    /// front rather than left to fall out of an empty result.
    pub(crate) fn ensure_requested_ids_selectable(
        &self,
        manifest: &Manifest,
        archive_dir: &Path,
    ) -> Result<()> {
        for id in &self.ids {
            anyhow::ensure!(
                manifest
                    .get(id)
                    .is_some_and(|record| record.deleted_at.is_none()),
                "--id {id} was not found in the archive manifest at {}",
                archive_dir.display()
            );
        }
        Ok(())
    }

    /// Whether `record` is selected — a plain conjunction of independent
    /// predicates: each is trivially satisfied when its corresponding
    /// option is unset, so specifying more than one narrows rather than
    /// widens the match set. A record with no parseable `internal_date` is
    /// excluded whenever `since`/`until` is set, and kept when neither is.
    pub(crate) fn matches(&self, record: &ManifestRecord) -> bool {
        if self.all {
            return true;
        }
        if !self.ids.is_empty() && !self.ids.contains(&record.id) {
            return false;
        }
        if let Some(label) = &self.source_label {
            if !record.label_ids.iter().any(|l| l == label) {
                return false;
            }
        }
        if self.since.is_some() || self.until.is_some() {
            let Some(date) = record.internal_date_utc() else {
                return false;
            };
            if self.since.is_some_and(|since| date < since) {
                return false;
            }
            if self.until.is_some_and(|until| date > until) {
                return false;
            }
        }
        true
    }
}

/// Parses `YYYY-MM-DD` as the first instant of that UTC day (`--since`'s
/// lower bound), mirroring `crate::cli::log::query::parse_time_bound`'s
/// date-only case.
fn parse_date_bound_start(s: &str) -> Result<DateTime<Utc>> {
    let date = NaiveDate::parse_from_str(s, "%Y-%m-%d")
        .with_context(|| format!("invalid date {s:?} (expected YYYY-MM-DD)"))?;
    Ok(date.and_time(NaiveTime::MIN).and_utc())
}

/// Parses `YYYY-MM-DD` as the last instant of that UTC day (`--until`'s
/// upper bound), so `--until` is inclusive of the whole named day rather
/// than excluding everything after its midnight.
fn parse_date_bound_end(s: &str) -> Result<DateTime<Utc>> {
    let date = NaiveDate::parse_from_str(s, "%Y-%m-%d")
        .with_context(|| format!("invalid date {s:?} (expected YYYY-MM-DD)"))?;
    let end_of_day = NaiveTime::from_hms_milli_opt(23, 59, 59, 999)
        .unwrap_or_else(|| unreachable!("23:59:59.999 is always a valid time"));
    Ok(date.and_time(end_of_day).and_utc())
}

/// Reads one id per line from `path` (`-` for stdin), skipping blank lines
/// and `#`-prefixed comments — the same shape a `--dry-run` report's ids can
/// be piped straight back into a follow-up `--ids-from -`.
fn read_ids_from(path: &std::path::Path) -> Result<Vec<String>> {
    let content = if path.as_os_str() == "-" {
        let mut buf = String::new();
        std::io::stdin()
            .lock()
            .read_to_string(&mut buf)
            .context("Failed to read ids from stdin")?;
        buf
    } else {
        std::fs::read_to_string(path)
            .with_context(|| format!("Failed to read ids from {}", path.display()))?
    };
    Ok(content
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty() && !line.starts_with('#'))
        .map(str::to_string)
        .collect())
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    fn sample_record(id: &str) -> ManifestRecord {
        ManifestRecord {
            id: id.to_string(),
            thread_id: None,
            label_ids: Vec::new(),
            internal_date: None,
            subject: None,
            from: None,
            to: None,
            rfc822_msgid: None,
            in_reply_to: None,
            references: None,
            attachment_count: 0,
            attachment_filenames: Vec::new(),
            path: PathBuf::from(format!("messages/{id}.eml")),
            size: 0,
            history_id: None,
            deleted_at: None,
            excluded_labels: Vec::new(),
        }
    }

    fn dated_record(id: &str, ms: i64) -> ManifestRecord {
        ManifestRecord {
            internal_date: Some(ms.to_string()),
            ..sample_record(id)
        }
    }

    fn labeled_record(id: &str, labels: &[&str]) -> ManifestRecord {
        ManifestRecord {
            label_ids: labels
                .iter()
                .map(std::string::ToString::to_string)
                .collect(),
            ..sample_record(id)
        }
    }

    // ── any_given ───────────────────────────────────────────────────

    #[test]
    fn any_given_is_false_for_default() {
        assert!(!SelectionArgs::default().any_given());
    }

    #[test]
    fn any_given_is_true_when_a_selector_is_set() {
        assert!(SelectionArgs {
            all: true,
            ..SelectionArgs::default()
        }
        .any_given());
        assert!(SelectionArgs {
            since: Some("2026-01-01".to_string()),
            ..SelectionArgs::default()
        }
        .any_given());
        assert!(SelectionArgs {
            ids: vec!["m1".to_string()],
            ..SelectionArgs::default()
        }
        .any_given());
    }

    // ── from_args validation ────────────────────────────────────────

    #[test]
    fn from_args_requires_at_least_one_selector() {
        let err = Selection::from_args(&SelectionArgs::default()).unwrap_err();
        assert!(err.to_string().contains("at least one selector"));
    }

    #[test]
    fn from_args_rejects_all_combined_with_a_narrowing_selector() {
        let args = SelectionArgs {
            all: true,
            since: Some("2026-01-01".to_string()),
            ..SelectionArgs::default()
        };
        let err = Selection::from_args(&args).unwrap_err();
        assert!(err.to_string().contains("cannot be combined"));
    }

    #[test]
    fn from_args_accepts_all_alone() {
        assert!(Selection::from_args(&SelectionArgs {
            all: true,
            ..SelectionArgs::default()
        })
        .is_ok());
    }

    #[test]
    fn from_args_rejects_an_invalid_date() {
        let args = SelectionArgs {
            since: Some("not-a-date".to_string()),
            ..SelectionArgs::default()
        };
        let err = Selection::from_args(&args).unwrap_err();
        assert!(err.to_string().contains("invalid date"));
    }

    #[test]
    fn from_args_reads_ids_from_a_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("ids.txt");
        std::fs::write(&path, "m1\n\n# a comment\nm2\n  m3  \n").unwrap();
        let args = SelectionArgs {
            ids_from: Some(path),
            ..SelectionArgs::default()
        };
        let selection = Selection::from_args(&args).unwrap();
        assert!(selection.matches(&sample_record("m1")));
        assert!(selection.matches(&sample_record("m2")));
        assert!(selection.matches(&sample_record("m3")));
        assert!(!selection.matches(&sample_record("m4")));
    }

    // ── ensure_requested_ids_selectable ───────────────────────────────

    #[test]
    fn ensure_requested_ids_selectable_accepts_a_present_non_deleted_id() {
        let mut manifest = Manifest::default();
        manifest.upsert(sample_record("m1"));
        let selection = Selection::from_args(&SelectionArgs {
            ids: vec!["m1".to_string()],
            ..SelectionArgs::default()
        })
        .unwrap();
        assert!(selection
            .ensure_requested_ids_selectable(&manifest, Path::new("archive"))
            .is_ok());
    }

    #[test]
    fn ensure_requested_ids_selectable_rejects_an_id_absent_from_the_manifest() {
        let manifest = Manifest::default();
        let selection = Selection::from_args(&SelectionArgs {
            ids: vec!["missing".to_string()],
            ..SelectionArgs::default()
        })
        .unwrap();
        let err = selection
            .ensure_requested_ids_selectable(&manifest, Path::new("archive"))
            .unwrap_err();
        assert!(err.to_string().contains("--id missing was not found"));
    }

    #[test]
    fn ensure_requested_ids_selectable_rejects_a_soft_deleted_id() {
        let mut manifest = Manifest::default();
        manifest.upsert(ManifestRecord {
            deleted_at: Some(Utc::now()),
            ..sample_record("m1")
        });
        let selection = Selection::from_args(&SelectionArgs {
            ids: vec!["m1".to_string()],
            ..SelectionArgs::default()
        })
        .unwrap();
        let err = selection
            .ensure_requested_ids_selectable(&manifest, Path::new("archive"))
            .unwrap_err();
        assert!(err.to_string().contains("--id m1 was not found"));
    }

    // ── matches (conjunction) ─────────────────────────────────────────

    #[test]
    fn matches_all_selects_everything() {
        let selection = Selection::from_args(&SelectionArgs {
            all: true,
            ..SelectionArgs::default()
        })
        .unwrap();
        assert!(selection.matches(&sample_record("m1")));
    }

    #[test]
    fn matches_id_selects_only_named_ids() {
        let args = SelectionArgs {
            ids: vec!["m1".to_string()],
            ..SelectionArgs::default()
        };
        let selection = Selection::from_args(&args).unwrap();
        assert!(selection.matches(&sample_record("m1")));
        assert!(!selection.matches(&sample_record("m2")));
    }

    #[test]
    fn matches_source_label_requires_the_label_present() {
        let args = SelectionArgs {
            source_label: Some("Label_1".to_string()),
            ..SelectionArgs::default()
        };
        let selection = Selection::from_args(&args).unwrap();
        assert!(selection.matches(&labeled_record("m1", &["Label_1"])));
        assert!(!selection.matches(&labeled_record("m2", &["Label_2"])));
    }

    #[test]
    fn matches_date_range_is_inclusive_on_both_ends() {
        let args = SelectionArgs {
            since: Some("2026-01-01".to_string()),
            until: Some("2026-01-02".to_string()),
            ..SelectionArgs::default()
        };
        let selection = Selection::from_args(&args).unwrap();
        let jan1_start = NaiveDate::from_ymd_opt(2026, 1, 1)
            .unwrap()
            .and_time(NaiveTime::MIN)
            .and_utc()
            .timestamp_millis();
        let jan2_end = NaiveDate::from_ymd_opt(2026, 1, 2)
            .unwrap()
            .and_time(NaiveTime::from_hms_milli_opt(23, 59, 59, 999).unwrap())
            .and_utc()
            .timestamp_millis();
        let jan3_start = NaiveDate::from_ymd_opt(2026, 1, 3)
            .unwrap()
            .and_time(NaiveTime::MIN)
            .and_utc()
            .timestamp_millis();
        assert!(selection.matches(&dated_record("m1", jan1_start)));
        assert!(selection.matches(&dated_record("m2", jan2_end)));
        assert!(!selection.matches(&dated_record("m3", jan3_start)));
    }

    #[test]
    fn matches_date_range_excludes_a_record_older_than_since() {
        let args = SelectionArgs {
            since: Some("2026-01-02".to_string()),
            ..SelectionArgs::default()
        };
        let selection = Selection::from_args(&args).unwrap();
        let jan1_start = NaiveDate::from_ymd_opt(2026, 1, 1)
            .unwrap()
            .and_time(NaiveTime::MIN)
            .and_utc()
            .timestamp_millis();
        assert!(!selection.matches(&dated_record("m1", jan1_start)));
    }

    #[test]
    fn matches_date_range_excludes_records_with_no_parseable_date() {
        let args = SelectionArgs {
            since: Some("2026-01-01".to_string()),
            ..SelectionArgs::default()
        };
        let selection = Selection::from_args(&args).unwrap();
        assert!(!selection.matches(&sample_record("m1")));
    }

    #[test]
    fn matches_with_no_date_bound_keeps_records_with_no_date() {
        let selection = Selection::from_args(&SelectionArgs {
            all: true,
            ..SelectionArgs::default()
        })
        .unwrap();
        assert!(selection.matches(&sample_record("m1")));
    }

    #[test]
    fn matches_conjoins_id_and_source_label() {
        let args = SelectionArgs {
            ids: vec!["m1".to_string()],
            source_label: Some("Label_1".to_string()),
            ..SelectionArgs::default()
        };
        let selection = Selection::from_args(&args).unwrap();
        // Right id, wrong label -> excluded (conjunction, not either-or).
        assert!(!selection.matches(&labeled_record("m1", &["Label_2"])));
        assert!(selection.matches(&labeled_record("m1", &["Label_1"])));
    }
}