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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
//! CLI command for `omni-dev drive permissions check`.

use anyhow::Result;
use clap::Parser;
use serde::Serialize;

use crate::cli::drive::format::{
    output_as, sanitize_for_terminal, write_scalar_jsonl, JsonlSerialize, OutputFormat,
};
use crate::cli::drive::helpers::active_account_rules;
use crate::drive::client::DriveClient;
use crate::drive::files_api::FilesApi;
use crate::drive::folder_ancestry::{self, DecisionSource, FileTargetDecision};
use crate::drive::types::GOOGLE_FOLDER_MIME_TYPE;
use crate::drive::write_gate::{self, DriveOperation, FolderPermissionRule, Verdict};

/// `--operation`'s value set — a thin CLI-layer copy of
/// [`DriveOperation`], kept separate so the pure engine module has no
/// `clap` dependency (mirrors how `crate::drive::visibility::MoveGateFlags`
/// stays free of the CLI layer's option-parsing types).
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
pub enum OperationArg {
    Read,
    Create,
    Upload,
    Edit,
    /// Writing cells into a Google Sheet — distinct from `Edit`, see
    /// [`DriveOperation::SheetsWrite`].
    SheetsWrite,
    /// Structurally editing a Google Sheet — distinct from `SheetsWrite`,
    /// see [`DriveOperation::SheetsStructure`].
    SheetsStructure,
    /// Destructively editing a Google Sheet — distinct from
    /// `SheetsStructure`, see [`DriveOperation::SheetsDelete`].
    SheetsDelete,
    /// Adding, changing or removing a protected range — distinct from
    /// `SheetsStructure`, see [`DriveOperation::SheetsProtection`].
    SheetsProtection,
    /// Replacing or appending text in a Google Doc — distinct from both
    /// `Edit` and `SheetsWrite`, see [`DriveOperation::DocsWrite`].
    DocsWrite,
    /// Moving an individual file to Trash or restoring it.
    Trash,
    /// Replacing text on ordinary Slides pages.
    SlidesWrite,
    /// Anchor-addressed content deletion; separate from docs-write.
    DocsDelete,
    /// Anchor-addressed text and paragraph styling.
    DocsFormat,
    /// Add empty Docs tables, rows or columns, or change named-range metadata.
    DocsStructure,
    /// Remove Docs table rows or columns.
    DocsTableDelete,
}

impl From<OperationArg> for DriveOperation {
    fn from(arg: OperationArg) -> Self {
        match arg {
            OperationArg::Read => Self::Read,
            OperationArg::Create => Self::Create,
            OperationArg::Upload => Self::Upload,
            OperationArg::Edit => Self::Edit,
            OperationArg::SheetsWrite => Self::SheetsWrite,
            OperationArg::SheetsStructure => Self::SheetsStructure,
            OperationArg::SheetsDelete => Self::SheetsDelete,
            OperationArg::SheetsProtection => Self::SheetsProtection,
            OperationArg::DocsWrite => Self::DocsWrite,
            OperationArg::Trash => Self::Trash,
            OperationArg::SlidesWrite => Self::SlidesWrite,
            OperationArg::DocsDelete => Self::DocsDelete,
            OperationArg::DocsFormat => Self::DocsFormat,
            OperationArg::DocsStructure => Self::DocsStructure,
            OperationArg::DocsTableDelete => Self::DocsTableDelete,
        }
    }
}

/// Evaluates the configured write-permission rules against a real target
/// and prints the verdict — the same [`folder_ancestry::resolve_decision`]/
/// [`folder_ancestry::resolve_decision_for_file_target`] the real
/// `create`/`upload`/`edit`/`sheets write` engine modules call, so this
/// diagnostic can never drift from actual enforcement.
#[derive(Parser)]
pub struct CheckCommand {
    /// The folder or file id to evaluate.
    pub id: String,

    /// Which operation to check.
    #[arg(long, value_enum)]
    pub operation: OperationArg,

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

impl CheckCommand {
    /// Runs the command against the shared client resolved by
    /// `PermissionsCommand::execute`.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        let rules = active_account_rules()?;
        run_check(
            client,
            &self.id,
            self.operation.into(),
            &rules,
            &self.output,
        )
        .await
    }
}

/// Report shape shared by table/JSON/YAML/JSONL rendering.
#[derive(Debug, Clone, Serialize)]
pub struct CheckReport {
    /// The evaluated target id.
    pub target_id: String,
    /// The evaluated operation.
    pub operation: String,
    /// `"allow"` or `"deny"`.
    pub verdict: String,
    /// The folder id of the rule that decided this, if a folder rule did.
    pub decided_by_folder_id: Option<String>,
    /// How many levels above the target that rule's folder sits.
    pub decided_by_depth: Option<usize>,
    /// The file id of the rule that decided this, if a **file** rule did
    /// (issue #1612). Mutually exclusive with `decided_by_folder_id`.
    pub decided_by_file_id: Option<String>,
    /// How the verdict was reached: `"file-rule"`, `"folder-chain"` or
    /// `"no-visible-parents"`.
    ///
    /// `"no-visible-parents"` is the answer to "why can't I grant this
    /// with a folder rule?" — the diagnostic this whole report exists to
    /// give. Always `"folder-chain"` for a folder target, which never
    /// consults file rules.
    pub evaluated_via: String,
    /// Whether a write acting on this verdict would need a valid `--lease`
    /// token ([`write_gate::decided_rule_requires_lease`], ADR-0080 §1/§9).
    /// Only meaningful alongside `verdict: "allow"` — a denied write never
    /// reaches the lease check either way. Always `false` for `read`,
    /// `create`, `upload` and `trash` (issue #1917,
    /// [`DriveOperation::ever_requires_lease`]) — none of these operations ever
    /// gates on a lease, whatever the resolved decision reports.
    pub requires_lease: bool,
}

impl JsonlSerialize for CheckReport {
    fn write_jsonl(&self, out: &mut dyn std::io::Write) -> Result<()> {
        write_scalar_jsonl(self, out)
    }
}

/// Resolves `target_id`'s evaluation chain (or chains, for a file with
/// multiple current parents) and prints the verdict.
///
/// Split from [`CheckCommand::execute`] so tests can inject a wiremock
/// client and a constructed rule set directly.
async fn run_check(
    client: &DriveClient,
    target_id: &str,
    op: DriveOperation,
    rules: &[FolderPermissionRule],
    output: &OutputFormat,
) -> Result<()> {
    let files_api = FilesApi::new(client);
    let evaluated = evaluate_target(&files_api, target_id, op, rules).await?;
    // `op` may never gate on a lease at all (issue #1917) — `read`,
    // `create` and `upload` never do, whatever the resolved decision says.
    let requires_lease = op.ever_requires_lease() && evaluated.requires_lease;
    let evaluated_via = evaluated_via(evaluated.source).to_string();
    let decision = evaluated.decision;
    let log_fields = write_gate::decided_by_log_fields(decision.decided_by.as_ref());
    let report = CheckReport {
        target_id: target_id.to_string(),
        operation: op.to_string(),
        verdict: match decision.verdict {
            Verdict::Allow => "allow".to_string(),
            Verdict::Deny => "deny".to_string(),
        },
        decided_by_folder_id: log_fields.folder_id,
        decided_by_depth: log_fields.depth,
        decided_by_file_id: log_fields.file_id,
        evaluated_via,
        requires_lease,
    };
    if output_as(&report, output)? {
        return Ok(());
    }
    print_report(&report);
    Ok(())
}

/// Fetches `target_id` and evaluates `op` against it.
///
/// A **folder** target's chain starts at itself (mirrors `create`/
/// `upload`'s `--parent` semantics, reusing the already-fetched metadata
/// via [`folder_ancestry::resolve_decision_from`] rather than re-fetching
/// it). `file_id` rules deliberately do **not** apply to a folder target:
/// a folder target means "create or upload something inside this", and a
/// `file_id` rule naming a folder id would just be a worse spelling of a
/// non-recursive `folder_id` rule.
///
/// A **file** target goes through
/// [`folder_ancestry::resolve_decision_for_file_target`] — the same single
/// entry point `drive edit` and `drive sheets write` use, which is what
/// lets this diagnostic claim it can never drift from actual enforcement.
async fn evaluate_target(
    files_api: &FilesApi<'_>,
    target_id: &str,
    op: DriveOperation,
    rules: &[FolderPermissionRule],
) -> Result<FileTargetDecision> {
    let target = files_api.get_metadata(target_id).await?;
    if target.mime_type == GOOGLE_FOLDER_MIME_TYPE {
        let decision = folder_ancestry::resolve_decision_from(files_api, target, op, rules).await?;
        let requires_lease =
            write_gate::decided_rule_requires_lease(decision.decided_by.as_ref(), op, rules);
        return Ok(FileTargetDecision {
            decision,
            resolved_folder_id: None,
            source: DecisionSource::FolderChain,
            requires_lease,
        });
    }
    folder_ancestry::resolve_decision_for_file_target(files_api, &target, op, rules).await
}

/// The `evaluated_via` string for a [`DecisionSource`].
///
/// Kebab-case to match every other machine-readable string this CLI emits.
const fn evaluated_via(source: DecisionSource) -> &'static str {
    match source {
        DecisionSource::FileRule => "file-rule",
        DecisionSource::FolderChain => "folder-chain",
        DecisionSource::NoVisibleParents => "no-visible-parents",
    }
}

/// Whether `print_report` should emit the `no visible parents` note.
///
/// Gated on the verdict as well as the source. `read` defaults to
/// [`Verdict::Allow`] on an empty chain, so a link-shared target checked for
/// `read` reaches the renderer having been *permitted* — advice on how to
/// grant it would read as a refusal that isn't one. The note only ever helps
/// an operator staring at a `deny` they cannot name a folder rule to fix.
fn should_note_no_visible_parents(evaluated_via: &str, verdict: &str) -> bool {
    evaluated_via == "no-visible-parents" && verdict == "deny"
}

/// Prints a `CheckReport` in the plain-text (non-`output_as`) form.
fn print_report(report: &CheckReport) {
    println!("target:     {}", sanitize_for_terminal(&report.target_id));
    println!("operation:  {}", report.operation);
    println!("verdict:    {}", report.verdict);
    match (&report.decided_by_folder_id, report.decided_by_depth) {
        (Some(folder_id), Some(depth)) => {
            println!(
                "decided by: rule on folder {} (depth {depth})",
                sanitize_for_terminal(folder_id)
            );
        }
        _ => match &report.decided_by_file_id {
            Some(file_id) => println!(
                "decided by: rule on file {}",
                sanitize_for_terminal(file_id)
            ),
            None => println!("decided by: default policy (no matching rule)"),
        },
    }
    if report.verdict == "allow" {
        println!(
            "lease:      {}",
            if report.requires_lease {
                "required"
            } else {
                "not required"
            }
        );
    }
    // The one line this diagnostic exists to print: it names the *only*
    // rule shape that could ever change this verdict.
    if should_note_no_visible_parents(&report.evaluated_via, &report.verdict) {
        println!(
            "note:       this target has no parent folder visible to this account, so no\n\
             \x20           folder_id rule can apply — grant it with a file_id rule instead"
        );
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    #[test]
    fn slides_operation_maps_to_the_distinct_engine_grant() {
        assert_eq!(
            super::DriveOperation::from(super::OperationArg::SlidesWrite),
            super::DriveOperation::SlidesWrite
        );
    }

    use super::*;
    use crate::drive::auth::{DriveCredentials, DriveGrantedScopes};
    use crate::utils::secret::Secret;

    #[test]
    fn operation_arg_maps_onto_every_drive_operation() {
        assert_eq!(
            DriveOperation::from(OperationArg::Read),
            DriveOperation::Read
        );
        assert_eq!(
            DriveOperation::from(OperationArg::Create),
            DriveOperation::Create
        );
        assert_eq!(
            DriveOperation::from(OperationArg::Upload),
            DriveOperation::Upload
        );
        assert_eq!(
            DriveOperation::from(OperationArg::Edit),
            DriveOperation::Edit
        );
        assert_eq!(
            DriveOperation::from(OperationArg::SheetsWrite),
            DriveOperation::SheetsWrite
        );
        assert_eq!(
            DriveOperation::from(OperationArg::SheetsStructure),
            DriveOperation::SheetsStructure
        );
        assert_eq!(
            DriveOperation::from(OperationArg::SheetsDelete),
            DriveOperation::SheetsDelete
        );
        assert_eq!(
            DriveOperation::from(OperationArg::SheetsProtection),
            DriveOperation::SheetsProtection
        );
        assert_eq!(
            DriveOperation::from(OperationArg::DocsWrite),
            DriveOperation::DocsWrite
        );
    }

    #[test]
    fn trash_operation_maps_to_the_gate() {
        assert_eq!(
            DriveOperation::from(OperationArg::Trash),
            DriveOperation::Trash
        );
    }

    fn test_credentials() -> DriveCredentials {
        DriveCredentials {
            client_id: "client-1".to_string(),
            client_secret: Secret::new("secret-1"),
            refresh_token: Secret::new("refresh-1"),
            scope: DriveGrantedScopes::READONLY,
        }
    }

    async fn client_with_bootstrapped_token(server: &wiremock::MockServer) -> DriveClient {
        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 = DriveClient::new(&server.uri(), &test_credentials()).unwrap();
        crate::drive::client::test_support::replace_session(
            &mut client,
            &test_credentials(),
            &format!("{}/token", server.uri()),
        );
        client
    }

    fn rule(folder_id: &str, recursive: bool, allow: &[DriveOperation]) -> FolderPermissionRule {
        FolderPermissionRule::folder(folder_id)
            .recursive(recursive)
            .allowing(allow.iter().copied())
    }

    fn file_rule(file_id: &str, allow: &[DriveOperation]) -> FolderPermissionRule {
        FolderPermissionRule::file(file_id).allowing(allow.iter().copied())
    }

    #[tokio::test]
    async fn folder_target_evaluates_from_itself() {
        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("/drive/v3/files/folder-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "folder-1", "name": "folder-1", "mimeType": GOOGLE_FOLDER_MIME_TYPE,
                })),
            )
            // Exactly once: evaluate_target must reuse the metadata it
            // already fetched to decide the target is a folder, not
            // re-fetch it as the ancestor walk's own first call.
            .expect(1)
            .mount(&server)
            .await;
        let files_api = FilesApi::new(&client);
        let rules = [rule("folder-1", false, &[DriveOperation::Create])];

        let decision = evaluate_target(&files_api, "folder-1", DriveOperation::Create, &rules)
            .await
            .unwrap();
        assert_eq!(decision.decision.verdict, Verdict::Allow);
    }

    #[tokio::test]
    async fn requires_lease_ignores_a_same_folder_rule_for_a_different_operation() {
        // Regression test (issue #1664): a `Create` rule on `folder-1`
        // opts out of the lease; an unrelated `Upload` rule on the same
        // folder/depth (which does not opt out) must not make a `Create`
        // check say `requires_lease: true` — a rule that doesn't govern
        // the operation being checked isn't "matching".
        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("/drive/v3/files/folder-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "folder-1", "name": "folder-1", "mimeType": GOOGLE_FOLDER_MIME_TYPE,
                })),
            )
            .mount(&server)
            .await;
        let files_api = FilesApi::new(&client);
        let rules = [
            FolderPermissionRule::folder("folder-1")
                .allowing([DriveOperation::Create])
                .requiring_lease(false),
            FolderPermissionRule::folder("folder-1").allowing([DriveOperation::Upload]),
        ];

        let decision = evaluate_target(&files_api, "folder-1", DriveOperation::Create, &rules)
            .await
            .unwrap();
        assert_eq!(decision.decision.verdict, Verdict::Allow);
        assert!(!decision.requires_lease);
    }

    #[tokio::test]
    async fn create_upload_read_and_trash_never_report_requires_lease() {
        // issue #1917: neither `create.rs` nor `upload.rs` ever gates on
        // `require_lease`, and `read` never mutates anything at all, so
        // `run_check`'s diagnostic must say `requires_lease: false`
        // regardless of what the resolved decision's own (otherwise
        // correct) `requires_lease` reports — even when an explicit
        // matching rule leaves `require_lease` at its default `true`.
        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("/drive/v3/files/folder-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "folder-1", "name": "folder-1", "mimeType": GOOGLE_FOLDER_MIME_TYPE,
                })),
            )
            .mount(&server)
            .await;
        let files_api = FilesApi::new(&client);
        let rules = [rule(
            "folder-1",
            false,
            &[
                DriveOperation::Create,
                DriveOperation::Upload,
                DriveOperation::Trash,
                DriveOperation::Read,
            ],
        )];

        for op in [
            DriveOperation::Create,
            DriveOperation::Upload,
            DriveOperation::Read,
            DriveOperation::Trash,
        ] {
            let evaluated = evaluate_target(&files_api, "folder-1", op, &rules)
                .await
                .unwrap();
            assert_eq!(evaluated.decision.verdict, Verdict::Allow);
            assert!(
                evaluated.requires_lease,
                "sanity: the raw decision should still say a lease is required for {op:?} \
                 before `run_check`'s override is applied"
            );
            let requires_lease = op.ever_requires_lease() && evaluated.requires_lease;
            assert!(!requires_lease, "{op:?} should never report requires_lease");
        }
    }

    #[tokio::test]
    async fn run_check_assembles_the_report_from_the_evaluated_decision() {
        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("/drive/v3/files/folder-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "folder-1", "name": "folder-1", "mimeType": GOOGLE_FOLDER_MIME_TYPE,
                })),
            )
            .mount(&server)
            .await;
        let rules = [rule("folder-1", false, &[DriveOperation::Create])];

        run_check(
            &client,
            "folder-1",
            DriveOperation::Create,
            &rules,
            &OutputFormat::Json,
        )
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn run_check_prints_a_deny_verdict_in_table_format() {
        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("/drive/v3/files/folder-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "folder-1", "name": "folder-1", "mimeType": GOOGLE_FOLDER_MIME_TYPE,
                })),
            )
            .mount(&server)
            .await;

        // No rules at all: default policy denies Create, and the Table
        // format exercises run_check's print_report call (JSON always
        // short-circuits before it).
        run_check(
            &client,
            "folder-1",
            DriveOperation::Create,
            &[],
            &OutputFormat::Table,
        )
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn file_target_evaluates_from_its_parent() {
        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("/drive/v3/files/file-1"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": "file-1", "name": "file-1", "mimeType": "text/plain", "parents": ["folder-1"],
            })))
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/folder-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "folder-1", "name": "folder-1", "mimeType": GOOGLE_FOLDER_MIME_TYPE,
                })),
            )
            .mount(&server)
            .await;
        let files_api = FilesApi::new(&client);
        let rules = [rule("folder-1", false, &[DriveOperation::Edit])];

        let decision = evaluate_target(&files_api, "file-1", DriveOperation::Edit, &rules)
            .await
            .unwrap();
        assert_eq!(decision.decision.verdict, Verdict::Allow);
    }

    #[tokio::test]
    async fn orphan_file_uses_default_policy() {
        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("/drive/v3/files/orphan"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "orphan", "name": "orphan", "mimeType": "text/plain",
                })),
            )
            .mount(&server)
            .await;
        let files_api = FilesApi::new(&client);

        let decision = evaluate_target(&files_api, "orphan", DriveOperation::Read, &[])
            .await
            .unwrap();
        assert_eq!(decision.decision.verdict, Verdict::Allow);
        let decision = evaluate_target(&files_api, "orphan", DriveOperation::Edit, &[])
            .await
            .unwrap();
        assert_eq!(decision.decision.verdict, Verdict::Deny);
    }

    #[tokio::test]
    async fn multi_parent_file_denies_when_any_parent_denies() {
        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("/drive/v3/files/file-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "file-1", "name": "file-1", "mimeType": "text/plain",
                    "parents": ["allow-parent", "deny-parent"],
                })),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/allow-parent"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": "allow-parent", "name": "allow-parent", "mimeType": GOOGLE_FOLDER_MIME_TYPE,
            })))
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/deny-parent"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "deny-parent", "name": "deny-parent", "mimeType": GOOGLE_FOLDER_MIME_TYPE,
                })),
            )
            .mount(&server)
            .await;
        let files_api = FilesApi::new(&client);
        let rules = [rule("allow-parent", false, &[DriveOperation::Edit])];

        let decision = evaluate_target(&files_api, "file-1", DriveOperation::Edit, &rules)
            .await
            .unwrap();
        assert_eq!(
            decision.decision.verdict,
            Verdict::Deny,
            "deny-parent has no matching rule and edit defaults deny, which must win over allow-parent"
        );
    }

    #[tokio::test]
    async fn ancestor_chain_fetch_failure_propagates_as_err() {
        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("/drive/v3/files/folder-1"))
            .respond_with(wiremock::ResponseTemplate::new(500).set_body_string("server error"))
            .mount(&server)
            .await;
        let files_api = FilesApi::new(&client);

        let result = evaluate_target(&files_api, "folder-1", DriveOperation::Read, &[]).await;
        assert!(result.is_err());
    }

    #[test]
    fn print_report_no_match_says_default_policy() {
        let report = CheckReport {
            target_id: "f1".to_string(),
            operation: "create".to_string(),
            verdict: "deny".to_string(),
            decided_by_folder_id: None,
            decided_by_depth: None,
            decided_by_file_id: None,
            evaluated_via: "folder-chain".to_string(),
            requires_lease: true,
        };
        // Smoke test only — print_report writes to stdout directly.
        print_report(&report);
    }

    #[test]
    fn print_report_renders_a_file_rule_and_the_no_visible_parents_note() {
        print_report(&CheckReport {
            target_id: "x1".to_string(),
            operation: "sheets-write".to_string(),
            verdict: "allow".to_string(),
            decided_by_folder_id: None,
            decided_by_depth: None,
            decided_by_file_id: Some("x1".to_string()),
            evaluated_via: "file-rule".to_string(),
            requires_lease: true,
        });
        print_report(&CheckReport {
            target_id: "x2".to_string(),
            operation: "sheets-write".to_string(),
            verdict: "deny".to_string(),
            decided_by_folder_id: None,
            decided_by_depth: None,
            decided_by_file_id: None,
            evaluated_via: "no-visible-parents".to_string(),
            requires_lease: true,
        });
    }

    #[test]
    fn print_report_renders_an_allow_that_does_not_require_a_lease() {
        print_report(&CheckReport {
            target_id: "x3".to_string(),
            operation: "create".to_string(),
            verdict: "allow".to_string(),
            decided_by_folder_id: Some("folder-1".to_string()),
            decided_by_depth: Some(0),
            decided_by_file_id: None,
            evaluated_via: "folder-chain".to_string(),
            requires_lease: false,
        });
    }

    #[test]
    fn the_no_visible_parents_note_is_gated_on_a_deny() {
        assert!(should_note_no_visible_parents("no-visible-parents", "deny"));
        // `read` defaults to allow on an empty chain, so this pairing is
        // reachable — and must not advise granting what was permitted.
        assert!(!should_note_no_visible_parents(
            "no-visible-parents",
            "allow"
        ));
        assert!(!should_note_no_visible_parents("folder-chain", "deny"));
        assert!(!should_note_no_visible_parents("file-rule", "deny"));
    }

    #[test]
    fn evaluated_via_maps_every_decision_source() {
        assert_eq!(evaluated_via(DecisionSource::FileRule), "file-rule");
        assert_eq!(evaluated_via(DecisionSource::FolderChain), "folder-chain");
        assert_eq!(
            evaluated_via(DecisionSource::NoVisibleParents),
            "no-visible-parents"
        );
    }

    // ── file-id rules (issue #1612) ────────────────────────────────────

    /// Mounts `GET /drive/v3/files/<id>` returning a plain file with
    /// `parents`.
    fn mount_plain_file(id: &'static str, parents: &[&str]) -> wiremock::Mock {
        let parents: Vec<String> = parents.iter().map(|p| (*p).to_string()).collect();
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(format!("/drive/v3/files/{id}")))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": id, "name": id, "mimeType": "text/plain", "parents": parents,
                })),
            )
    }

    #[tokio::test]
    async fn a_file_rule_decides_a_file_target_without_walking_its_parents() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        // `never-mounted` is deliberately absent: wiremock panics if the
        // ancestor walk happens at all.
        mount_plain_file("file-1", &["never-mounted"])
            .mount(&server)
            .await;
        let files_api = FilesApi::new(&client);
        let rules = [file_rule("file-1", &[DriveOperation::SheetsWrite])];

        let evaluated = evaluate_target(&files_api, "file-1", DriveOperation::SheetsWrite, &rules)
            .await
            .unwrap();

        assert_eq!(evaluated.decision.verdict, Verdict::Allow);
        assert_eq!(evaluated.source, DecisionSource::FileRule);
    }

    #[tokio::test]
    async fn a_parentless_file_target_is_reported_as_no_visible_parents() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        mount_plain_file("file-1", &[]).mount(&server).await;
        let files_api = FilesApi::new(&client);

        let evaluated = evaluate_target(&files_api, "file-1", DriveOperation::Edit, &[])
            .await
            .unwrap();

        assert_eq!(evaluated.source, DecisionSource::NoVisibleParents);
        assert_eq!(evaluated.decision.verdict, Verdict::Deny);
    }

    #[tokio::test]
    async fn no_visible_parents_still_answers_allow_for_read() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        mount_plain_file("file-1", &[]).mount(&server).await;
        let files_api = FilesApi::new(&client);

        let evaluated = evaluate_target(&files_api, "file-1", DriveOperation::Read, &[])
            .await
            .unwrap();

        assert_eq!(evaluated.decision.verdict, Verdict::Allow);
        assert_eq!(evaluated.source, DecisionSource::NoVisibleParents);
    }

    #[tokio::test]
    async fn a_file_rule_does_not_apply_to_a_folder_target() {
        // A folder target means "create/upload something inside this", and
        // a `file_id` rule naming a folder id would just be a worse
        // spelling of a non-recursive `folder_id` rule. Deliberately inert.
        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("/drive/v3/files/folder-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "folder-1", "name": "folder-1", "mimeType": GOOGLE_FOLDER_MIME_TYPE,
                })),
            )
            .mount(&server)
            .await;
        let files_api = FilesApi::new(&client);
        let rules = [file_rule("folder-1", &[DriveOperation::Create])];

        let evaluated = evaluate_target(&files_api, "folder-1", DriveOperation::Create, &rules)
            .await
            .unwrap();

        assert_eq!(
            evaluated.decision.verdict,
            Verdict::Deny,
            "a file_id rule must not grant a folder target"
        );
        assert_eq!(evaluated.decision.decided_by, None);
    }
    #[test]
    fn docs_delete_operation_arg_maps_to_the_separate_gate() {
        assert_eq!(
            DriveOperation::from(OperationArg::DocsDelete),
            DriveOperation::DocsDelete
        );
    }
}