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
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
//! `trim-whitespace` — trim whitespace in every cell of a range (issue
//! #1844).
//!
//! [ADR-0083](../../../docs/adrs/adr-0083.md) §1 places this under
//! `DriveOperation::SheetsWrite`: it rewrites ordinary cell content in
//! place, which a `sheets clear` followed by a `sheets write` of the same
//! range could already do under that grant.
//!
//! That placement is measured, not provisional: issue #1877 ran §5's live
//! formatting check and nothing moved. Backgrounds, text and number
//! formats, borders, notes and validation rules all survive a trim, and
//! cells the trim skips are left untouched. Rich-text runs are rebased by
//! the API so every character that remains keeps its own formatting;
//! formatting on removed whitespace goes with it. That is gentler than a
//! plain `sheets write`, which drops those runs outright (§5's #1877
//! addendum).
//!
//! The trim rule, measured live against the API (issue #1844): leading
//! and trailing whitespace is stripped **and each internal run collapses
//! to a single space** (`a   b` becomes `a b`), a cell of nothing but
//! whitespace becomes blank, a formula's text is untouched, and text that
//! trims to something starting `=` or `+` stays a string rather than
//! becoming a formula.
//!
//! **The preview never predicts which cells change.** §6 puts this verb in
//! the first `--dry-run` tier — one bounded read, reporting the *count and
//! A1 locations* of the range's non-blank cells and never their values —
//! but stops short of naming the cells that *would* change, because
//! deciding that means reproducing the server's trim rule locally, the
//! same "preview that lies" risk §6 declined for `findReplace`. So every
//! non-blank cell is a candidate and the wording is always "may be
//! trimmed". The gap is real, not theoretical: a live run over a 13-cell
//! range previewed all 13 as candidates and the server changed 5.
//!
//! **The read happens on `--dry-run` only**, unlike `auto_fill.rs` and
//! `paste.rs`, which read on both paths so their real runs can report the
//! same cells. This verb's real run has something strictly better: the
//! server's own `cellsChangedCount`, an exact count of what it actually
//! changed. Reading the range again would spend a call to print a worse
//! number beside the good one.

#![allow(missing_docs)] // The CLI-facing outcome models are self-describing in JSON.

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::lease::check::{
    conclude_native_leased_write, gate_optional_leased_write, FromLeaseRefusal, LeaseGateRefusal,
    LeasedWrite,
};
use crate::drive::sheets::api::{
    applied_reply_unreadable_line, BatchUpdateOutcome, RetryHint, SheetsApi, ValueRenderOption,
};
use crate::drive::sheets::client::SheetsClient;
use crate::drive::sheets::types::{
    BatchUpdateRequestItem, GridRange, Sheet, Spreadsheet, TrimWhitespaceRequest,
};
use crate::drive::sheets::{a1, grid_range, target_gate};
use crate::drive::types::SheetTargetRefusal;
use crate::drive::write_gate::{self, DecidingRule, DriveOperation, FolderPermissionRule};
use crate::request_log::{self, DriveMutationOutcome};

const LOG_OPERATION: &str = "sheets-trim-whitespace";

/// Which cells the caller named.
///
/// `--whole-sheet` is offered here but deliberately *not* on
/// `delete-duplicates` — see that module's docs for why a whole-sheet
/// dedupe is a different proposition from a whole-sheet trim.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TrimScope {
    /// A `--range`, already carrying its own `Sheet!` prefix or supplied
    /// one from `--sheet`. May be open-ended (`A:A`); open bounds are
    /// materialised from the sheet's grid extent.
    Range,
    /// `--whole-sheet`: every cell of the sheet named by `--sheet`.
    WholeSheet,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TrimWhitespaceOptions {
    pub spreadsheet_id: String,
    pub sheet: Option<String>,
    pub range: Option<String>,
    pub scope: TrimScope,
    pub dry_run: bool,
    pub lease_token: Option<String>,
    pub ledger_path: PathBuf,
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
#[serde(tag = "status", rename_all = "kebab-case")]
pub enum TrimWhitespaceResult {
    WouldChange {
        /// The range as sent, with any open bound materialised.
        range: String,
        /// Every non-blank cell in the range, as bare A1 addresses —
        /// **never their values**. An upper bound on what the server will
        /// actually trim, never a prediction: see the module docs.
        candidate_cells: Vec<String>,
        /// The candidate list is always an upper bound, including when it
        /// is empty. The server alone decides which cells actually change.
        candidate_cells_upper_bound: bool,
        /// The values read covered only the part of the requested range
        /// inside the sheet's currently allocated grid.
        read_clamped_to_sheet: bool,
    },
    Changed {
        range: String,
        /// The server's own count. `None` when the reply carried no
        /// `trimWhitespace` object — `find-replace`'s precedent for a
        /// response that succeeded but reported nothing.
        cells_changed_count: Option<i64>,
    },
    RefusedInvalidRequest {
        detail: String,
    },
    RefusedNotASpreadsheet {
        mime_type: String,
    },
    RefusedShortcut,
    RefusedNoVisibleParents,
    RefusedSheetNotFound {
        title: String,
        available: Vec<String>,
    },
    Blocked {
        decided_by: Option<DecidingRule>,
    },
    RefusedNoLease,
    RefusedLeaseExpired,
    RefusedLeaseWrongFile,
    RefusedLeaseStale,
    /// The API answered 2xx — the trim **was applied** — but its reply could
    /// not be read (issue #2021). Distinct from [`Self::Failed`]. The server's
    /// `cellsChangedCount` was in that reply, so it is unknown.
    AppliedReplyUnreadable {
        range: String,
        /// What was applied, in the same terms as a `Changed` line.
        summary: String,
        /// Why the reply could not be read.
        detail: String,
    },
    Failed {
        detail: String,
    },
}

impl FromLeaseRefusal for TrimWhitespaceResult {
    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 TrimWhitespaceResult {
    fn log_status(&self) -> &'static str {
        match self {
            Self::WouldChange { .. } => "would-change",
            Self::Changed { .. } => "changed",
            Self::RefusedInvalidRequest { .. } => "refused-invalid-request",
            Self::RefusedNotASpreadsheet { .. } => "refused-not-a-spreadsheet",
            Self::RefusedShortcut => "refused-shortcut",
            Self::RefusedNoVisibleParents => "refused-no-visible-parents",
            Self::RefusedSheetNotFound { .. } => "refused-sheet-not-found",
            Self::Blocked { .. } => "blocked",
            Self::RefusedNoLease => "refused-no-lease",
            Self::RefusedLeaseExpired => "refused-lease-expired",
            Self::RefusedLeaseWrongFile => "refused-lease-wrong-file",
            Self::RefusedLeaseStale => "refused-lease-stale",
            Self::AppliedReplyUnreadable { .. } => "applied-reply-unreadable",
            Self::Failed { .. } => "failed",
        }
    }
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct TrimWhitespaceOutcome {
    pub spreadsheet_id: String,
    pub file_name: Option<String>,
    pub resolved_folder_id: Option<String>,
    pub result: TrimWhitespaceResult,
}

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

pub async fn trim_whitespace(
    drive: &DriveClient,
    sheets: &SheetsClient,
    opts: &TrimWhitespaceOptions,
    rules: &[FolderPermissionRule],
) -> TrimWhitespaceOutcome {
    let started = Instant::now();
    let outcome = trim_whitespace_inner(drive, sheets, opts, rules).await;
    if !opts.dry_run {
        record_attempt(&outcome, started.elapsed());
    }
    outcome
}

async fn trim_whitespace_inner(
    drive: &DriveClient,
    sheets: &SheetsClient,
    opts: &TrimWhitespaceOptions,
    rules: &[FolderPermissionRule],
) -> TrimWhitespaceOutcome {
    let bare = |result| TrimWhitespaceOutcome {
        spreadsheet_id: opts.spreadsheet_id.clone(),
        file_name: None,
        resolved_folder_id: None,
        result,
    };
    if let Err(detail) = validate_scope_syntax(opts) {
        return bare(TrimWhitespaceResult::RefusedInvalidRequest { detail });
    }
    // Composed only for the `Range` scope: `--whole-sheet` resolves its
    // sheet id by title instead, so there is no range string to compose.
    let composed = match opts.scope {
        TrimScope::WholeSheet => None,
        TrimScope::Range => match a1::compose(opts.sheet.as_deref(), opts.range.as_deref()) {
            Ok(range) => Some(range),
            Err(err) => {
                return bare(TrimWhitespaceResult::RefusedInvalidRequest {
                    detail: err.to_string(),
                })
            }
        },
    };
    let (target, decision, resolved_folder_id, requires_lease) = match target_gate::resolve(
        drive,
        &opts.spreadsheet_id,
        DriveOperation::SheetsWrite,
        rules,
    )
    .await
    {
        target_gate::TargetGateOutcome::MetadataFetchFailed { detail } => {
            return bare(TrimWhitespaceResult::Failed { detail })
        }
        target_gate::TargetGateOutcome::Refused { target, refusal } => {
            let result = match refusal {
                SheetTargetRefusal::Shortcut => TrimWhitespaceResult::RefusedShortcut,
                SheetTargetRefusal::NotASpreadsheet { mime_type } => {
                    TrimWhitespaceResult::RefusedNotASpreadsheet { mime_type }
                }
                SheetTargetRefusal::NoVisibleParents => {
                    TrimWhitespaceResult::RefusedNoVisibleParents
                }
            };
            return TrimWhitespaceOutcome {
                spreadsheet_id: opts.spreadsheet_id.clone(),
                file_name: Some(target.name),
                resolved_folder_id: None,
                result,
            };
        }
        target_gate::TargetGateOutcome::GateFetchFailed { target, detail } => {
            return TrimWhitespaceOutcome {
                spreadsheet_id: opts.spreadsheet_id.clone(),
                file_name: Some(target.name),
                resolved_folder_id: None,
                result: TrimWhitespaceResult::Failed { detail },
            }
        }
        target_gate::TargetGateOutcome::Gated {
            target,
            decision,
            resolved_folder_id,
            requires_lease,
        } => (target, decision, resolved_folder_id, requires_lease),
    };
    let gated = |result| TrimWhitespaceOutcome {
        spreadsheet_id: opts.spreadsheet_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(TrimWhitespaceResult::Blocked {
            decided_by: decision.decided_by,
        });
    }
    let api = SheetsApi::new(sheets);
    let workbook = match api.get_spreadsheet(&opts.spreadsheet_id).await {
        Ok(book) => book,
        Err(err) => {
            return gated(TrimWhitespaceResult::Failed {
                detail: format!("{err:#}"),
            })
        }
    };
    let (sheet_title, grid) = match resolve_scope(opts, composed.as_deref(), &workbook) {
        Ok(value) => value,
        Err(result) => return gated(result),
    };
    // Open bounds are materialised from the sheet's own extent so the
    // request, the reported range and the preview read all describe the
    // same rectangle. A `--whole-sheet` request could equally be sent with
    // every bound absent, but then the outcome could not name what it
    // acted on.
    let grid = materialise_bounds(
        &grid,
        grid_range::find_sheet_by_id(&workbook, grid.sheet_id),
    );
    let Some(range_a1) = grid_range::bounded_range_to_a1(&sheet_title, &grid) else {
        return gated(TrimWhitespaceResult::RefusedInvalidRequest {
            detail: format!(
                "'{}' resolves to no cells in the sheet's current grid",
                composed.as_deref().unwrap_or(&sheet_title)
            ),
        });
    };

    // Built before the gate, not after — #1688/#1742's ordering invariant,
    // shared verbatim by every leased engine.
    let request = BatchUpdateRequestItem::TrimWhitespace(TrimWhitespaceRequest { range: grid });

    if opts.dry_run {
        // A bounded request can still extend past the allocated grid. The
        // mutation keeps the caller's range, but values.get must read only
        // its intersection with the sheet's current cells.
        let Some(read_grid) = grid_range::clamp_to_sheet(&workbook, &grid) else {
            return gated(TrimWhitespaceResult::RefusedInvalidRequest {
                detail: format!("{range_a1} has no cells inside the sheet's current grid"),
            });
        };
        let Some(read_a1) = grid_range::bounded_range_to_a1(&sheet_title, &read_grid) else {
            return gated(TrimWhitespaceResult::RefusedInvalidRequest {
                detail: format!("{range_a1} has no cells inside the sheet's current grid"),
            });
        };
        let candidate_cells =
            match read_non_blank(&api, &opts.spreadsheet_id, &read_a1, &read_grid).await {
                Ok(cells) => cells,
                Err(detail) => return gated(TrimWhitespaceResult::Failed { detail }),
            };
        return gated(TrimWhitespaceResult::WouldChange {
            range: range_a1,
            candidate_cells,
            candidate_cells_upper_bound: true,
            read_clamped_to_sheet: read_grid != grid,
        });
    }

    let leased = LeasedWrite {
        log_prefix: "drive sheets trim-whitespace",
        operation: LOG_OPERATION,
        ledger_path: &opts.ledger_path,
        file_id: &opts.spreadsheet_id,
    };
    let files_api = FilesApi::new(drive);
    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_native_leased_write(
        leased,
        &lease_grant,
        &files_api,
        api.batch_update(&opts.spreadsheet_id, vec![request]).await,
        |err| format!("{err:#}"),
    )
    .await
    {
        Ok(BatchUpdateOutcome::Applied(response)) => TrimWhitespaceResult::Changed {
            range: range_a1,
            cells_changed_count: response
                .replies
                .into_iter()
                .next()
                .and_then(|reply| reply.trim_whitespace)
                .map(|trim| trim.cells_changed_count),
        },
        // Idempotent (`RetryHint::Idempotent`): trimming an already-trimmed
        // range changes nothing, so a re-run is safe.
        Ok(BatchUpdateOutcome::AppliedReplyUnreadable { detail }) => {
            TrimWhitespaceResult::AppliedReplyUnreadable {
                summary: format!("trim whitespace in {range_a1}"),
                range: range_a1,
                detail,
            }
        }
        Err(err) => TrimWhitespaceResult::Failed {
            detail: format!("{err:#}"),
        },
    };
    drop(lease_grant);
    gated(result)
}

/// Refuses the scope combinations clap cannot express on its own, so the
/// engine is safe for a non-clap caller too — `find_replace.rs`'s pattern.
fn validate_scope_syntax(opts: &TrimWhitespaceOptions) -> Result<(), String> {
    match opts.scope {
        TrimScope::WholeSheet => {
            if opts.range.is_some() {
                return Err("--whole-sheet cannot be combined with --range".to_string());
            }
            if opts.sheet.as_ref().is_none_or(|s| s.trim().is_empty()) {
                return Err("--whole-sheet needs --sheet to name the sheet to trim".to_string());
            }
        }
        TrimScope::Range => {
            if opts.range.as_ref().is_none_or(|r| r.trim().is_empty()) {
                return Err("pass --range, or --whole-sheet to trim an entire sheet".to_string());
            }
        }
    }
    Ok(())
}

/// The sheet title and grid range the caller's scope names.
fn resolve_scope(
    opts: &TrimWhitespaceOptions,
    composed: Option<&str>,
    workbook: &Spreadsheet,
) -> Result<(String, GridRange), TrimWhitespaceResult> {
    match opts.scope {
        TrimScope::WholeSheet => {
            let title = opts.sheet.clone().unwrap_or_default();
            let sheet_id = grid_range::find_sheet_id(workbook, &title, |title, available| {
                TrimWhitespaceResult::RefusedSheetNotFound { title, available }
            })?;
            Ok((
                title,
                GridRange {
                    sheet_id,
                    start_row_index: None,
                    end_row_index: None,
                    start_column_index: None,
                    end_column_index: None,
                },
            ))
        }
        TrimScope::Range => {
            let composed = composed.unwrap_or_default();
            grid_range::resolve_grid_range(
                workbook,
                composed,
                |detail| TrimWhitespaceResult::RefusedInvalidRequest { detail },
                |title, available| TrimWhitespaceResult::RefusedSheetNotFound { title, available },
            )
        }
    }
}

/// Fills any absent bound of `grid` from `sheet`'s current grid extent.
///
/// A bound the sheet reports no count for is left absent, as is every
/// bound when `sheet` is `None`. Either way the caller treats a range that
/// still isn't fully bounded as naming no cells, since it cannot be read
/// or rendered — which is also why a missing sheet needs no branch of its
/// own here: it cannot happen (the id came from this same workbook a
/// moment earlier) and would refuse correctly if it did.
fn materialise_bounds(grid: &GridRange, sheet: Option<&Sheet>) -> GridRange {
    let props = sheet
        .and_then(|sheet| sheet.properties.as_ref())
        .and_then(|p| p.grid_properties.as_ref());
    GridRange {
        sheet_id: grid.sheet_id,
        start_row_index: grid.start_row_index.or(Some(0)),
        end_row_index: grid
            .end_row_index
            .or_else(|| props.and_then(|g| g.row_count)),
        start_column_index: grid.start_column_index.or(Some(0)),
        end_column_index: grid
            .end_column_index
            .or_else(|| props.and_then(|g| g.column_count)),
    }
}

/// The range's non-blank cells as A1 addresses, from one `values.get`.
///
/// `grid` has already been clamped to the sheet's current extent by the
/// caller; the batch request itself retains the caller's original range.
async fn read_non_blank(
    api: &SheetsApi<'_>,
    spreadsheet_id: &str,
    range_a1: &str,
    grid: &GridRange,
) -> Result<Vec<String>, String> {
    let values = api
        .values_get(spreadsheet_id, range_a1, ValueRenderOption::Formatted)
        .await
        .map_err(|err| format!("{err:#}"))?;
    Ok(grid_range::non_blank_locations(
        &values,
        grid.start_row_index.unwrap_or(0),
        grid.start_column_index.unwrap_or(0),
    ))
}

/// The `fields_changed` summary a result logs. An unreadable-reply result
/// always logs its summary, though not the count that was in the reply.
fn logged_fields_changed(result: &TrimWhitespaceResult) -> Option<String> {
    match result {
        TrimWhitespaceResult::Changed {
            range,
            cells_changed_count,
        } => Some(match cells_changed_count {
            Some(count) => format!("trimmed {count} cell(s) in {range}"),
            None => format!("trimmed {range}; the API reported no count"),
        }),
        TrimWhitespaceResult::AppliedReplyUnreadable { summary, .. } => Some(summary.clone()),
        _ => None,
    }
}

fn record_attempt(outcome: &TrimWhitespaceOutcome, duration: Duration) {
    let decided_by = match &outcome.result {
        TrimWhitespaceResult::Blocked { decided_by } => decided_by.as_ref(),
        _ => None,
    };
    let decided_by = write_gate::decided_by_log_fields(decided_by);
    let fields_changed = logged_fields_changed(&outcome.result);
    let error = match &outcome.result {
        TrimWhitespaceResult::RefusedInvalidRequest { detail }
        | TrimWhitespaceResult::AppliedReplyUnreadable { detail, .. }
        | TrimWhitespaceResult::Failed { detail } => Some(detail.clone()),
        _ => None,
    };
    request_log::record_drive_mutation(DriveMutationOutcome {
        operation: LOG_OPERATION,
        file_id: outcome.spreadsheet_id.clone(),
        file_name: outcome.file_name.clone().unwrap_or_default(),
        status: outcome.result.log_status().to_string(),
        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,
        fields_changed,
        error,
        duration,
        ..Default::default()
    });
}

pub fn describe_lines(outcome: &TrimWhitespaceOutcome) -> Vec<String> {
    let book = outcome.file_name.as_deref().map_or_else(
        || format!("'{}'", outcome.spreadsheet_id),
        |name| format!("'{name}'"),
    );
    match &outcome.result {
        TrimWhitespaceResult::WouldChange {
            range,
            candidate_cells,
            read_clamped_to_sheet,
            ..
        } => {
            let mut lines = vec![
                format!("Would trim whitespace in {range} of {book}"),
                candidate_line(candidate_cells),
            ];
            if *read_clamped_to_sheet {
                lines.push(
                    "  the preview read was clipped to the sheet's current grid; the real run sends the requested range to Sheets".to_string(),
                );
            }
            lines
        }
        TrimWhitespaceResult::Changed {
            range,
            cells_changed_count,
        } => vec![match cells_changed_count {
            Some(count) => format!("Trimmed whitespace in {count} cell(s) of {range} in {book}"),
            None => {
                format!("Trimmed whitespace in {range} of {book}; the API reported no cell count")
            }
        }],
        TrimWhitespaceResult::RefusedInvalidRequest { detail } => {
            vec![format!("Refused: {detail}")]
        }
        TrimWhitespaceResult::RefusedNotASpreadsheet { mime_type } => vec![format!(
            "Refused: {book} is not a Google Sheet (mimeType: {mime_type})"
        )],
        TrimWhitespaceResult::RefusedShortcut => vec![format!(
            "Refused: {book} is a shortcut; trim-whitespace doesn't follow shortcuts"
        )],
        TrimWhitespaceResult::RefusedNoVisibleParents => {
            vec![format!("Refused: {book} has no visible parent folder")]
        }
        TrimWhitespaceResult::RefusedSheetNotFound { title, available } => {
            vec![grid_range::no_sheet_refusal(&book, title, available)]
        }
        TrimWhitespaceResult::Blocked { .. } => vec![format!(
            "Blocked: trim-whitespace on {book} requires an allowing sheets-write rule"
        )],
        TrimWhitespaceResult::RefusedNoLease => LeaseGateRefusal::NoLease
            .describe_line(&outcome.spreadsheet_id, &book)
            .into_iter()
            .collect(),
        TrimWhitespaceResult::RefusedLeaseExpired => LeaseGateRefusal::Expired
            .describe_line(&outcome.spreadsheet_id, &book)
            .into_iter()
            .collect(),
        TrimWhitespaceResult::RefusedLeaseWrongFile => LeaseGateRefusal::WrongFile
            .describe_line(&outcome.spreadsheet_id, &book)
            .into_iter()
            .collect(),
        TrimWhitespaceResult::RefusedLeaseStale => LeaseGateRefusal::Stale
            .describe_line(&outcome.spreadsheet_id, &book)
            .into_iter()
            .collect(),
        TrimWhitespaceResult::AppliedReplyUnreadable {
            summary, detail, ..
        } => vec![
            applied_reply_unreadable_line(summary, &book, RetryHint::Idempotent, detail),
            "  the cell count was in the unreadable reply; check the spreadsheet".to_string(),
        ],
        TrimWhitespaceResult::Failed { detail } => vec![format!("Failed: {detail}")],
    }
}

/// The indented candidate line. Always "may be trimmed", never "would be":
/// the server owns the trim rule, so a non-blank cell is a candidate, not
/// a prediction (module docs; ADR-0083 §6).
fn candidate_line(candidate_cells: &[String]) -> String {
    if candidate_cells.is_empty() {
        return "  no non-blank cells in the range".to_string();
    }
    format!(
        "  {} non-blank cell(s) may be trimmed: {}",
        candidate_cells.len(),
        grid_range::render_locations(candidate_cells)
    )
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use crate::drive::auth::{DriveCredentials, DriveGrantedScopes};
    use crate::drive::sheets::client::SHEETS_API_URL;
    use crate::drive::test_support::seed_lease;
    use crate::drive::types::GOOGLE_SHEET_MIME_TYPE;
    use crate::test_support::env::MapEnv;
    use crate::utils::secret::Secret;
    use std::collections::HashSet;

    async fn clients(server: &wiremock::MockServer) -> (DriveClient, SheetsClient) {
        let credentials = DriveCredentials {
            client_id: "client-1".into(),
            client_secret: Secret::new("secret-1"),
            refresh_token: Secret::new("refresh-1"),
            scope: DriveGrantedScopes::READONLY,
        };
        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 drive = DriveClient::new(&server.uri(), &credentials).unwrap();
        crate::drive::client::test_support::replace_session(
            &mut drive,
            &credentials,
            &format!("{}/token", server.uri()),
        );
        let env = MapEnv::new().with(SHEETS_API_URL, &server.uri());
        let sheets = SheetsClient::from_drive_client_with(&env, &drive).unwrap();
        (drive, sheets)
    }

    async fn mount_metadata(server: &wiremock::MockServer) {
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/sheet-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "sheet-1", "name": "Budget", "mimeType": GOOGLE_SHEET_MIME_TYPE,
                    "parents": ["parent-1"], "version": "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(200).set_body_json(serde_json::json!({
                    "id": "parent-1", "name": "parent-1",
                    "mimeType": "application/vnd.google-apps.folder", "parents": []
                })),
            )
            .mount(server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/v4/spreadsheets/sheet-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "spreadsheetId": "sheet-1",
                    "sheets": [{"properties": {
                        "sheetId": 0, "title": "Q1",
                        "gridProperties": {"rowCount": 100, "columnCount": 6}
                    }}]
                })),
            )
            .mount(server)
            .await;
    }

    /// A `values.get` reply for any range, carrying `values`.
    fn mount_values(values: serde_json::Value) -> wiremock::Mock {
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path_regex(
                r"^/v4/spreadsheets/sheet-1/values/.*$",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"values": values})),
            )
    }

    fn mount_batch_update(body: serde_json::Value) -> wiremock::Mock {
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path(
                "/v4/spreadsheets/sheet-1:batchUpdate",
            ))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(body))
    }

    fn options(dry_run: bool) -> TrimWhitespaceOptions {
        TrimWhitespaceOptions {
            spreadsheet_id: "sheet-1".into(),
            sheet: Some("Q1".into()),
            range: Some("A2:C10".into()),
            scope: TrimScope::Range,
            dry_run,
            lease_token: None,
            ledger_path: PathBuf::from("/tmp/unused-trim-whitespace-ledger"),
        }
    }

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

    fn rule_allowing(operation: DriveOperation) -> FolderPermissionRule {
        FolderPermissionRule {
            allow: std::iter::once(operation).collect(),
            ..rule()
        }
    }

    fn rule_requiring_lease() -> FolderPermissionRule {
        FolderPermissionRule {
            require_lease: true,
            ..rule()
        }
    }

    // ── scope validation (pure) ─────────────────────────────────────────

    #[test]
    fn whole_sheet_refuses_a_range_and_demands_a_sheet() {
        let mut opts = options(true);
        opts.scope = TrimScope::WholeSheet;
        assert!(validate_scope_syntax(&opts)
            .unwrap_err()
            .contains("cannot be combined with --range"));

        opts.range = None;
        opts.sheet = None;
        assert!(validate_scope_syntax(&opts)
            .unwrap_err()
            .contains("needs --sheet"));

        // A blank `--sheet` is as useless as an absent one.
        opts.sheet = Some("   ".into());
        assert!(validate_scope_syntax(&opts).is_err());

        opts.sheet = Some("Q1".into());
        assert!(validate_scope_syntax(&opts).is_ok());
    }

    #[test]
    fn range_scope_demands_a_non_empty_range_and_names_the_alternative() {
        let mut opts = options(true);
        opts.range = None;
        let err = validate_scope_syntax(&opts).unwrap_err();
        assert!(err.contains("--range"), "{err}");
        assert!(err.contains("--whole-sheet"), "{err}");

        opts.range = Some("  ".into());
        assert!(validate_scope_syntax(&opts).is_err());
    }

    // ── bound materialisation (pure) ────────────────────────────────────

    fn sheet_with(row_count: Option<i64>, column_count: Option<i64>) -> Sheet {
        let json = serde_json::json!({"properties": {
            "sheetId": 0, "title": "Q1",
            "gridProperties": {"rowCount": row_count, "columnCount": column_count}
        }});
        serde_json::from_value(json).unwrap()
    }

    #[test]
    fn materialise_bounds_fills_open_axes_from_the_sheet_extent() {
        let open = GridRange {
            sheet_id: 0,
            start_row_index: None,
            end_row_index: None,
            start_column_index: None,
            end_column_index: None,
        };
        let filled = materialise_bounds(&open, Some(&sheet_with(Some(100), Some(6))));
        assert_eq!(filled.start_row_index, Some(0));
        assert_eq!(filled.end_row_index, Some(100));
        assert_eq!(filled.start_column_index, Some(0));
        assert_eq!(filled.end_column_index, Some(6));
    }

    #[test]
    fn materialise_bounds_leaves_a_bound_the_sheet_reports_no_count_for() {
        let open = GridRange {
            sheet_id: 0,
            start_row_index: None,
            end_row_index: None,
            start_column_index: Some(0),
            end_column_index: Some(3),
        };
        let filled = materialise_bounds(&open, Some(&sheet_with(None, Some(6))));
        // A start always materialises to 0; an end can only come from the
        // sheet, so it stays absent and the caller refuses the range.
        assert_eq!(filled.start_row_index, Some(0));
        assert_eq!(filled.end_row_index, None);
    }

    /// With no sheet the ends cannot be filled, so the range stays
    /// unbounded and the caller refuses it as naming no cells — the
    /// behaviour that lets the engine skip a "sheet vanished" branch.
    #[test]
    fn materialise_bounds_without_a_sheet_leaves_the_ends_open() {
        let open = GridRange {
            sheet_id: 0,
            start_row_index: None,
            end_row_index: None,
            start_column_index: None,
            end_column_index: None,
        };
        let filled = materialise_bounds(&open, None);
        assert_eq!(filled.end_row_index, None);
        assert_eq!(filled.end_column_index, None);
        assert!(!grid_range::is_bounded(&filled));
    }

    #[test]
    fn materialise_bounds_never_widens_an_already_bounded_range() {
        let bounded = GridRange {
            sheet_id: 0,
            start_row_index: Some(1),
            end_row_index: Some(10),
            start_column_index: Some(0),
            end_column_index: Some(3),
        };
        assert_eq!(
            materialise_bounds(&bounded, Some(&sheet_with(Some(100), Some(6)))),
            bounded
        );
    }

    // ── rendering (pure) ────────────────────────────────────────────────

    #[test]
    fn the_candidate_line_says_may_be_trimmed_never_would_be() {
        let line = candidate_line(&["A1".to_string(), "B2".to_string()]);
        assert!(
            line.contains("2 non-blank cell(s) may be trimmed"),
            "{line}"
        );
        assert!(!line.contains("would be"), "{line}");
        assert_eq!(candidate_line(&[]), "  no non-blank cells in the range");
    }

    #[test]
    fn the_candidate_line_elides_past_the_render_limit_but_keeps_the_true_count() {
        let cells: Vec<String> = (1..=120).map(|row| format!("A{row}")).collect();
        let line = candidate_line(&cells);
        assert!(line.contains("120 non-blank cell(s)"), "{line}");
        assert!(line.contains("… and 70 more"), "{line}");
        assert!(!line.contains("A120"), "{line}");
    }

    #[test]
    fn lease_refusals_map_to_their_trim_whitespace_results() {
        assert_eq!(
            TrimWhitespaceResult::from_no_lease(),
            TrimWhitespaceResult::RefusedNoLease
        );
        assert_eq!(
            TrimWhitespaceResult::from_lease_expired(),
            TrimWhitespaceResult::RefusedLeaseExpired
        );
        assert_eq!(
            TrimWhitespaceResult::from_lease_wrong_file(),
            TrimWhitespaceResult::RefusedLeaseWrongFile
        );
        assert_eq!(
            TrimWhitespaceResult::from_lease_stale(),
            TrimWhitespaceResult::RefusedLeaseStale
        );
        assert_eq!(
            TrimWhitespaceResult::from_lease_failed("boom".into()),
            TrimWhitespaceResult::Failed {
                detail: "boom".into()
            }
        );
    }

    fn every_result() -> Vec<TrimWhitespaceResult> {
        vec![
            TrimWhitespaceResult::WouldChange {
                range: "Q1!A2:C10".into(),
                candidate_cells: vec!["A2".into()],
                candidate_cells_upper_bound: true,
                read_clamped_to_sheet: false,
            },
            TrimWhitespaceResult::WouldChange {
                range: "Q1!A2:C10".into(),
                candidate_cells: Vec::new(),
                candidate_cells_upper_bound: true,
                read_clamped_to_sheet: false,
            },
            TrimWhitespaceResult::Changed {
                range: "Q1!A2:C10".into(),
                cells_changed_count: Some(3),
            },
            TrimWhitespaceResult::Changed {
                range: "Q1!A2:C10".into(),
                cells_changed_count: None,
            },
            TrimWhitespaceResult::RefusedInvalidRequest {
                detail: "bad".into(),
            },
            TrimWhitespaceResult::RefusedNotASpreadsheet {
                mime_type: "application/pdf".into(),
            },
            TrimWhitespaceResult::RefusedShortcut,
            TrimWhitespaceResult::RefusedNoVisibleParents,
            TrimWhitespaceResult::RefusedSheetNotFound {
                title: "Nope".into(),
                available: vec!["Q1".into()],
            },
            TrimWhitespaceResult::Blocked { decided_by: None },
            TrimWhitespaceResult::RefusedNoLease,
            TrimWhitespaceResult::RefusedLeaseExpired,
            TrimWhitespaceResult::RefusedLeaseWrongFile,
            TrimWhitespaceResult::RefusedLeaseStale,
            TrimWhitespaceResult::AppliedReplyUnreadable {
                range: "Q1!A2:C10".into(),
                summary: "trim whitespace in Q1!A2:C10".into(),
                detail: "bad reply".into(),
            },
            TrimWhitespaceResult::Failed {
                detail: "boom".into(),
            },
        ]
    }

    #[test]
    fn every_result_renders_and_carries_a_distinct_log_status() {
        let mut statuses = HashSet::new();
        for result in every_result() {
            let outcome = TrimWhitespaceOutcome {
                spreadsheet_id: "sheet-1".into(),
                file_name: Some("Budget".into()),
                resolved_folder_id: None,
                result,
            };
            assert!(
                !describe_lines(&outcome).is_empty(),
                "{:?} rendered nothing",
                outcome.result
            );
            statuses.insert(outcome.result.log_status());
        }
        // 16 results, 14 distinct statuses: the two `WouldChange`s share
        // one and the two `Changed`s share another.
        assert_eq!(statuses.len(), 14);
    }

    #[test]
    fn describe_lines_renders_applied_reply_unreadable_with_a_count_hint() {
        let outcome = TrimWhitespaceOutcome {
            spreadsheet_id: "sheet-1".into(),
            file_name: Some("Budget".into()),
            resolved_folder_id: None,
            result: TrimWhitespaceResult::AppliedReplyUnreadable {
                range: "Q1!A2:C10".into(),
                summary: "trim whitespace in Q1!A2:C10".into(),
                detail: "bad reply".into(),
            },
        };
        assert_eq!(
            describe_lines(&outcome),
            [
                "Applied, but the reply could not be read: trim whitespace in Q1!A2:C10 in \
                 'Budget' — check the spreadsheet to confirm (bad reply)",
                "  the cell count was in the unreadable reply; check the spreadsheet",
            ]
        );
    }

    #[test]
    fn an_unreadable_reply_logs_its_summary_and_serializes_its_range() {
        let result = TrimWhitespaceResult::AppliedReplyUnreadable {
            range: "Q1!A2:C10".into(),
            summary: "trim whitespace in Q1!A2:C10".into(),
            detail: "bad reply".into(),
        };
        assert_eq!(
            logged_fields_changed(&result).as_deref(),
            Some("trim whitespace in Q1!A2:C10")
        );
        let json = serde_json::to_value(&result).unwrap();
        assert_eq!(json["status"], "applied-reply-unreadable");
        assert_eq!(json["range"], "Q1!A2:C10");
    }

    #[test]
    fn describe_lines_falls_back_to_the_spreadsheet_id_with_no_file_name() {
        let outcome = TrimWhitespaceOutcome {
            spreadsheet_id: "sheet-1".into(),
            file_name: None,
            resolved_folder_id: None,
            result: TrimWhitespaceResult::RefusedShortcut,
        };
        assert!(describe_lines(&outcome).join("\n").contains("'sheet-1'"));
    }

    #[test]
    fn write_jsonl_emits_one_line_of_json() {
        let outcome = TrimWhitespaceOutcome {
            spreadsheet_id: "sheet-1".into(),
            file_name: Some("Budget".into()),
            resolved_folder_id: None,
            result: TrimWhitespaceResult::Changed {
                range: "Q1!A2:C10".into(),
                cells_changed_count: Some(3),
            },
        };
        let mut buf = Vec::new();
        outcome.write_jsonl(&mut buf).unwrap();
        let text = String::from_utf8(buf).unwrap();
        assert_eq!(text.lines().count(), 1);
        assert!(text.contains("\"cells_changed_count\":3"), "{text}");
    }

    // ── the gate ────────────────────────────────────────────────────────

    /// A real (non-dry) run records its attempt, so a denied one must reach
    /// the request log's `Blocked` arm too.
    #[tokio::test]
    async fn a_denied_real_run_is_blocked_and_recorded() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_metadata(&server).await;
        let outcome = trim_whitespace(&drive, &sheets, &options(false), &[]).await;
        assert_eq!(outcome.result.log_status(), "blocked", "{outcome:?}");
        assert!(matches!(
            outcome.result,
            TrimWhitespaceResult::Blocked { .. }
        ));
    }

    #[tokio::test]
    async fn gate_denies_sheets_write_by_default() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_metadata(&server).await;
        let outcome = trim_whitespace(&drive, &sheets, &options(true), &[]).await;
        assert!(
            matches!(outcome.result, TrimWhitespaceResult::Blocked { .. }),
            "{outcome:?}"
        );
    }

    /// The other half of `delete-duplicates`' non-widening test: the two
    /// verbs in issue #1844 take different operations, so neither grant
    /// may stand in for the other.
    #[tokio::test]
    async fn a_sheets_delete_grant_alone_does_not_permit_trim_whitespace() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_metadata(&server).await;
        let outcome = trim_whitespace(
            &drive,
            &sheets,
            &options(true),
            &[rule_allowing(DriveOperation::SheetsDelete)],
        )
        .await;
        assert!(
            matches!(outcome.result, TrimWhitespaceResult::Blocked { .. }),
            "{outcome:?}"
        );
    }

    #[tokio::test]
    async fn a_denied_target_makes_no_sheets_calls_at_all() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_metadata(&server).await;
        let _ = trim_whitespace(&drive, &sheets, &options(true), &[]).await;
        let requests = server.received_requests().await.unwrap();
        assert!(
            !requests
                .iter()
                .any(|request| request.url.path().starts_with("/v4/spreadsheets")),
            "a blocked run reached the Sheets API"
        );
    }

    // ── target-gate failures and refusals ───────────────────────────────

    #[tokio::test]
    async fn a_metadata_fetch_failure_surfaces_as_failed_without_a_file_name() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/sheet-1"))
            .respond_with(wiremock::ResponseTemplate::new(404).set_body_string("not found"))
            .mount(&server)
            .await;

        let outcome = trim_whitespace(&drive, &sheets, &options(true), &[]).await;

        assert!(matches!(
            outcome.result,
            TrimWhitespaceResult::Failed { .. }
        ));
        assert!(outcome.file_name.is_none());
    }

    #[tokio::test]
    async fn a_shortcut_target_is_refused_without_following_it() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/sheet-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "sheet-1", "name": "Budget",
                    "mimeType": "application/vnd.google-apps.shortcut",
                    "parents": ["parent-1"], "version": "1"
                })),
            )
            .mount(&server)
            .await;

        let outcome = trim_whitespace(&drive, &sheets, &options(true), &[]).await;

        assert_eq!(outcome.result, TrimWhitespaceResult::RefusedShortcut);
        assert_eq!(outcome.file_name.as_deref(), Some("Budget"));
    }

    #[tokio::test]
    async fn a_non_spreadsheet_target_is_refused_with_its_mime_type() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/sheet-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "sheet-1", "name": "Budget",
                    "mimeType": "application/vnd.google-apps.document",
                    "parents": ["parent-1"], "version": "1"
                })),
            )
            .mount(&server)
            .await;

        let outcome = trim_whitespace(&drive, &sheets, &options(true), &[]).await;

        assert_eq!(
            outcome.result,
            TrimWhitespaceResult::RefusedNotASpreadsheet {
                mime_type: "application/vnd.google-apps.document".into(),
            }
        );
        assert_eq!(outcome.file_name.as_deref(), Some("Budget"));
    }

    #[tokio::test]
    async fn a_target_with_no_visible_parents_is_refused() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/sheet-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "sheet-1", "name": "Budget", "mimeType": GOOGLE_SHEET_MIME_TYPE,
                    "parents": [], "version": "1"
                })),
            )
            .mount(&server)
            .await;

        let outcome = trim_whitespace(&drive, &sheets, &options(true), &[]).await;

        assert_eq!(
            outcome.result,
            TrimWhitespaceResult::RefusedNoVisibleParents
        );
        assert_eq!(outcome.file_name.as_deref(), Some("Budget"));
    }

    #[tokio::test]
    async fn a_gate_ancestor_fetch_failure_surfaces_as_failed_with_the_file_name() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/sheet-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "sheet-1", "name": "Budget", "mimeType": GOOGLE_SHEET_MIME_TYPE,
                    "parents": ["parent-1"], "version": "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("boom"))
            .mount(&server)
            .await;

        let outcome = trim_whitespace(&drive, &sheets, &options(true), &[]).await;

        assert!(matches!(
            outcome.result,
            TrimWhitespaceResult::Failed { .. }
        ));
        assert_eq!(outcome.file_name.as_deref(), Some("Budget"));
        assert!(outcome.resolved_folder_id.is_none());
    }

    #[tokio::test]
    async fn a_workbook_fetch_failure_after_a_granted_gate_surfaces_as_failed() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_metadata(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/v4/spreadsheets/sheet-1"))
            .respond_with(wiremock::ResponseTemplate::new(500).set_body_string("boom"))
            .mount(&server)
            .await;

        let outcome = trim_whitespace(&drive, &sheets, &options(true), &[rule()]).await;

        assert!(matches!(
            outcome.result,
            TrimWhitespaceResult::Failed { .. }
        ));
        assert_eq!(outcome.file_name.as_deref(), Some("Budget"));
    }

    // ── the two read paths ──────────────────────────────────────────────

    #[tokio::test]
    async fn dry_run_reads_values_once_and_never_mutates() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_metadata(&server).await;
        mount_values(serde_json::json!([
            ["  padded  ", "", "x"],
            [null, "y", null]
        ]))
        .mount(&server)
        .await;
        let outcome = trim_whitespace(&drive, &sheets, &options(true), &[rule()]).await;
        let json = serde_json::to_value(&outcome).unwrap();
        assert_eq!(json["result"]["candidate_cells_upper_bound"], true);
        let TrimWhitespaceResult::WouldChange {
            range,
            candidate_cells,
            candidate_cells_upper_bound,
            read_clamped_to_sheet,
        } = outcome.result
        else {
            panic!("expected would-change"); // omni-dev: coverage ignore-line reason="this let-else panic only runs if the match failed to bind the expected variant; the mocked run always produces it"
        };
        assert_eq!(range, "'Q1'!A2:C10");
        // Offsets are the range's own start (row 1, column 0 zero-based).
        assert_eq!(candidate_cells, vec!["A2", "C2", "B3"]);
        assert!(candidate_cells_upper_bound);
        assert!(!read_clamped_to_sheet);

        let requests = server.received_requests().await.unwrap();
        assert_eq!(
            requests
                .iter()
                .filter(|r| r.url.path().contains("/values/"))
                .count(),
            1
        );
        assert!(
            !requests
                .iter()
                .any(|r| r.url.path().ends_with(":batchUpdate")),
            "a dry run mutated"
        );
    }

    #[tokio::test]
    async fn dry_run_clamps_an_explicit_range_to_the_sheet_grid_for_its_read() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_metadata(&server).await;
        mount_values(serde_json::json!([["  padded  "]]))
            .mount(&server)
            .await;
        let mut opts = options(true);
        opts.range = Some("E90:J120".into());

        let outcome = trim_whitespace(&drive, &sheets, &opts, &[rule()]).await;
        assert_eq!(
            outcome.result,
            TrimWhitespaceResult::WouldChange {
                range: "'Q1'!E90:J120".into(),
                candidate_cells: vec!["E90".into()],
                candidate_cells_upper_bound: true,
                read_clamped_to_sheet: true,
            }
        );
        assert_eq!(
            serde_json::to_value(&outcome).unwrap()["result"]["read_clamped_to_sheet"],
            true
        );
        assert!(describe_lines(&outcome)
            .join("\n")
            .contains("preview read was clipped"));
        let requests = server.received_requests().await.unwrap();
        let reads: Vec<_> = requests
            .iter()
            .filter(|request| request.url.path().contains("/values/"))
            .collect();
        assert_eq!(reads.len(), 1);
        let read_path = reads[0].url.path();
        assert!(
            read_path.contains("E90") && read_path.contains("F100"),
            "{read_path}"
        );
        assert!(!read_path.contains("J120"), "{read_path}");
    }

    /// The deviation from `auto_fill.rs`/`paste.rs` recorded in the module
    /// docs: the real run reports the server's exact count, so re-reading
    /// the range would buy nothing.
    #[tokio::test]
    async fn real_run_sends_one_trim_request_and_reads_no_values() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_metadata(&server).await;
        mount_batch_update(serde_json::json!({
            "replies": [{"trimWhitespace": {"cellsChangedCount": 7}}]
        }))
        .mount(&server)
        .await;
        let outcome = trim_whitespace(&drive, &sheets, &options(false), &[rule()]).await;
        assert_eq!(
            outcome.result,
            TrimWhitespaceResult::Changed {
                range: "'Q1'!A2:C10".into(),
                cells_changed_count: Some(7),
            }
        );

        let requests = server.received_requests().await.unwrap();
        assert!(
            !requests.iter().any(|r| r.url.path().contains("/values/")),
            "the real run read values it did not need"
        );
        let batch = requests
            .iter()
            .find(|r| r.url.path().ends_with(":batchUpdate"))
            .unwrap();
        let body: serde_json::Value = serde_json::from_slice(&batch.body).unwrap();
        assert_eq!(
            body["requests"][0]["trimWhitespace"]["range"],
            serde_json::json!({
                "sheetId": 0, "startRowIndex": 1, "endRowIndex": 10,
                "startColumnIndex": 0, "endColumnIndex": 3
            })
        );
        assert_eq!(body["requests"].as_array().unwrap().len(), 1);
    }

    #[tokio::test]
    async fn whole_sheet_sends_the_materialised_grid_extent() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_metadata(&server).await;
        mount_batch_update(serde_json::json!({"replies": [{}]}))
            .mount(&server)
            .await;
        let mut opts = options(false);
        opts.scope = TrimScope::WholeSheet;
        opts.range = None;
        let outcome = trim_whitespace(&drive, &sheets, &opts, &[rule()]).await;
        let TrimWhitespaceResult::Changed { range, .. } = &outcome.result else {
            panic!("expected changed"); // omni-dev: coverage ignore-line reason="this let-else panic only runs if the match failed to bind the expected variant; the mocked run always produces it"
        };
        assert_eq!(range, "'Q1'!A1:F100");

        let requests = server.received_requests().await.unwrap();
        let batch = requests
            .iter()
            .find(|r| r.url.path().ends_with(":batchUpdate"))
            .unwrap();
        let body: serde_json::Value = serde_json::from_slice(&batch.body).unwrap();
        assert_eq!(
            body["requests"][0]["trimWhitespace"]["range"]["endColumnIndex"],
            6
        );
    }

    #[tokio::test]
    async fn a_reply_without_a_trim_object_reports_changed_with_no_count() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_metadata(&server).await;
        mount_batch_update(serde_json::json!({"replies": [{}]}))
            .mount(&server)
            .await;
        let outcome = trim_whitespace(&drive, &sheets, &options(false), &[rule()]).await;
        assert_eq!(
            outcome.result,
            TrimWhitespaceResult::Changed {
                range: "'Q1'!A2:C10".into(),
                cells_changed_count: None,
            }
        );
        assert!(describe_lines(&outcome)
            .join("\n")
            .contains("reported no cell count"));
    }

    // ── the "never a cell value" guard (ADR-0083 §6) ─────────────────────

    #[tokio::test]
    async fn no_cell_value_ever_reaches_the_outcome_or_its_rendering() {
        const SECRET: &str = "  zzsecretzz  ";
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_metadata(&server).await;
        mount_values(serde_json::json!([[SECRET]]))
            .mount(&server)
            .await;
        let outcome = trim_whitespace(&drive, &sheets, &options(true), &[rule()]).await;

        let json = serde_json::to_string(&outcome).unwrap();
        assert!(!json.contains("zzsecretzz"), "{json}");
        assert!(!describe_lines(&outcome).join("\n").contains("zzsecretzz"));
    }

    // ── failure paths ───────────────────────────────────────────────────

    #[tokio::test]
    async fn a_values_read_failure_surfaces_as_failed() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_metadata(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path_regex(
                r"^/v4/spreadsheets/sheet-1/values/.*$",
            ))
            .respond_with(wiremock::ResponseTemplate::new(500).set_body_string("boom"))
            .mount(&server)
            .await;
        let outcome = trim_whitespace(&drive, &sheets, &options(true), &[rule()]).await;
        assert!(
            matches!(outcome.result, TrimWhitespaceResult::Failed { .. }),
            "{outcome:?}"
        );
    }

    #[tokio::test]
    async fn a_batch_update_failure_surfaces_as_failed() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_metadata(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path(
                "/v4/spreadsheets/sheet-1:batchUpdate",
            ))
            .respond_with(wiremock::ResponseTemplate::new(500).set_body_string("boom"))
            .mount(&server)
            .await;
        let outcome = trim_whitespace(&drive, &sheets, &options(false), &[rule()]).await;
        assert!(
            matches!(outcome.result, TrimWhitespaceResult::Failed { .. }),
            "{outcome:?}"
        );
    }

    #[tokio::test]
    async fn trim_whitespace_with_an_unreadable_reply_reports_applied_reply_unreadable() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_metadata(&server).await;
        // 2xx, so the trim WAS applied — but the body is not the reply shape.
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path(
                "/v4/spreadsheets/sheet-1:batchUpdate",
            ))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_string("not json"))
            .expect(1)
            .mount(&server)
            .await;
        let outcome = trim_whitespace(&drive, &sheets, &options(false), &[rule()]).await;
        assert_eq!(
            outcome.result.log_status(),
            "applied-reply-unreadable",
            "{outcome:?}"
        );
        let lines = describe_lines(&outcome);
        assert!(
            lines[0].starts_with("Applied, but the reply could not be read"),
            "{lines:?}"
        );
        assert!(
            lines[0].contains("check the spreadsheet to confirm"),
            "{lines:?}"
        );
    }

    #[tokio::test]
    async fn an_unknown_sheet_is_refused_with_the_available_titles() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_metadata(&server).await;
        let mut opts = options(true);
        opts.scope = TrimScope::WholeSheet;
        opts.sheet = Some("Nope".into());
        opts.range = None;
        let outcome = trim_whitespace(&drive, &sheets, &opts, &[rule()]).await;
        assert_eq!(
            outcome.result,
            TrimWhitespaceResult::RefusedSheetNotFound {
                title: "Nope".into(),
                available: vec!["Q1".into()],
            }
        );
    }

    #[tokio::test]
    async fn a_scope_refusal_happens_before_any_network_call() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        let mut opts = options(true);
        opts.range = None;
        let outcome = trim_whitespace(&drive, &sheets, &opts, &[rule()]).await;
        assert!(matches!(
            outcome.result,
            TrimWhitespaceResult::RefusedInvalidRequest { .. }
        ));
        assert!(server.received_requests().await.unwrap().is_empty());
    }

    // ── 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 (drive, sheets) = clients(&server).await;
        mount_metadata(&server).await;
        // No batchUpdate mock: a refusal must make zero mutating calls.
        let outcome =
            trim_whitespace(&drive, &sheets, &options(false), &[rule_requiring_lease()]).await;
        assert_eq!(outcome.result, TrimWhitespaceResult::RefusedNoLease);
    }

    #[tokio::test]
    async fn refuses_a_lease_bound_to_a_different_file() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_metadata(&server).await;
        let dir = tempfile::tempdir().unwrap();
        let ledger_path = dir.path().join("leases.json");
        let token = seed_lease(&ledger_path, "other-file", "1");
        let mut opts = options(false);
        opts.lease_token = Some(token);
        opts.ledger_path = ledger_path;
        let outcome = trim_whitespace(&drive, &sheets, &opts, &[rule_requiring_lease()]).await;
        assert_eq!(outcome.result, TrimWhitespaceResult::RefusedLeaseWrongFile);
    }

    #[tokio::test]
    async fn a_valid_lease_lets_the_write_through() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_metadata(&server).await;
        mount_batch_update(serde_json::json!({
            "replies": [{"trimWhitespace": {"cellsChangedCount": 1}}]
        }))
        .mount(&server)
        .await;
        let dir = tempfile::tempdir().unwrap();
        let ledger_path = dir.path().join("leases.json");
        let token = seed_lease(&ledger_path, "sheet-1", "1");
        let mut opts = options(false);
        opts.lease_token = Some(token);
        opts.ledger_path = ledger_path;
        let outcome = trim_whitespace(&drive, &sheets, &opts, &[rule_requiring_lease()]).await;
        assert!(
            matches!(
                outcome.result,
                TrimWhitespaceResult::Changed {
                    cells_changed_count: Some(1),
                    ..
                }
            ),
            "{outcome:?}"
        );
    }
}