omni-dev 0.41.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
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
//! CLI command for `omni-dev gmail search`.

use std::io::Write;

use anyhow::{Context, Result};
use clap::Parser;

use crate::cli::gmail::format::{output_as, sanitize_for_terminal, OutputFormat};
use crate::gmail::client::GmailClient;
use crate::gmail::messages_api::{MessageSummary, MessagesApi, DEFAULT_SEARCH_LIMIT};
use crate::gmail::types::MessageRef;

/// Maximum snippet length shown in the table view before truncation.
const SNIPPET_TRUNCATE_AT: usize = 60;

/// Default bound on concurrent `messages.get` calls when `--enrich` is set.
const DEFAULT_ENRICH_CONCURRENCY: usize = 4;

/// Searches Gmail messages (mirrors the `gmail_search` MCP tool).
///
/// **Ids-only by default.** `messages.list` only returns `{id, threadId}`
/// per hit — enriching a result with From/Subject/Date/snippet costs one
/// extra `messages.get` request per hit, and Gmail's quota is 250
/// units/user/second with `messages.get` at 5 units, so an unbounded
/// enrichment pass can burn the entire per-second budget in one command.
/// Ids-only is therefore the cheap path you get by accident; `--enrich`
/// opts into the expensive, more useful table.
#[derive(Parser)]
pub struct SearchCommand {
    /// Gmail search query (same syntax as the Gmail search box, e.g.
    /// `label:finance after:2026/01/01`).
    #[arg(long)]
    pub query: String,

    /// Maximum results to return. `0` means "fetch every match" (capped, like
    /// Datadog's log/event search, at a hard ceiling to bound run time and quota).
    #[arg(long, default_value_t = DEFAULT_SEARCH_LIMIT)]
    pub limit: usize,

    /// Enrich each hit with From/Subject/Date/snippet via one extra
    /// `messages.get` request per hit. Without this flag, `search` returns
    /// only `id`/`threadId` — the cheap, quota-safe default. Combined with
    /// `--limit 0` this can issue thousands of requests; use deliberately.
    #[arg(long)]
    pub enrich: bool,

    /// Bounds concurrent `messages.get` calls when `--enrich` is set (has
    /// no effect otherwise). Modelled on `confluence download`'s
    /// `--concurrency`. Clamped to 1..=50 — Gmail's quota is 250
    /// units/user/second and `messages.get` costs 5 units, so a higher
    /// value could burst past it.
    #[arg(long, default_value_t = DEFAULT_ENRICH_CONCURRENCY)]
    pub concurrency: usize,

    /// Output format.
    #[arg(short = 'o', long, value_enum, default_value_t = OutputFormat::Table)]
    pub output: OutputFormat,
}

impl SearchCommand {
    /// Runs the command against the shared client resolved by the parent
    /// `GmailCommand::execute`.
    pub async fn execute(self, client: &GmailClient) -> Result<()> {
        run_search(
            client,
            &self.query,
            self.limit,
            self.enrich,
            self.concurrency,
            &self.output,
        )
        .await
    }
}

/// Fetches search results (ids-only, or enriched when `enrich` is set) and
/// emits them in the requested format.
///
/// Split from [`SearchCommand::execute`] so tests can inject a wiremock
/// client without going through the credential-loading path.
async fn run_search(
    client: &GmailClient,
    query: &str,
    limit: usize,
    enrich: bool,
    concurrency: usize,
    output: &OutputFormat,
) -> Result<()> {
    let api = MessagesApi::new(client);
    if enrich {
        let summaries = api
            .search_summaries(Some(query), &[], limit, concurrency)
            .await?;
        if output_as(&summaries, output)? {
            return Ok(());
        }
        let stdout = std::io::stdout();
        let mut handle = stdout.lock();
        render_search_table(&summaries, &mut handle)
    } else {
        let list = api.search_all(Some(query), &[], limit).await?;
        if output_as(&list.messages, output)? {
            return Ok(());
        }
        let stdout = std::io::stdout();
        let mut handle = stdout.lock();
        render_id_table(&list.messages, &mut handle)
    }
}

/// Renders ids-only search results (the default) as a two-column table.
///
/// Column layout: `ID | THREAD_ID`. An empty input prints
/// `No messages returned.`.
fn render_id_table(refs: &[MessageRef], out: &mut dyn Write) -> Result<()> {
    if refs.is_empty() {
        writeln!(out, "No messages returned.").context("Failed to write empty-table message")?;
        return Ok(());
    }

    // Sanitize before computing column widths (#1537) — see
    // `render_search_table` below for the same treatment.
    let rows: Vec<(String, String)> = refs
        .iter()
        .map(|r| {
            (
                sanitize_for_terminal(&r.id),
                sanitize_for_terminal(&r.thread_id),
            )
        })
        .collect();

    let id_width = "ID"
        .len()
        .max(rows.iter().map(|(id, _)| id.len()).max().unwrap_or(0));
    let thread_width = "THREAD_ID"
        .len()
        .max(rows.iter().map(|(_, t)| t.len()).max().unwrap_or(0));

    writeln!(out, "{:<id_width$}  {:<thread_width$}", "ID", "THREAD_ID")
        .context("Failed to write search row")?;
    writeln!(
        out,
        "{}  {}",
        "-".repeat(id_width),
        "-".repeat(thread_width)
    )
    .context("Failed to write search row")?;
    for (id, thread_id) in &rows {
        writeln!(out, "{id:<id_width$}  {thread_id:<thread_width$}")
            .context("Failed to write search row")?;
    }
    Ok(())
}

/// Renders enriched search results as an aligned text table.
///
/// Column layout: `ID | FROM | SUBJECT | DATE | SNIPPET`. The snippet is
/// truncated to [`SNIPPET_TRUNCATE_AT`] chars — Gmail's own snippet is
/// already short, but even that is often too wide for a terminal table. An
/// empty input prints `No messages returned.`.
pub(crate) fn render_search_table(summaries: &[MessageSummary], out: &mut dyn Write) -> Result<()> {
    if summaries.is_empty() {
        writeln!(out, "No messages returned.").context("Failed to write empty-table message")?;
        return Ok(());
    }

    // Sanitize server-supplied strings *before* computing column widths (and
    // before truncating the snippet, so stripped control bytes don't eat
    // into the visible-character budget) — a stripped control byte must not
    // leave a column one character too wide for what's actually written
    // (#1537).
    let rows: Vec<[String; 5]> = summaries
        .iter()
        .map(|s| {
            [
                sanitize_for_terminal(&s.id),
                sanitize_for_terminal(&s.from),
                sanitize_for_terminal(&s.subject),
                sanitize_for_terminal(&s.date),
                truncate(&sanitize_for_terminal(&s.snippet)),
            ]
        })
        .collect();

    let id_width = "ID"
        .len()
        .max(rows.iter().map(|r| r[0].len()).max().unwrap_or(0));
    let from_width = "FROM"
        .len()
        .max(rows.iter().map(|r| r[1].len()).max().unwrap_or(0));
    let subject_width = "SUBJECT"
        .len()
        .max(rows.iter().map(|r| r[2].len()).max().unwrap_or(0));
    let date_width = "DATE"
        .len()
        .max(rows.iter().map(|r| r[3].len()).max().unwrap_or(0));
    let snippet_width = "SNIPPET"
        .len()
        .max(rows.iter().map(|r| r[4].len()).max().unwrap_or(0));

    write_row(
        out,
        "ID",
        "FROM",
        "SUBJECT",
        "DATE",
        "SNIPPET",
        id_width,
        from_width,
        subject_width,
        date_width,
        snippet_width,
    )?;
    write_row(
        out,
        &"-".repeat(id_width),
        &"-".repeat(from_width),
        &"-".repeat(subject_width),
        &"-".repeat(date_width),
        &"-".repeat(snippet_width),
        id_width,
        from_width,
        subject_width,
        date_width,
        snippet_width,
    )?;
    for row in &rows {
        write_row(
            out,
            &row[0],
            &row[1],
            &row[2],
            &row[3],
            &row[4],
            id_width,
            from_width,
            subject_width,
            date_width,
            snippet_width,
        )?;
    }
    Ok(())
}

fn truncate(text: &str) -> String {
    if text.chars().count() <= SNIPPET_TRUNCATE_AT {
        text.to_string()
    } else {
        let mut truncated: String = text.chars().take(SNIPPET_TRUNCATE_AT).collect();
        truncated.push('');
        truncated
    }
}

/// Writes a single row of the bespoke search table with consistent 2-space
/// gutters between cells.
#[allow(clippy::too_many_arguments)]
fn write_row(
    out: &mut dyn Write,
    id: &str,
    from: &str,
    subject: &str,
    date: &str,
    snippet: &str,
    id_w: usize,
    from_w: usize,
    subject_w: usize,
    date_w: usize,
    snippet_w: usize,
) -> Result<()> {
    writeln!(
        out,
        "{id:<id_w$}  {from:<from_w$}  {subject:<subject_w$}  {date:<date_w$}  {snippet:<snippet_w$}"
    )
    .context("Failed to write search row")?;
    Ok(())
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::gmail::auth::{GmailCredentials, GmailScope};
    use crate::utils::secret::Secret;

    fn test_credentials() -> GmailCredentials {
        GmailCredentials {
            client_id: "client-1".to_string(),
            client_secret: Secret::new("secret-1"),
            refresh_token: Secret::new("refresh-1"),
            scope: GmailScope::ReadOnly,
        }
    }

    async fn client_with_bootstrapped_token(server: &wiremock::MockServer) -> GmailClient {
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path("/token"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "access_token": "test-token",
                    "expires_in": 3600,
                })),
            )
            .mount(server)
            .await;

        let mut client = GmailClient::new(&server.uri(), &test_credentials()).unwrap();
        crate::gmail::client::test_support::replace_session(
            &mut client,
            &test_credentials(),
            &format!("{}/token", server.uri()),
        );
        client
    }

    fn sample_summary(id: &str) -> MessageSummary {
        MessageSummary {
            id: id.to_string(),
            thread_id: "t1".to_string(),
            from: "a@example.com".to_string(),
            subject: "Hello".to_string(),
            date: "Mon, 1 Jan 2026".to_string(),
            snippet: "Hi there".to_string(),
        }
    }

    fn sample_ref(id: &str) -> MessageRef {
        MessageRef {
            id: id.to_string(),
            thread_id: "t1".to_string(),
        }
    }

    // ── truncate ─────────────────────────────────────────────────────

    #[test]
    fn truncate_leaves_short_snippet_unchanged() {
        assert_eq!(truncate("short"), "short");
    }

    #[test]
    fn truncate_shortens_long_snippet_with_ellipsis() {
        let long = "a".repeat(SNIPPET_TRUNCATE_AT + 20);
        let truncated = truncate(&long);
        assert_eq!(truncated.chars().count(), SNIPPET_TRUNCATE_AT + 1);
        assert!(truncated.ends_with(''));
    }

    // ── render_id_table ────────────────────────────────────────────────

    #[test]
    fn render_id_table_empty_prints_message() {
        let mut buf = Vec::new();
        render_id_table(&[], &mut buf).unwrap();
        assert_eq!(String::from_utf8(buf).unwrap(), "No messages returned.\n");
    }

    #[test]
    fn render_id_table_writes_header_and_rows() {
        let refs = [sample_ref("m1"), sample_ref("m2")];
        let mut buf = Vec::new();
        render_id_table(&refs, &mut buf).unwrap();
        let out = String::from_utf8(buf).unwrap();
        assert!(out.contains("ID"));
        assert!(out.contains("THREAD_ID"));
        assert!(out.contains("m1"));
        assert!(out.contains("m2"));
        assert_eq!(out.lines().count(), 4);
    }

    #[test]
    fn render_id_table_strips_control_bytes_and_keeps_columns_aligned() {
        let refs = [
            MessageRef {
                id: "evil\x1b[31mid".to_string(),
                thread_id: "t\r\x071".to_string(),
            },
            sample_ref("m2"),
        ];
        let mut buf = Vec::new();
        render_id_table(&refs, &mut buf).unwrap();
        let out = String::from_utf8(buf).unwrap();
        assert!(
            !out.contains(|c: char| c.is_control() && c != '\n'),
            "{out:?}"
        );
        assert!(out.contains("evil[31mid"), "{out:?}");
        let lengths: Vec<usize> = out.lines().map(str::len).collect();
        assert!(lengths.windows(2).all(|w| w[0] == w[1]), "{out:?}");
    }

    // ── render_search_table ──────────────────────────────────────────

    #[test]
    fn render_table_empty_prints_message() {
        let mut buf = Vec::new();
        render_search_table(&[], &mut buf).unwrap();
        assert_eq!(String::from_utf8(buf).unwrap(), "No messages returned.\n");
    }

    #[test]
    fn render_table_writes_header_and_rows() {
        let summaries = [sample_summary("m1"), sample_summary("m2")];
        let mut buf = Vec::new();
        render_search_table(&summaries, &mut buf).unwrap();
        let out = String::from_utf8(buf).unwrap();
        assert!(out.contains("ID"));
        assert!(out.contains("FROM"));
        assert!(out.contains("SUBJECT"));
        assert!(out.contains("DATE"));
        assert!(out.contains("SNIPPET"));
        assert!(out.contains("m1"));
        assert!(out.contains("m2"));
        // Header + separator + 2 data rows = 4 lines.
        assert_eq!(out.lines().count(), 4);
    }

    #[test]
    fn render_search_table_strips_control_bytes_and_keeps_columns_aligned() {
        let summaries = [
            MessageSummary {
                id: "evil\x1b[31mid".to_string(),
                thread_id: "t1".to_string(),
                from: "a\r@example.com".to_string(),
                subject: "Hi\x07There".to_string(),
                date: "Mon, 1 Jan 2026".to_string(),
                snippet: "snippet\u{9b}2J".to_string(),
            },
            sample_summary("m2"),
        ];
        let mut buf = Vec::new();
        render_search_table(&summaries, &mut buf).unwrap();
        let out = String::from_utf8(buf).unwrap();
        assert!(
            !out.contains(|c: char| c.is_control() && c != '\n'),
            "{out:?}"
        );
        assert!(out.contains("evil[31mid"), "{out:?}");
        let lengths: Vec<usize> = out.lines().map(str::len).collect();
        assert!(lengths.windows(2).all(|w| w[0] == w[1]), "{out:?}");
    }

    struct FailAfter {
        successes_remaining: usize,
    }
    impl Write for FailAfter {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            if self.successes_remaining == 0 {
                return Err(std::io::Error::other("test forced write failure"));
            }
            if buf.contains(&b'\n') {
                self.successes_remaining -= 1;
            }
            Ok(buf.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    #[test]
    fn render_table_propagates_header_write_errors() {
        let summaries = [sample_summary("m1")];
        let err = render_search_table(
            &summaries,
            &mut FailAfter {
                successes_remaining: 0,
            },
        )
        .unwrap_err();
        assert!(err.to_string().contains("Failed to write"));
    }

    #[test]
    fn render_table_empty_propagates_write_errors() {
        let err = render_search_table(
            &[],
            &mut FailAfter {
                successes_remaining: 0,
            },
        )
        .unwrap_err();
        assert!(err.to_string().contains("empty-table message"));
    }

    #[test]
    fn render_table_propagates_separator_row_write_errors() {
        let summaries = [sample_summary("m1")];
        let err = render_search_table(
            &summaries,
            &mut FailAfter {
                successes_remaining: 1,
            },
        )
        .unwrap_err();
        assert!(err.to_string().contains("Failed to write"));
    }

    #[test]
    fn render_table_propagates_data_row_write_errors() {
        let summaries = [sample_summary("m1")];
        let err = render_search_table(
            &summaries,
            &mut FailAfter {
                successes_remaining: 2,
            },
        )
        .unwrap_err();
        assert!(err.to_string().contains("Failed to write"));
    }

    // ── run_search (ids-only default) ─────────────────────────────────

    #[tokio::test]
    async fn run_search_defaults_to_ids_only_and_makes_no_hydration_call() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/messages"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "messages": [{"id": "m1", "threadId": "t1"}]
                })),
            )
            .expect(1)
            .mount(&server)
            .await;
        // No mock for GET .../messages/m1 — if `run_search` tried to
        // hydrate, wiremock would 404 and the call would fail; it doesn't
        // fail, proving no hydration request was made.

        run_search(&client, "label:finance", 5, false, 4, &OutputFormat::Table)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn run_search_ids_only_json_path_returns_ok() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/messages"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "messages": []
                })),
            )
            .mount(&server)
            .await;

        run_search(&client, "*", 5, false, 4, &OutputFormat::Json)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn run_search_ids_only_propagates_api_errors() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/messages"))
            .respond_with(wiremock::ResponseTemplate::new(500).set_body_string("boom"))
            .mount(&server)
            .await;

        let err = run_search(&client, "*", 5, false, 4, &OutputFormat::Table)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("500"));
    }

    // ── run_search (--enrich) ──────────────────────────────────────────

    #[tokio::test]
    async fn run_search_enrich_table_path_writes_to_stdout() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/messages"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "messages": [{"id": "m1", "threadId": "t1"}]
                })),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/messages/m1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({"id": "m1"})),
            )
            .mount(&server)
            .await;

        run_search(&client, "label:finance", 5, true, 4, &OutputFormat::Table)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn run_search_enrich_json_path_returns_ok() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/messages"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "messages": []
                })),
            )
            .mount(&server)
            .await;

        run_search(&client, "*", 5, true, 4, &OutputFormat::Json)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn run_search_enrich_propagates_api_errors() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/messages"))
            .respond_with(wiremock::ResponseTemplate::new(500).set_body_string("boom"))
            .mount(&server)
            .await;

        let err = run_search(&client, "*", 5, true, 4, &OutputFormat::Table)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("500"));
    }

    // ── SearchCommand::execute glue ────────────────────────────────

    #[tokio::test]
    async fn execute_passes_query_through() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/messages"))
            .and(wiremock::matchers::query_param("q", "label:finance"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "messages": []
                })),
            )
            .expect(1)
            .mount(&server)
            .await;

        let cmd = SearchCommand {
            query: "label:finance".to_string(),
            limit: 5,
            enrich: false,
            concurrency: DEFAULT_ENRICH_CONCURRENCY,
            output: OutputFormat::Json,
        };
        cmd.execute(&client).await.unwrap();
    }

    #[tokio::test]
    async fn execute_enrich_flag_triggers_hydration() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/messages"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "messages": [{"id": "m1", "threadId": "t1"}]
                })),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/messages/m1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({"id": "m1"})),
            )
            .expect(1)
            .mount(&server)
            .await;

        let cmd = SearchCommand {
            query: "*".to_string(),
            limit: 5,
            enrich: true,
            concurrency: 2,
            output: OutputFormat::Json,
        };
        cmd.execute(&client).await.unwrap();
    }
}