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
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
//! Drive file content edit — replaces an existing file's content (issue
//! #1574, [ADR-0071](../../docs/adrs/adr-0071.md)).
//!
//! The most structurally distinct of the three mutating verbs: unlike
//! `create`/`upload` (whose gate chain starts at the caller-given
//! `--parent`), `edit`'s chain starts at the target's *current* parent
//! folder(s) — `files.get` first, then
//! [`folder_ancestry::resolve_decision_for_file_target`], which consults a
//! `file_id` rule before the parents (issue #1612) and otherwise resolves
//! and combines a decision per parent for a legacy multi-parent file
//! (mirrors `visibility.rs`'s existing multi-parent-union contract; shared
//! with `drive permissions check`'s identical file-target case). A target
//! with no visible parent and no file rule is refused as
//! [`EditResult::RefusedNoVisibleParents`] rather than degenerating to a
//! bare default-policy `Blocked`.
//!
//! Still single-target, so this follows `create.rs`/`upload.rs`'s linear-
//! function shape, not `file_move.rs`'s batch Plan/Execute.

use std::path::PathBuf;
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::files_api::FilesApi;
use crate::drive::folder_ancestry;
use crate::drive::lease::check::{
    conclude_leased_write, gate_optional_leased_write, FromLeaseRefusal, LeaseGateRefusal,
    LeasedWrite,
};
use crate::drive::write_gate::{self, DecidingRule, DriveOperation, FolderPermissionRule};
use crate::request_log::{self, DriveMutationOutcome};

/// Per-call edit options.
#[derive(Debug, Clone)]
pub struct EditOptions {
    /// The file id to edit.
    pub file_id: String,
    /// The new content, already read into memory (and already
    /// size-checked) by the caller.
    pub content: Vec<u8>,
    /// The content's MIME type.
    pub content_type: String,
    /// When `true`, classify but never call `files.update`.
    pub dry_run: bool,
    /// The lease token presented via `--lease`. Checked only when the
    /// deciding rule requires one
    /// ([`write_gate::decided_rule_requires_lease`], ADR-0080 §1/§13);
    /// `None` is only ever valid when it does not.
    pub lease_token: Option<String>,
    /// Path to the lease ledger the token is checked against. Production
    /// callers pass `crate::drive::lease::ledger::ledger_path`'s own
    /// result; tests pass a path under a `tempdir`.
    pub ledger_path: PathBuf,
}

/// What happened (or, under `--dry-run`, would happen).
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "status", rename_all = "kebab-case")]
pub enum EditResult {
    /// `--dry-run`, and the gate would allow it.
    WouldEdit,
    /// The target is a Google-native document (Docs/Sheets/Slides/...)
    /// with no fixed byte content a raw media PATCH can replace. Checked
    /// client-side, before the gate — this isn't a policy decision, the
    /// operation is simply nonsensical for this target.
    RefusedNativeDocument,
    /// The target has no parents this account can see and no `file_id`
    /// rule named it, so nothing could grant it (issue #1612).
    ///
    /// Mirrors `crate::drive::sheets::write::WriteResult`'s variant of the
    /// same name. Before #1612 this case fell into `Blocked { decided_by:
    /// None }`, which reads as "no rule matched, fix your rules" when no
    /// *folder* rule the operator could write would have helped — the
    /// latent gap [ADR-0073](../../docs/adrs/adr-0073.md) §4 flagged for
    /// `drive edit`.
    RefusedNoVisibleParents,
    /// The folder write-permission gate refused it.
    Blocked {
        /// The rule that decided the refusal, if any.
        decided_by: Option<DecidingRule>,
    },
    /// No `--lease` was presented, and the deciding rule requires one
    /// (ADR-0080 §9).
    RefusedNoLease,
    /// The presented lease has expired, or was never a token this ledger
    /// knows about.
    RefusedLeaseExpired,
    /// The presented lease is bound to a different file id.
    RefusedLeaseWrongFile,
    /// The file has moved since the lease's recorded `version` — the
    /// staleness check (ADR-0080 §6).
    RefusedLeaseStale,
    /// `files.update` (media) succeeded.
    Edited,
    /// An API/validation error.
    Failed {
        /// A human-readable summary of what failed.
        detail: String,
    },
}

impl FromLeaseRefusal for EditResult {
    fn from_no_lease() -> Self {
        Self::RefusedNoLease
    }
    fn from_lease_expired() -> Self {
        Self::RefusedLeaseExpired
    }
    fn from_lease_wrong_file() -> Self {
        Self::RefusedLeaseWrongFile
    }
    fn from_lease_stale() -> Self {
        Self::RefusedLeaseStale
    }
    fn from_lease_failed(detail: String) -> Self {
        Self::Failed { detail }
    }
}

impl EditResult {
    /// The request-log `status` string — mirrors
    /// `CreateResult`/`UploadResult`/`MoveResult::log_status`'s precedent.
    fn log_status(&self) -> &'static str {
        match self {
            Self::WouldEdit => "would-edit",
            Self::RefusedNativeDocument => "refused-native-document",
            Self::RefusedNoVisibleParents => "refused-no-visible-parents",
            Self::Blocked { .. } => "blocked",
            Self::RefusedNoLease => LeaseGateRefusal::NoLease.log_status(),
            Self::RefusedLeaseExpired => LeaseGateRefusal::Expired.log_status(),
            Self::RefusedLeaseWrongFile => LeaseGateRefusal::WrongFile.log_status(),
            Self::RefusedLeaseStale => LeaseGateRefusal::Stale.log_status(),
            Self::Edited => "edited",
            Self::Failed { .. } => "failed",
        }
    }
}

/// The planned (and, after a real run, final) outcome of one `edit` call.
#[derive(Debug, Clone, Serialize)]
pub struct EditOutcome {
    /// The target file id.
    pub file_id: String,
    /// The file's name at the time of the attempt, once known (absent if
    /// the initial `files.get` itself failed).
    pub file_name: Option<String>,
    /// The folder the write-permission gate evaluated against — the
    /// target's resolved current parent, when the target has exactly one
    /// *and* the ancestor chain is what decided the verdict. `None` for an
    /// orphan target, a target refused before the gate ran
    /// (`RefusedNativeDocument`), a target with more than one current
    /// parent (no single folder to report), or a target decided by a
    /// `file_id` rule (issue #1612) — that short-circuits at depth −1
    /// before any parent is fetched, so no folder was evaluated even when
    /// the target has exactly one.
    pub resolved_folder_id: Option<String>,
    /// The result.
    pub result: EditResult,
}

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

/// Replaces `opts.file_id`'s content with `opts.content`, gated by `rules`.
///
/// Every real (non-dry-run) attempt is logged; a `--dry-run` preview never
/// is, matching `create`/`upload`/`move`'s existing precedent.
pub async fn edit(
    client: &DriveClient,
    opts: &EditOptions,
    rules: &[FolderPermissionRule],
) -> EditOutcome {
    let started = Instant::now();
    let outcome = edit_inner(client, opts, rules).await;
    if !opts.dry_run {
        record_attempt(&outcome, started.elapsed());
    }
    outcome
}

async fn edit_inner(
    client: &DriveClient,
    opts: &EditOptions,
    rules: &[FolderPermissionRule],
) -> EditOutcome {
    let files_api = FilesApi::new(client);
    let target = match files_api.get_metadata(&opts.file_id).await {
        Ok(target) => target,
        Err(err) => {
            return EditOutcome {
                file_id: opts.file_id.clone(),
                file_name: None,
                resolved_folder_id: None,
                result: EditResult::Failed {
                    detail: err.to_string(),
                },
            }
        }
    };

    if target.is_google_native() {
        return EditOutcome {
            file_id: opts.file_id.clone(),
            file_name: Some(target.name),
            resolved_folder_id: None,
            result: EditResult::RefusedNativeDocument,
        };
    }

    // A `file_id` rule is consulted before the parents are, so a file
    // shared by link or email can still be granted (issue #1612).
    let evaluated = match folder_ancestry::resolve_decision_for_file_target(
        &files_api,
        &target,
        DriveOperation::Edit,
        rules,
    )
    .await
    {
        Ok(evaluated) => evaluated,
        Err(err) => {
            return EditOutcome {
                file_id: opts.file_id.clone(),
                file_name: Some(target.name),
                resolved_folder_id: None,
                result: EditResult::Failed {
                    detail: err.to_string(),
                },
            }
        }
    };

    if evaluated.source == folder_ancestry::DecisionSource::NoVisibleParents {
        return EditOutcome {
            file_id: opts.file_id.clone(),
            file_name: Some(target.name),
            resolved_folder_id: None,
            result: EditResult::RefusedNoVisibleParents,
        };
    }

    let folder_ancestry::FileTargetDecision {
        decision,
        resolved_folder_id,
        requires_lease,
        ..
    } = evaluated;

    let gated = |result: EditResult| EditOutcome {
        file_id: opts.file_id.clone(),
        file_name: Some(target.name.clone()),
        resolved_folder_id: resolved_folder_id.clone(),
        result,
    };

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

    if opts.dry_run {
        return gated(EditResult::WouldEdit);
    }

    // The lease check (ADR-0080 §9) sits here: after the permission gate
    // and the `--dry-run` branch, before the mutating call. A folder-
    // permission refusal above already made zero Drive API calls with the
    // lease never touched; a `--dry-run` never needs `--lease` at all.
    //
    // No request-building step sits between the `--dry-run` branch and the
    // gate below — `opts.content`/`opts.content_type` are already-validated
    // caller-supplied bytes, passed straight to `edit_content` once the
    // gate succeeds — so the build-before-gate invariant (`gate_leased_write`'s
    // doc comment, `validation.rs`'s identical comment) is satisfied with
    // nothing to build. A future fallible step added here must stay ahead
    // of the gate, the same way (#1688/#1742).
    //
    // `requires_lease` already folds in every legacy multi-parent's own
    // requirement (see `FileTargetDecision::requires_lease`'s doc comment)
    // — it must not be re-derived from `decision.decided_by` alone here,
    // which would only see the one parent whose decision happened to win
    // the verdict. `gate_optional_leased_write` treats `requires_lease:
    // false` as relaxing the *requirement*, not the *meaning* — a `--lease`
    // presented anyway is still validated, consumed and audited (ADR-0080
    // §13).
    //
    // The staleness check below is re-fetched fresh here rather than
    // reusing `target.version` from the very first `get_metadata` call:
    // `resolve_decision_for_file_target` above can issue its own
    // `files.get` calls walking the ancestor chain, so by this point
    // `target.version` may already be stale relative to the live file —
    // exactly the same window ADR-0080 §6 introduces the check to guard
    // against. Re-fetching immediately before the check (and thus
    // immediately before `edit_content`) keeps that window as small as
    // the Sheets/Docs equivalent ("a `files.get` immediately before the
    // `batchUpdate`", ADR-0080 §6) rather than spanning the whole gate
    // evaluation.
    //
    // The ledger lock acquired by `check_and_lock_lease` below is held
    // across the `edit_content` call and released only after
    // `finish_leased_write` — otherwise a second concurrent `drive
    // edit` presenting the same token could load the ledger before this
    // write's `record_write` lands, see the same (still non-stale)
    // recorded version, and pass its own staleness check even though this
    // write is about to invalidate it (a lease-token double-spend).
    let leased = LeasedWrite {
        log_prefix: "drive edit",
        operation: "edit",
        ledger_path: &opts.ledger_path,
        file_id: &opts.file_id,
    };
    let lease_grant = match gate_optional_leased_write(
        leased,
        &files_api,
        requires_lease,
        opts.lease_token.as_deref(),
    )
    .await
    {
        Ok(grant) => grant,
        Err(err) => return gated(err.into_result()),
    };

    let result = match conclude_leased_write(
        leased,
        &lease_grant,
        files_api
            .edit_content(&opts.file_id, &opts.content, &opts.content_type)
            .await,
        |updated| (updated.version.clone(), updated.modified_time.clone()),
        ToString::to_string,
    ) {
        Ok(_updated) => EditResult::Edited,
        Err(err) => EditResult::Failed {
            detail: err.to_string(),
        },
    };
    drop(lease_grant);
    gated(result)
}

/// Builds and writes the [`DriveMutationOutcome`] for one `edit` attempt.
fn record_attempt(outcome: &EditOutcome, duration: Duration) {
    let error = match &outcome.result {
        EditResult::Failed { detail } => Some(detail.clone()),
        _ => None,
    };
    let decided_by = match &outcome.result {
        EditResult::Blocked { decided_by } => decided_by.as_ref(),
        _ => None,
    };
    let decided_by = write_gate::decided_by_log_fields(decided_by);
    request_log::record_drive_mutation(DriveMutationOutcome {
        operation: "edit",
        file_id: outcome.file_id.clone(),
        file_name: outcome.file_name.clone().unwrap_or_default(),
        status: outcome.result.log_status().to_string(),
        added_principals: Vec::new(),
        removed_principals: Vec::new(),
        crosses_drive_boundary: false,
        resolved_folder_id: outcome.resolved_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,
        error,
        duration,
        ..Default::default()
    });
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::drive::auth::{DriveCredentials, DriveGrantedScopes};
    use crate::drive::lease::ledger::LeaseLedger;
    use crate::drive::test_support::seed_lease;
    use crate::drive::types::GOOGLE_FOLDER_MIME_TYPE;
    use crate::drive::write_gate::DriveOperation;
    use crate::test_support::AuditLogGuard;
    use crate::utils::secret::Secret;

    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
    }

    /// `version: "1"` throughout — matches [`seed_lease`]'s default, so any
    /// test that seeds a lease and mounts a file via this helper has a
    /// live, non-stale lease by construction.
    fn mount_file(id: &str, mime_type: &str, parents: &[&str]) -> wiremock::Mock {
        let parents_json: Vec<&str> = parents.to_vec();
        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": mime_type, "parents": parents_json,
                    "version": "1",
                })),
            )
    }

    fn mount_folder(id: &str) -> wiremock::Mock {
        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": GOOGLE_FOLDER_MIME_TYPE,
                })),
            )
    }

    fn opts(dry_run: bool) -> EditOptions {
        opts_for("file-1", dry_run)
    }

    /// No lease token and a ledger path that is never created — every test
    /// using this reaches a refusal (native document, no visible parents,
    /// blocked, a fetch failure) before the lease check would matter. Tests
    /// exercising the success path use [`opts_with_lease`] instead.
    fn opts_for(file_id: &str, dry_run: bool) -> EditOptions {
        EditOptions {
            file_id: file_id.to_string(),
            content: b"new content".to_vec(),
            content_type: "text/plain".to_string(),
            dry_run,
            lease_token: None,
            ledger_path: std::path::PathBuf::from("/nonexistent/lease-ledger.jsonl"),
        }
    }

    /// [`opts_for`] plus a lease already seeded (via [`seed_lease`]) into
    /// `ledger_path` for `file_id` at `version` — for tests exercising the
    /// success path.
    fn opts_with_lease(file_id: &str, ledger_path: &std::path::Path, version: &str) -> EditOptions {
        let token = seed_lease(ledger_path, file_id, version);
        EditOptions {
            lease_token: Some(token),
            ledger_path: ledger_path.to_path_buf(),
            ..opts_for(file_id, false)
        }
    }

    fn allow_rule() -> FolderPermissionRule {
        FolderPermissionRule {
            folder_id: Some("parent-1".to_string()),
            file_id: None,
            recursive: false,
            allow: std::iter::once(DriveOperation::Edit).collect(),
            deny: std::collections::HashSet::default(),
            require_lease: true,
        }
    }

    #[tokio::test]
    async fn allowed_target_succeeds_and_calls_edit_endpoint_once() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        mount_file("file-1", "text/plain", &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("PATCH"))
            .and(wiremock::matchers::path("/upload/drive/v3/files/file-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "file-1", "name": "file-1", "version": "2",
                })),
            )
            .expect(1)
            .mount(&server)
            .await;
        let dir = tempfile::tempdir().unwrap();
        let _audit = crate::test_support::AuditLogGuard::redirect(dir.path());
        let ledger_path = dir.path().join("lease-ledger.jsonl");

        let outcome = edit(
            &client,
            &opts_with_lease("file-1", &ledger_path, "1"),
            &[allow_rule()],
        )
        .await;
        assert!(matches!(outcome.result, EditResult::Edited));

        let reloaded = LeaseLedger::load(&ledger_path).unwrap();
        assert_eq!(
            reloaded.get("test-lease-token").unwrap().version,
            "2",
            "a successful write refreshes the lease's recorded version"
        );
    }

    #[tokio::test]
    async fn staleness_check_uses_a_version_fetched_after_the_ancestor_walk_not_before() {
        // Regression test for the lease staleness-check TOCTOU (issue
        // #1664): the *first* `files.get` (used for the permission-gate's
        // ancestor walk) returns version "0" — stale, as if a foreign edit
        // landed while the gate was still resolving. A *second*,
        // freshly-fetched `files.get` returns "1", matching the lease. If
        // the staleness check reused the first call's snapshot (the bug),
        // this would incorrectly refuse as stale; using the fresh fetch,
        // it must succeed.
        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": ["parent-1"], "version": "0",
                })),
            )
            .up_to_n_times(1)
            .with_priority(1)
            .mount(&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": ["parent-1"], "version": "1",
                })),
            )
            .with_priority(2)
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("PATCH"))
            .and(wiremock::matchers::path("/upload/drive/v3/files/file-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "file-1", "name": "file-1", "version": "2",
                })),
            )
            .expect(1)
            .mount(&server)
            .await;
        let dir = tempfile::tempdir().unwrap();
        let _audit = crate::test_support::AuditLogGuard::redirect(dir.path());
        let ledger_path = dir.path().join("lease-ledger.jsonl");

        let outcome = edit(
            &client,
            &opts_with_lease("file-1", &ledger_path, "1"),
            &[allow_rule()],
        )
        .await;
        assert!(
            matches!(outcome.result, EditResult::Edited),
            "{:?}",
            outcome.result
        );
    }

    #[tokio::test]
    async fn a_failed_pre_lease_refetch_is_reported_as_failed_with_no_edit_call() {
        // The gate's ancestor walk succeeds off the first `files.get`, but
        // the fresh re-fetch feeding the staleness check (ADR-0080 §6)
        // fails — the edit must report `Failed` and never reach the
        // media PATCH.
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        mount_file("file-1", "text/plain", &["parent-1"])
            .up_to_n_times(1)
            .with_priority(1)
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/file-1"))
            .respond_with(wiremock::ResponseTemplate::new(500))
            .with_priority(2)
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("PATCH"))
            .and(wiremock::matchers::path("/upload/drive/v3/files/file-1"))
            .respond_with(wiremock::ResponseTemplate::new(200))
            .expect(0)
            .mount(&server)
            .await;
        let dir = tempfile::tempdir().unwrap();
        let _audit = crate::test_support::AuditLogGuard::redirect(dir.path());
        let ledger_path = dir.path().join("lease-ledger.jsonl");

        let outcome = edit(
            &client,
            &opts_with_lease("file-1", &ledger_path, "1"),
            &[allow_rule()],
        )
        .await;
        assert!(
            matches!(outcome.result, EditResult::Failed { .. }),
            "{:?}",
            outcome.result
        );
        assert_eq!(outcome.file_name.as_deref(), Some("file-1"));
    }

    /// A responder that makes the ledger's directory read-only the instant
    /// the media PATCH lands — i.e. after `check_and_lock_lease` has
    /// already locked and loaded the ledger, but before
    /// `finish_leased_write` tries to save it. `tempfile::NamedTempFile::new_in`
    /// then fails to create its temp file, so `LeaseLedger::save` errors.
    #[cfg(unix)]
    struct MakeDirReadOnlyThenRespond {
        dir: std::path::PathBuf,
    }

    #[cfg(unix)]
    impl wiremock::Respond for MakeDirReadOnlyThenRespond {
        fn respond(&self, _req: &wiremock::Request) -> wiremock::ResponseTemplate {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&self.dir, std::fs::Permissions::from_mode(0o500)).unwrap();
            wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": "file-1", "name": "file-1", "version": "2",
            }))
        }
    }

    /// A failed post-write lease refresh (ADR-0080 §5) must never turn an
    /// already-successful edit into a reported failure — see
    /// `finish_leased_write`'s own doc comment.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_failed_lease_refresh_after_a_successful_write_does_not_fail_the_edit() {
        use std::os::unix::fs::PermissionsExt;

        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        mount_file("file-1", "text/plain", &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        let root = tempfile::tempdir().unwrap();
        let _audit = crate::test_support::AuditLogGuard::redirect(root.path());
        let ledger_dir = root.path().join("ledger");
        std::fs::create_dir(&ledger_dir).unwrap();
        let ledger_path = ledger_dir.join("lease-ledger.jsonl");
        let opts = opts_with_lease("file-1", &ledger_path, "1");
        wiremock::Mock::given(wiremock::matchers::method("PATCH"))
            .and(wiremock::matchers::path("/upload/drive/v3/files/file-1"))
            .respond_with(MakeDirReadOnlyThenRespond {
                dir: ledger_dir.clone(),
            })
            .expect(1)
            .mount(&server)
            .await;

        let outcome = edit(&client, &opts, &[allow_rule()]).await;

        // Restore write permission before the tempdir is dropped, or its
        // own cleanup fails to remove a now-read-only directory.
        std::fs::set_permissions(&ledger_dir, std::fs::Permissions::from_mode(0o700)).unwrap();

        assert!(
            matches!(outcome.result, EditResult::Edited),
            "a refresh failure must not fail the edit itself: {:?}",
            outcome.result
        );
    }

    #[tokio::test]
    async fn denied_target_refuses_with_zero_edit_calls() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        mount_file("file-1", "text/plain", &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        // No PATCH /upload/drive/v3/files/file-1 mock mounted — an
        // accidental edit attempt fails loudly with "no matching mock".

        let outcome = edit(&client, &opts(false), &[]).await;
        assert!(matches!(outcome.result, EditResult::Blocked { .. }));
    }

    #[tokio::test]
    async fn google_native_document_is_refused_before_any_gate_or_network_call() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        mount_file(
            "doc-1",
            "application/vnd.google-apps.document",
            &["parent-1"],
        )
        .mount(&server)
        .await;
        // Deliberately no mock for parent-1 (the gate never runs) and no
        // PATCH mock — proves the refusal happens strictly before the
        // ancestor-chain walk and before any mutating call, even though
        // an allow-everything rule set would otherwise permit it.
        let permissive_rule = FolderPermissionRule {
            folder_id: Some("parent-1".to_string()),
            file_id: None,
            recursive: true,
            allow: std::iter::once(DriveOperation::Edit).collect(),
            deny: std::collections::HashSet::default(),
            require_lease: true,
        };

        let outcome = edit(&client, &opts_for("doc-1", false), &[permissive_rule]).await;
        assert!(matches!(outcome.result, EditResult::RefusedNativeDocument));
    }

    #[tokio::test]
    async fn orphan_file_is_refused_as_having_no_visible_parents() {
        // Before issue #1612 this reported `Blocked { decided_by: None }`,
        // i.e. "no rule matched" — true but unhelpful, since no *folder*
        // rule could ever match a target with no chain. It is now its own
        // outcome, whose message names the `file_id` rule that would work.
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        mount_file("orphan", "text/plain", &[]).mount(&server).await;

        let outcome = edit(&client, &opts_for("orphan", false), &[]).await;
        assert!(matches!(
            outcome.result,
            EditResult::RefusedNoVisibleParents
        ));
        assert_eq!(outcome.resolved_folder_id, None);
    }

    #[tokio::test]
    async fn edit_denies_when_any_current_parent_denies_even_if_another_allows() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        mount_file("file-1", "text/plain", &["allow-parent", "deny-parent"])
            .mount(&server)
            .await;
        mount_folder("allow-parent").mount(&server).await;
        mount_folder("deny-parent").mount(&server).await;
        let rules = [allow_rule()]; // only "parent-1" is allowed; neither
                                    // allow-parent nor deny-parent match it,
                                    // so both fall to the default deny —
                                    // this asserts deny-wins-across-parents
                                    // even when BOTH parents individually
                                    // resolve to the same (deny) verdict,
                                    // and the multi-parent path is exercised.

        let outcome = edit(&client, &opts(false), &rules).await;
        assert!(matches!(outcome.result, EditResult::Blocked { .. }));
        assert_eq!(
            outcome.resolved_folder_id, None,
            "multi-parent targets report no single resolved folder id"
        );
    }

    #[tokio::test]
    async fn ancestor_chain_fetch_failure_produces_failed_not_allow() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        mount_file("file-1", "text/plain", &["parent-1"])
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/parent-1"))
            .respond_with(wiremock::ResponseTemplate::new(500).set_body_string("server error"))
            .mount(&server)
            .await;

        let outcome = edit(&client, &opts(false), &[allow_rule()]).await;
        assert!(
            matches!(outcome.result, EditResult::Failed { .. }),
            "a fetch failure must never silently fall through to Edited/WouldEdit"
        );
    }

    #[tokio::test]
    async fn insufficient_scope_403_surfaces_both_write_flags() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        mount_file("file-1", "text/plain", &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("PATCH"))
            .and(wiremock::matchers::path("/upload/drive/v3/files/file-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(403).set_body_json(serde_json::json!({
                    "error": {
                        "message": "Insufficient Permission",
                        "errors": [{"reason": "insufficientPermissions"}],
                    }
                })),
            )
            .mount(&server)
            .await;
        let dir = tempfile::tempdir().unwrap();
        let _audit = crate::test_support::AuditLogGuard::redirect(dir.path());
        let ledger_path = dir.path().join("lease-ledger.jsonl");

        let outcome = edit(
            &client,
            &opts_with_lease("file-1", &ledger_path, "1"),
            &[allow_rule()],
        )
        .await;
        let EditResult::Failed { detail } = outcome.result else {
            panic!("expected Failed, got {:?}", outcome.result);
        };
        assert!(detail.contains("--write-file"), "{detail}");
        assert!(detail.contains("--write-full"), "{detail}");
    }

    #[tokio::test]
    async fn dry_run_never_calls_edit_endpoint() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        mount_file("file-1", "text/plain", &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;

        let outcome = edit(&client, &opts(true), &[allow_rule()]).await;
        assert!(matches!(outcome.result, EditResult::WouldEdit));
    }

    #[tokio::test]
    async fn dry_run_surfaces_the_same_blocked_reasoning_as_a_real_denied_run() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        mount_file("file-1", "text/plain", &["parent-1"])
            .expect(2)
            .mount(&server)
            .await;
        mount_folder("parent-1").expect(2).mount(&server).await;

        let dry_run_outcome = edit(&client, &opts(true), &[]).await;
        let real_outcome = edit(&client, &opts(false), &[]).await;
        assert!(matches!(dry_run_outcome.result, EditResult::Blocked { .. }));
        assert!(matches!(real_outcome.result, EditResult::Blocked { .. }));
    }

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

    #[tokio::test]
    async fn a_file_rule_grants_a_target_with_no_visible_parents() {
        // The `drive edit` half of the shared-file gap: a binary file
        // shared by link arrives with no parents, so no folder rule could
        // ever apply to it.
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        mount_file("file-1", "text/plain", &[]).mount(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("PATCH"))
            .and(wiremock::matchers::path("/upload/drive/v3/files/file-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"id": "file-1", "name": "file-1"})),
            )
            .expect(1)
            .mount(&server)
            .await;
        let dir = tempfile::tempdir().unwrap();
        let _audit = crate::test_support::AuditLogGuard::redirect(dir.path());
        let ledger_path = dir.path().join("lease-ledger.jsonl");

        let outcome = edit(
            &client,
            &opts_with_lease("file-1", &ledger_path, "1"),
            &[FolderPermissionRule::file("file-1").allowing([DriveOperation::Edit])],
        )
        .await;

        assert!(
            matches!(outcome.result, EditResult::Edited),
            "{:?}",
            outcome.result
        );
    }

    #[tokio::test]
    async fn a_parentless_target_is_now_refused_distinctly_not_generically_blocked() {
        // Before #1612 this reported `Blocked { decided_by: None }`, which
        // reads as "fix your rules" when no folder rule would have helped.
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        mount_file("file-1", "text/plain", &[]).mount(&server).await;

        let outcome = edit(&client, &opts(false), &[]).await;

        assert!(matches!(
            outcome.result,
            EditResult::RefusedNoVisibleParents
        ));
        assert_eq!(outcome.result.log_status(), "refused-no-visible-parents");
    }

    #[tokio::test]
    async fn a_file_deny_beats_an_allowing_parent_folder() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        mount_file("file-1", "text/plain", &["parent-1"])
            .mount(&server)
            .await;
        // No parent-1 mock and no PATCH mock: the file rule must decide
        // before either is reached.

        let outcome = edit(
            &client,
            &opts(false),
            &[
                allow_rule(),
                FolderPermissionRule::file("file-1").denying([DriveOperation::Edit]),
            ],
        )
        .await;

        match &outcome.result {
            EditResult::Blocked { decided_by } => {
                let rule = decided_by.as_ref().expect("a file rule decided this");
                assert_eq!(rule.kind_label(), "file");
                assert_eq!(rule.id(), "file-1");
            }
            other => panic!("expected Blocked, got {other:?}"),
        }
    }

    // ── the Drive write lease (ADR-0080 §9) ────────────────────────────

    #[tokio::test]
    async fn refuses_without_a_lease_when_the_rule_requires_one() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        mount_file("file-1", "text/plain", &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        // No PATCH mock mounted — a refusal must make zero mutating calls.
        let dir = tempfile::tempdir().unwrap();
        let _audit = AuditLogGuard::redirect(dir.path());

        let outcome = edit(&client, &opts(false), &[allow_rule()]).await;
        assert!(matches!(outcome.result, EditResult::RefusedNoLease));
        assert_eq!(outcome.result.log_status(), "refused-no-lease");
    }

    #[tokio::test]
    async fn refuses_an_unknown_lease_token() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        mount_file("file-1", "text/plain", &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        let dir = tempfile::tempdir().unwrap();
        let _audit = crate::test_support::AuditLogGuard::redirect(dir.path());
        let ledger_path = dir.path().join("lease-ledger.jsonl");
        // Never seeded — the ledger exists nowhere near this token.

        let opts = EditOptions {
            lease_token: Some("bogus-token".to_string()),
            ledger_path,
            ..opts_for("file-1", false)
        };
        let outcome = edit(&client, &opts, &[allow_rule()]).await;
        assert!(matches!(outcome.result, EditResult::RefusedLeaseExpired));
    }

    #[tokio::test]
    async fn refuses_a_lease_when_the_ledger_is_unreadable() {
        // A directory in place of the ledger file makes `LeaseLedger::load`
        // fail with something other than a missing-file error — refused as
        // expired rather than trusting an unreadable ledger (fail-closed,
        // see `check_and_lock_lease`'s doc comment).
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        mount_file("file-1", "text/plain", &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        let dir = tempfile::tempdir().unwrap();
        let _audit = crate::test_support::AuditLogGuard::redirect(dir.path());
        let ledger_path = dir.path().join("lease-ledger.jsonl");
        std::fs::create_dir(&ledger_path).unwrap();

        let opts = EditOptions {
            lease_token: Some("any-token".to_string()),
            ledger_path,
            ..opts_for("file-1", false)
        };
        let outcome = edit(&client, &opts, &[allow_rule()]).await;
        assert!(matches!(outcome.result, EditResult::RefusedLeaseExpired));
    }

    #[tokio::test]
    async fn refuses_an_expired_lease() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        mount_file("file-1", "text/plain", &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        let dir = tempfile::tempdir().unwrap();
        let _audit = crate::test_support::AuditLogGuard::redirect(dir.path());
        let ledger_path = dir.path().join("lease-ledger.jsonl");
        let token = "expired-token".to_string();
        let mut ledger = LeaseLedger::default();
        ledger.insert(crate::drive::lease::ledger::LeaseRecord {
            token: token.clone(),
            file_id: "file-1".to_string(),
            version: "1".to_string(),
            modified_time: None,
            backup: crate::drive::lease::ledger::LeaseBackup::Bytes {
                path: std::path::PathBuf::from("/tmp/test-backup"),
                sha256: "deadbeef".to_string(),
                size: 0,
            },
            acquired_at: chrono::Utc::now() - chrono::Duration::hours(2),
            expires_at: chrono::Utc::now() - chrono::Duration::hours(1),
            released_at: None,
            superseded_by: None,
            restored_at: None,
            restored_sheet_id: None,
        });
        ledger.save(&ledger_path).unwrap();

        let opts = EditOptions {
            lease_token: Some(token),
            ledger_path,
            ..opts_for("file-1", false)
        };
        let outcome = edit(&client, &opts, &[allow_rule()]).await;
        assert!(matches!(outcome.result, EditResult::RefusedLeaseExpired));
    }

    #[tokio::test]
    async fn refuses_a_lease_bound_to_a_different_file() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        mount_file("file-1", "text/plain", &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        let dir = tempfile::tempdir().unwrap();
        let _audit = crate::test_support::AuditLogGuard::redirect(dir.path());
        let ledger_path = dir.path().join("lease-ledger.jsonl");
        // Seeded for a *different* file id.
        let token = seed_lease(&ledger_path, "some-other-file", "1");

        let opts = EditOptions {
            lease_token: Some(token),
            ledger_path,
            ..opts_for("file-1", false)
        };
        let outcome = edit(&client, &opts, &[allow_rule()]).await;
        assert!(matches!(outcome.result, EditResult::RefusedLeaseWrongFile));
    }

    #[tokio::test]
    async fn refuses_a_stale_lease_when_the_file_has_moved() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        // mount_file always returns version "1"; the lease below was
        // acquired against version "0" — a foreign edit landed since.
        mount_file("file-1", "text/plain", &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        let dir = tempfile::tempdir().unwrap();
        let _audit = crate::test_support::AuditLogGuard::redirect(dir.path());
        let ledger_path = dir.path().join("lease-ledger.jsonl");
        let token = seed_lease(&ledger_path, "file-1", "0");

        let opts = EditOptions {
            lease_token: Some(token),
            ledger_path,
            ..opts_for("file-1", false)
        };
        let outcome = edit(&client, &opts, &[allow_rule()]).await;
        assert!(matches!(outcome.result, EditResult::RefusedLeaseStale));
    }

    #[tokio::test]
    async fn edit_requires_a_lease_when_any_legacy_parent_requires_one_even_if_the_deciding_parent_opted_out(
    ) {
        // Regression test for the multi-parent lease-bypass (issue #1664):
        // `combine_across_parents` keeps only the *last* Allow decision's
        // `decided_by` — here that's `lenient-parent`, whose rule opts out
        // of the lease. `strict-parent`'s own requirement must still
        // apply, or a lease could be silently skipped just by attaching an
        // opted-out legacy parent to a file.
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        mount_file("file-1", "text/plain", &["strict-parent", "lenient-parent"])
            .mount(&server)
            .await;
        mount_folder("strict-parent").mount(&server).await;
        mount_folder("lenient-parent").mount(&server).await;
        // No PATCH mock mounted — a refusal must make zero mutating calls.
        let dir = tempfile::tempdir().unwrap();
        let _audit = AuditLogGuard::redirect(dir.path());
        let rules = [
            FolderPermissionRule::folder("strict-parent").allowing([DriveOperation::Edit]),
            FolderPermissionRule::folder("lenient-parent")
                .allowing([DriveOperation::Edit])
                .requiring_lease(false),
        ];

        let outcome = edit(&client, &opts(false), &rules).await;
        assert!(
            matches!(outcome.result, EditResult::RefusedNoLease),
            "{:?}",
            outcome.result
        );
    }

    #[tokio::test]
    async fn a_held_ledger_lock_fails_the_edit_rather_than_risking_a_lease_double_spend() {
        // Regression test for the lease-check/refresh TOCTOU (issue
        // #1664): simulates a concurrent `drive lease`/`drive edit`
        // operation already holding the ledger lock. The edit must fail
        // outright rather than silently reading the ledger unlocked.
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        mount_file("file-1", "text/plain", &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        let dir = tempfile::tempdir().unwrap();
        let _audit = crate::test_support::AuditLogGuard::redirect(dir.path());
        let ledger_path = dir.path().join("lease-ledger.jsonl");
        let token = seed_lease(&ledger_path, "file-1", "1");
        // Under flock (issue #1687), a busy lock now waits rather than
        // hard-failing (`check_and_lock_lease` -> `acquire_waiting`), so a
        // held `LedgerLock` no longer reproduces an immediate failure here.
        // A directory at the lock path does: opening it for write fails
        // outright with an I/O error, which is never retried.
        let mut lock_path = ledger_path.clone().into_os_string();
        lock_path.push(".lock");
        std::fs::create_dir(std::path::PathBuf::from(lock_path)).unwrap();
        wiremock::Mock::given(wiremock::matchers::method("PATCH"))
            .and(wiremock::matchers::path("/upload/drive/v3/files/file-1"))
            .respond_with(wiremock::ResponseTemplate::new(200))
            .expect(0)
            .mount(&server)
            .await;

        let opts = EditOptions {
            lease_token: Some(token),
            ledger_path,
            ..opts_for("file-1", false)
        };
        let outcome = edit(&client, &opts, &[allow_rule()]).await;
        assert!(
            matches!(outcome.result, EditResult::Failed { .. }),
            "{:?}",
            outcome.result
        );
    }

    #[tokio::test]
    async fn require_lease_false_writes_without_a_lease() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        mount_file("file-1", "text/plain", &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("PATCH"))
            .and(wiremock::matchers::path("/upload/drive/v3/files/file-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"id": "file-1", "name": "file-1"})),
            )
            .expect(1)
            .mount(&server)
            .await;
        let rule = FolderPermissionRule::folder("parent-1")
            .allowing([DriveOperation::Edit])
            .requiring_lease(false);

        // No lease token presented at all, and no ledger exists.
        let outcome = edit(&client, &opts(false), &[rule]).await;
        assert!(matches!(outcome.result, EditResult::Edited));
    }

    #[tokio::test]
    async fn require_lease_false_still_refuses_a_stale_lease_if_one_is_presented() {
        // ADR-0080 §13: `require_lease: false` relaxes the *requirement*,
        // not the *meaning* — a token volunteered anyway is checked exactly
        // like a required one, including staleness.
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        // mount_file always returns version "1"; the lease below was
        // acquired against version "0" — a foreign edit landed since.
        mount_file("file-1", "text/plain", &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        // No PATCH mock mounted — a refusal must make zero mutating calls.
        let dir = tempfile::tempdir().unwrap();
        let _audit = AuditLogGuard::redirect(dir.path());
        let ledger_path = dir.path().join("lease-ledger.jsonl");
        let token = seed_lease(&ledger_path, "file-1", "0");
        let rule = FolderPermissionRule::folder("parent-1")
            .allowing([DriveOperation::Edit])
            .requiring_lease(false);

        let opts = EditOptions {
            lease_token: Some(token),
            ledger_path,
            ..opts_for("file-1", false)
        };
        let outcome = edit(&client, &opts, &[rule]).await;
        assert!(
            matches!(outcome.result, EditResult::RefusedLeaseStale),
            "{:?}",
            outcome.result
        );
    }

    #[tokio::test]
    async fn require_lease_false_still_refreshes_the_ledger_for_a_presented_lease() {
        // The issue's own named consequence: a volunteered lease that goes
        // unvalidated still moves Drive's `version`, leaving its ledger row
        // stale so a *later* required-lease write on the same file refuses
        // `RefusedLeaseStale` because of this write. Enforcing the lease
        // (ADR-0080 §13) closes that by refreshing the row like any other
        // successful leased write.
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        mount_file("file-1", "text/plain", &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("PATCH"))
            .and(wiremock::matchers::path("/upload/drive/v3/files/file-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "file-1", "name": "file-1", "version": "2",
                })),
            )
            .mount(&server)
            .await;
        let dir = tempfile::tempdir().unwrap();
        let _audit = AuditLogGuard::redirect(dir.path());
        let ledger_path = dir.path().join("lease-ledger.jsonl");
        let token = seed_lease(&ledger_path, "file-1", "1");
        let rule = FolderPermissionRule::folder("parent-1")
            .allowing([DriveOperation::Edit])
            .requiring_lease(false);

        let opts = EditOptions {
            lease_token: Some(token.clone()),
            ledger_path: ledger_path.clone(),
            ..opts_for("file-1", false)
        };
        let outcome = edit(&client, &opts, &[rule]).await;
        assert!(
            matches!(outcome.result, EditResult::Edited),
            "{:?}",
            outcome.result
        );

        let ledger = LeaseLedger::load(&ledger_path).unwrap();
        let record = ledger
            .get(&token)
            .expect("the lease is still in the ledger");
        assert_eq!(record.version, "2");
    }

    #[tokio::test]
    async fn a_dry_run_never_needs_a_lease() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        mount_file("file-1", "text/plain", &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        // No PATCH mock, no lease token, no ledger — a dry run must not
        // need any of them.

        let outcome = edit(&client, &opts(true), &[allow_rule()]).await;
        assert!(matches!(outcome.result, EditResult::WouldEdit));
    }

    // ── the write's own audit trail (ADR-0080 §11) ─────────────────────

    #[tokio::test]
    async fn a_successful_edit_writes_a_pending_intent_and_an_allowed_outcome() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        mount_file("file-1", "text/plain", &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("PATCH"))
            .and(wiremock::matchers::path("/upload/drive/v3/files/file-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "file-1", "name": "file-1", "version": "2",
                })),
            )
            .mount(&server)
            .await;
        let dir = tempfile::tempdir().unwrap();
        let audit = AuditLogGuard::redirect(dir.path());
        let ledger_path = dir.path().join("lease-ledger.jsonl");

        let outcome = edit(
            &client,
            &opts_with_lease("file-1", &ledger_path, "1"),
            &[allow_rule()],
        )
        .await;
        assert!(matches!(outcome.result, EditResult::Edited));

        let records = audit.records();
        assert_eq!(audit.verdicts(), ["pending", "allowed"], "{records:?}");
        // Both halves share the lease id, and `command` has the same
        // segmented shape every other record kind uses.
        for record in &records {
            assert_eq!(record.command, ["drive", "edit"]);
            assert_eq!(
                record.context.get("lease_id").map(String::as_str),
                Some("test-lease-token")
            );
        }
        assert_eq!(
            records[0].context.get("version_before").map(String::as_str),
            Some("1")
        );
        assert_eq!(
            records[1].context.get("version_after").map(String::as_str),
            Some("2")
        );
        assert_eq!(records[1].error, None);
    }

    #[tokio::test]
    async fn a_failed_edit_after_a_valid_lease_writes_a_failed_outcome() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        mount_file("file-1", "text/plain", &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("PATCH"))
            .and(wiremock::matchers::path("/upload/drive/v3/files/file-1"))
            .respond_with(wiremock::ResponseTemplate::new(500))
            .mount(&server)
            .await;
        let dir = tempfile::tempdir().unwrap();
        let audit = AuditLogGuard::redirect(dir.path());
        let ledger_path = dir.path().join("lease-ledger.jsonl");

        let outcome = edit(
            &client,
            &opts_with_lease("file-1", &ledger_path, "1"),
            &[allow_rule()],
        )
        .await;
        let EditResult::Failed { detail } = &outcome.result else {
            panic!("expected Failed, got {:?}", outcome.result);
        };

        let records = audit.records();
        assert_eq!(audit.verdicts(), ["pending", "failed"], "{records:?}");
        // The outcome carries the same error the CLI reports.
        assert_eq!(records[1].error.as_deref(), Some(detail.as_str()));
    }
}