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
//! `drive docs create` engine — creates a Google Doc, optionally seeded with
//! text (issue #1615, [ADR-0076](../../../docs/adrs/adr-0076.md) §9).
//!
//! Owns its verb rather than composing `drive create`'s public engine, which
//! logs internally and unconditionally — composing it would emit a phantom
//! `["drive","create"]` record for a command the user never typed, alongside
//! the `docs-create` one. Same reasoning as `sheets/create.rs`.
//!
//! One of ADR-0073 §11's arguments is *stronger* here, and it is worth
//! stating plainly: `documents.create` accepts only a title and drops the
//! new document in the caller's My Drive root — it **cannot set a parent
//! folder**. Since the folder is the write gate's entire input, going
//! through `FilesApi::create` is not merely the tidier option, it is the
//! only shape the gate can evaluate at all.
//!
//! The optional `--text` seed costs a second `documents.get`, purely to mint
//! a lease for a document created milliseconds earlier. That round-trip is
//! paid deliberately rather than adding a "we just made it, nobody can have
//! touched it" unleased write path — which is exactly the escape hatch the
//! next caller reaches for, and whose existence would void both the type
//! fence and the grep guard in `write_types.rs`/`api.rs`.

use std::time::{Duration, Instant};

use serde::Serialize;

use crate::cli::drive::format::{write_scalar_jsonl, JsonlSerialize};
use crate::drive::client::DriveClient;
use crate::drive::docs::api::{DocsApi, SuggestionsViewMode};
use crate::drive::docs::client::DocsClient;
use crate::drive::docs::write_types::DocsRequest;
use crate::drive::files_api::FilesApi;
use crate::drive::folder_ancestry;
use crate::drive::types::GOOGLE_DOC_MIME_TYPE;
use crate::drive::write_gate::{self, DecidingRule, DriveOperation, FolderPermissionRule};
use crate::request_log::{self, DriveMutationOutcome};

/// Per-call options.
#[derive(Debug, Clone)]
pub struct CreateOptions {
    /// The new document's title.
    pub name: String,
    /// The folder to create it in — also the gate's input.
    pub parent_folder_id: String,
    /// Optional initial body text.
    pub text: Option<String>,
    /// Classify and preview, but create nothing.
    pub dry_run: bool,
}

/// What happened (or, under `--dry-run`, would happen).
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
#[serde(tag = "status", rename_all = "kebab-case")]
pub enum CreateResult {
    /// A dry run.
    WouldCreate {
        /// Unicode scalar values that would be seeded.
        chars: usize,
        /// UTF-8 bytes that would be seeded.
        bytes: usize,
    },
    /// The gate refused it.
    Blocked {
        /// The rule that decided, when one did.
        decided_by: Option<DecidingRule>,
    },
    /// Created, and seeded if `--text` was given.
    Created {
        /// The new document's id.
        file_id: String,
        /// Characters seeded, when `--text` was given.
        #[serde(skip_serializing_if = "Option::is_none")]
        seeded_chars: Option<usize>,
    },
    /// Created, but the seeding write failed.
    ///
    /// Carries the ID because automatic rollback is not authorised by a
    /// create grant. The operator may explicitly trash the empty document
    /// with a separate `trash` permission; plain failure would hide its ID.
    CreatedTextFailed {
        /// The new document's id, so it is findable.
        file_id: String,
        /// Why the seed failed.
        detail: String,
    },
    /// Anything else.
    Failed {
        /// The error, verbatim.
        detail: String,
    },
}

impl CreateResult {
    /// The kebab-case status for the request log.
    const fn log_status(&self) -> &'static str {
        match self {
            Self::WouldCreate { .. } => "would-create",
            Self::Blocked { .. } => "blocked",
            Self::Created { .. } => "created",
            Self::CreatedTextFailed { .. } => "created-text-failed",
            Self::Failed { .. } => "failed",
        }
    }
}

/// The full outcome of one attempt.
///
/// Serialised by hand (below) so the JSON carries `parent_folder_id`, the
/// name `drive create` and `sheets create` use for the same field, while
/// still emitting the `resolved_folder_id` this verb shipped with, so
/// existing consumers keep working (#1941).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CreateOutcome {
    /// The requested title.
    pub name: String,
    /// The folder the document is created in, which the gate evaluated
    /// against.
    pub parent_folder_id: String,
    /// What happened.
    pub result: CreateResult,
}

impl Serialize for CreateOutcome {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        #[derive(Serialize)]
        struct Wire<'a> {
            name: &'a str,
            parent_folder_id: &'a str,
            /// The original name for `parent_folder_id`, kept for
            /// compatibility.
            resolved_folder_id: &'a str,
            result: &'a CreateResult,
        }
        Wire {
            name: &self.name,
            parent_folder_id: &self.parent_folder_id,
            resolved_folder_id: &self.parent_folder_id,
            result: &self.result,
        }
        .serialize(serializer)
    }
}

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

/// Creates a document, optionally seeding it, logging every non-dry attempt.
///
/// Never returns `Err`: every failure is a [`CreateResult`] variant.
pub async fn create(
    drive: &DriveClient,
    docs: &DocsClient,
    opts: &CreateOptions,
    rules: &[FolderPermissionRule],
) -> CreateOutcome {
    let started = Instant::now();
    let outcome = create_inner(drive, docs, opts, rules).await;
    if !opts.dry_run {
        record_attempt(&outcome, started.elapsed());
    }
    outcome
}

async fn create_inner(
    drive: &DriveClient,
    docs: &DocsClient,
    opts: &CreateOptions,
    rules: &[FolderPermissionRule],
) -> CreateOutcome {
    let finish = |result| CreateOutcome {
        name: opts.name.clone(),
        parent_folder_id: opts.parent_folder_id.clone(),
        result,
    };

    let files_api = FilesApi::new(drive);
    let decision = match folder_ancestry::resolve_decision(
        &files_api,
        &opts.parent_folder_id,
        DriveOperation::Create,
        rules,
    )
    .await
    {
        Ok(decision) => decision,
        Err(err) => {
            return finish(CreateResult::Failed {
                detail: err.to_string(),
            })
        }
    };

    if decision.verdict == write_gate::Verdict::Deny {
        return finish(CreateResult::Blocked {
            decided_by: decision.decided_by,
        });
    }

    // An explicit `deny: ["docs-write"]` on this folder still refuses the
    // seed, even though `Create` alone authorises it otherwise — see this
    // module's header and ADR-0076 §9. `decided_by.is_some()` is what
    // distinguishes that deliberate signal from the bare default policy (no
    // rule mentions `docs-write` at all), which must **not** block a folder
    // that only grants `create`.
    if opts.text.is_some() {
        let docs_write_decision = match folder_ancestry::resolve_decision(
            &files_api,
            &opts.parent_folder_id,
            DriveOperation::DocsWrite,
            rules,
        )
        .await
        {
            Ok(decision) => decision,
            Err(err) => {
                return finish(CreateResult::Failed {
                    detail: err.to_string(),
                })
            }
        };
        if docs_write_decision.verdict == write_gate::Verdict::Deny
            && docs_write_decision.decided_by.is_some()
        {
            return finish(CreateResult::Blocked {
                decided_by: docs_write_decision.decided_by,
            });
        }
    }

    let (chars, bytes) = opts
        .text
        .as_ref()
        .map_or((0, 0), |text| (text.chars().count(), text.len()));

    if opts.dry_run {
        return finish(CreateResult::WouldCreate { chars, bytes });
    }

    let created = match files_api
        .create(&opts.name, &opts.parent_folder_id, GOOGLE_DOC_MIME_TYPE)
        .await
    {
        Ok(created) => created,
        Err(err) => {
            return finish(CreateResult::Failed {
                detail: err.to_string(),
            })
        }
    };

    let Some(text) = opts.text.as_ref() else {
        return finish(CreateResult::Created {
            file_id: created.id,
            seeded_chars: None,
        });
    };

    // The seed pays for its own lease rather than taking an unleased path.
    let api = DocsApi::new(docs);
    let document = match api
        .get_document(&created.id, SuggestionsViewMode::default())
        .await
    {
        Ok(document) => document,
        Err(err) => {
            return finish(CreateResult::CreatedTextFailed {
                file_id: created.id,
                detail: err.to_string(),
            })
        }
    };
    // A document this invocation just created should always carry a
    // revision id — the account plainly has edit access to it — so this is
    // folded into the partial-failure variant rather than given a variant
    // that could never fire.
    let Some(revision_id) = document.revision_id else {
        return finish(CreateResult::CreatedTextFailed {
            file_id: created.id,
            detail: "the new document returned no revision id, so the seed could not be leased"
                .to_string(),
        });
    };

    match api
        .batch_update(
            &created.id,
            DocsRequest::insert_text_at_end(text),
            &revision_id,
        )
        .await
    {
        Ok(_) => finish(CreateResult::Created {
            file_id: created.id,
            seeded_chars: Some(chars),
        }),
        // A stale lease is not realistically reachable on a document created
        // milliseconds earlier, so it is absorbed here rather than given its
        // own variant; the detail carries the server's message either way.
        Err(err) => finish(CreateResult::CreatedTextFailed {
            file_id: created.id,
            detail: err.to_string(),
        }),
    }
}

/// Emits the `kind: "drivemutation"` record.
///
/// The seed **text is never recorded**, only its size — same reasoning as
/// `write.rs::record_attempt`.
fn record_attempt(outcome: &CreateOutcome, duration: Duration) {
    let error = match &outcome.result {
        CreateResult::Failed { detail } | CreateResult::CreatedTextFailed { detail, .. } => {
            Some(detail.clone())
        }
        _ => None,
    };
    let decided_by = match &outcome.result {
        CreateResult::Blocked { decided_by } => decided_by.as_ref(),
        _ => None,
    };
    let decided_by = write_gate::decided_by_log_fields(decided_by);
    let file_id = match &outcome.result {
        CreateResult::Created { file_id, .. } | CreateResult::CreatedTextFailed { file_id, .. } => {
            file_id.clone()
        }
        _ => String::new(),
    };
    let inserted_chars = match &outcome.result {
        CreateResult::Created {
            seeded_chars: Some(chars),
            ..
        } => Some(*chars as i64),
        _ => None,
    };

    request_log::record_drive_mutation(DriveMutationOutcome {
        operation: "docs-create",
        file_id,
        file_name: outcome.name.clone(),
        status: outcome.result.log_status().to_string(),
        resolved_folder_id: Some(outcome.parent_folder_id.clone()),
        decided_by_folder_id: decided_by.folder_id,
        decided_by_depth: decided_by.depth,
        decided_by_file_id: decided_by.file_id,
        inserted_chars,
        error,
        duration,
        ..Default::default()
    });
}

/// Renders an outcome as a single human-readable line.
#[must_use]
pub fn describe(outcome: &CreateOutcome) -> String {
    let name = &outcome.name;
    let folder = &outcome.parent_folder_id;
    match &outcome.result {
        CreateResult::WouldCreate { chars, bytes } if *chars > 0 => format!(
            "Would create: document '{name}' in {folder}, seeded with {chars} char(s) / \
             {bytes} byte(s)"
        ),
        CreateResult::WouldCreate { .. } => {
            format!("Would create: document '{name}' in {folder}")
        }
        CreateResult::Blocked { decided_by } => match decided_by {
            Some(rule) => format!(
                "Blocked: '{name}' in {folder} — refused by rule on {} {}{}",
                rule.kind_label(),
                rule.id(),
                rule.depth_suffix()
            ),
            None => format!(
                "Blocked: '{name}' in {folder} — refused by default policy (no matching rule)"
            ),
        },
        CreateResult::Created {
            file_id,
            seeded_chars,
        } => match seeded_chars {
            Some(chars) => {
                format!("Created: '{name}' ({file_id}) in {folder}, seeded with {chars} char(s)")
            }
            None => format!("Created: '{name}' ({file_id}) in {folder}"),
        },
        CreateResult::CreatedTextFailed { file_id, detail } => format!(
            "Partially failed: created '{name}' ({file_id}) in {folder}, but seeding its text \
             failed: {detail} The document exists and is empty — it cannot be rolled back \
             automatically. Clean up explicitly with `omni-dev drive trash {file_id}` \
             (requires trash permission on the file or its folder)."
        ),
        CreateResult::Failed { detail } => format!("Failed: '{name}' in {folder}: {detail}"),
    }
}

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

    use crate::drive::auth::{DriveCredentials, DriveGrantedScopes};
    use crate::drive::docs::client::DOCS_API_URL;
    use crate::test_support::env::MapEnv;
    use crate::utils::secret::Secret;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    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 clients(server: &MockServer) -> (DriveClient, DocsClient) {
        Mock::given(method("POST"))
            .and(path("/token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "access_token": "test-token", "expires_in": 3600,
            })))
            .mount(server)
            .await;
        let mut drive = DriveClient::new(&server.uri(), &test_credentials()).unwrap();
        crate::drive::client::test_support::replace_session(
            &mut drive,
            &test_credentials(),
            &format!("{}/token", server.uri()),
        );
        let env = MapEnv::new().with(DOCS_API_URL, &server.uri());
        let docs = DocsClient::from_drive_client_with(&env, &drive).unwrap();
        (drive, docs)
    }

    fn mount_folder(id: &str) -> Mock {
        Mock::given(method("GET"))
            .and(path(format!("/drive/v3/files/{id}")))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": id, "name": id,
                "mimeType": "application/vnd.google-apps.folder", "parents": [],
            })))
    }

    fn mount_files_create() -> Mock {
        Mock::given(method("POST"))
            .and(path("/drive/v3/files"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": "new-1", "name": "New Doc", "mimeType": GOOGLE_DOC_MIME_TYPE,
            })))
    }

    fn mount_new_document(revision: Option<&str>) -> Mock {
        let mut body = serde_json::json!({"documentId": "new-1", "body": {"content": []}});
        if let Some(revision) = revision {
            body["revisionId"] = serde_json::json!(revision);
        }
        Mock::given(method("GET"))
            .and(path("/v1/documents/new-1"))
            .respond_with(ResponseTemplate::new(200).set_body_json(body))
    }

    fn rule(ops: &[DriveOperation], denies: &[DriveOperation]) -> FolderPermissionRule {
        FolderPermissionRule {
            folder_id: Some("folder-1".to_string()),
            file_id: None,
            recursive: true,
            allow: ops.iter().copied().collect(),
            deny: denies.iter().copied().collect::<HashSet<_>>(),
            require_lease: true,
        }
    }

    fn opts(text: Option<&str>, dry_run: bool) -> CreateOptions {
        CreateOptions {
            name: "New Doc".to_string(),
            parent_folder_id: "folder-1".to_string(),
            text: text.map(str::to_string),
            dry_run,
        }
    }

    /// The JSON names the folder `parent_folder_id`, as `drive create` and
    /// `sheets create` do, and keeps the original `resolved_folder_id`.
    #[test]
    fn json_carries_parent_folder_id_and_the_legacy_resolved_folder_id() {
        let outcome = CreateOutcome {
            name: "Notes".to_string(),
            parent_folder_id: "folder-1".to_string(),
            result: CreateResult::Created {
                file_id: "doc-1".to_string(),
                seeded_chars: None,
            },
        };
        let json = serde_json::to_value(&outcome).unwrap();
        assert_eq!(json["parent_folder_id"], "folder-1");
        assert_eq!(json["resolved_folder_id"], "folder-1");
        assert_eq!(json["name"], "Notes");
        assert_eq!(json["result"]["file_id"], "doc-1");
    }
    #[tokio::test]
    async fn create_without_text_makes_one_files_create_and_zero_docs_calls() {
        let server = MockServer::start().await;
        let (drive, docs) = clients(&server).await;
        mount_folder("folder-1").mount(&server).await;
        mount_files_create().expect(1).mount(&server).await;
        // No Docs mocks: an unseeded create must not touch the Docs API.

        let outcome = create(
            &drive,
            &docs,
            &opts(None, false),
            &[rule(&[DriveOperation::Create], &[])],
        )
        .await;
        assert_eq!(
            outcome.result,
            CreateResult::Created {
                file_id: "new-1".to_string(),
                seeded_chars: None,
            }
        );
    }

    /// ADR-0076 §9: the seed mints its own lease rather than writing
    /// unleased, so a `documents.get` on the *new* id must precede the
    /// batchUpdate and its revision must be presented.
    #[tokio::test]
    async fn create_with_text_reads_the_new_document_for_a_lease_before_seeding() {
        let server = MockServer::start().await;
        let (drive, docs) = clients(&server).await;
        mount_folder("folder-1").mount(&server).await;
        mount_files_create().mount(&server).await;
        mount_new_document(Some("rev-new"))
            .expect(1)
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/v1/documents/new-1:batchUpdate"))
            .and(wiremock::matchers::body_partial_json(serde_json::json!({
                "writeControl": {"requiredRevisionId": "rev-new"},
            })))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"documentId": "new-1", "replies": [{}]})),
            )
            .expect(1)
            .mount(&server)
            .await;

        let outcome = create(
            &drive,
            &docs,
            &opts(Some("hello"), false),
            &[rule(&[DriveOperation::Create], &[])],
        )
        .await;
        assert_eq!(
            outcome.result,
            CreateResult::Created {
                file_id: "new-1".to_string(),
                seeded_chars: Some(5),
            }
        );
    }

    /// There is no `files.delete` in this integration, so a failed seed must
    /// name the orphan rather than report a clean failure.
    #[tokio::test]
    async fn a_seed_failure_reports_created_text_failed_carrying_the_id() {
        let server = MockServer::start().await;
        let (drive, docs) = clients(&server).await;
        mount_folder("folder-1").mount(&server).await;
        mount_files_create().mount(&server).await;
        mount_new_document(Some("rev-new")).mount(&server).await;
        Mock::given(method("POST"))
            .and(path("/v1/documents/new-1:batchUpdate"))
            .respond_with(ResponseTemplate::new(500))
            .mount(&server)
            .await;

        let outcome = create(
            &drive,
            &docs,
            &opts(Some("hello"), false),
            &[rule(&[DriveOperation::Create], &[])],
        )
        .await;
        match &outcome.result {
            CreateResult::CreatedTextFailed { file_id, .. } => assert_eq!(file_id, "new-1"),
            other => panic!("expected CreatedTextFailed, got {other:?}"),
        }
        let text = describe(&outcome);
        assert!(
            text.contains("new-1"),
            "the orphan must be findable: {text}"
        );
        assert!(text.contains("cannot be rolled back"), "{text}");
        assert!(text.contains("omni-dev drive trash new-1"), "{text}");
        assert!(text.contains("requires trash permission"), "{text}");
    }

    /// The ADR-0073 §11 / ADR-0076 §9 distinction: a bare default deny must
    /// **not** block the seed, or `--text` would be refused on every folder
    /// that grants only `create`.
    #[tokio::test]
    async fn a_bare_default_deny_does_not_block_the_seed() {
        let server = MockServer::start().await;
        let (drive, docs) = clients(&server).await;
        mount_folder("folder-1").mount(&server).await;
        mount_files_create().mount(&server).await;
        mount_new_document(Some("rev-new")).mount(&server).await;
        Mock::given(method("POST"))
            .and(path("/v1/documents/new-1:batchUpdate"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"documentId": "new-1", "replies": [{}]})),
            )
            .mount(&server)
            .await;

        // Grants `create` only — no rule mentions `docs-write` at all.
        let outcome = create(
            &drive,
            &docs,
            &opts(Some("hello"), false),
            &[rule(&[DriveOperation::Create], &[])],
        )
        .await;
        assert!(matches!(outcome.result, CreateResult::Created { .. }));
    }

    /// …but an *explicit* deny is a deliberate operator signal and is
    /// honoured, before anything is created.
    #[tokio::test]
    async fn an_explicit_docs_write_deny_blocks_the_seed_and_creates_nothing() {
        let server = MockServer::start().await;
        let (drive, docs) = clients(&server).await;
        mount_folder("folder-1").mount(&server).await;
        // No `files.create` mock: nothing may be created.

        let outcome = create(
            &drive,
            &docs,
            &opts(Some("hello"), false),
            &[rule(
                &[DriveOperation::Create],
                &[DriveOperation::DocsWrite],
            )],
        )
        .await;
        assert!(matches!(outcome.result, CreateResult::Blocked { .. }));
    }

    /// The same explicit deny must not block a create with *no* seed, since
    /// no text is written.
    #[tokio::test]
    async fn an_explicit_docs_write_deny_does_not_block_an_unseeded_create() {
        let server = MockServer::start().await;
        let (drive, docs) = clients(&server).await;
        mount_folder("folder-1").mount(&server).await;
        mount_files_create().mount(&server).await;

        let outcome = create(
            &drive,
            &docs,
            &opts(None, false),
            &[rule(
                &[DriveOperation::Create],
                &[DriveOperation::DocsWrite],
            )],
        )
        .await;
        assert!(matches!(outcome.result, CreateResult::Created { .. }));
    }

    #[tokio::test]
    async fn a_denied_create_is_blocked_and_creates_nothing() {
        let server = MockServer::start().await;
        let (drive, docs) = clients(&server).await;
        mount_folder("folder-1").mount(&server).await;

        let outcome = create(&drive, &docs, &opts(None, false), &[]).await;
        assert!(matches!(outcome.result, CreateResult::Blocked { .. }));
    }

    #[tokio::test]
    async fn dry_run_creates_nothing() {
        let server = MockServer::start().await;
        let (drive, docs) = clients(&server).await;
        mount_folder("folder-1").mount(&server).await;
        // No POST mocks at all.

        let outcome = create(
            &drive,
            &docs,
            &opts(Some("hello"), true),
            &[rule(&[DriveOperation::Create], &[])],
        )
        .await;
        assert_eq!(
            outcome.result,
            CreateResult::WouldCreate { chars: 5, bytes: 5 }
        );
        assert!(describe(&outcome).contains("seeded with 5 char(s)"));
    }
}