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
//! CLI commands for `omni-dev drive sheets add-sheet`/`rename-sheet`/
//! `insert-rows`/`insert-columns` (issue #1613), `insert-range` (issue
//! #1838), `duplicate-sheet`/
//! `reorder-sheet`/`hide-sheet`/`show-sheet` (issue #1643),
//! `delete-sheet`/`delete-rows`/`delete-columns`/`delete-range` (issue
//! #1623), `move-rows`/`move-columns` (issue #1834),
//! `update-sheet-properties` (issue #1835) and `update-workbook-properties`
//! (issue #1836).
//!
//! Seventeen clap structs over one engine call. They share `run_structure`, so
//! the gate wiring, `--dry-run` handling, output rendering and request
//! logging cannot drift between them — the same arrangement `write.rs` uses
//! for its three verbs. The additive verbs are gated on
//! `DriveOperation::SheetsStructure`; the destructive ones on
//! `DriveOperation::SheetsDelete` — `StructureVerb::gate_operation` decides
//! which, not this layer.
//!
//! There is deliberately **no** command that takes a raw
//! `spreadsheets.batchUpdate` request array, additive or destructive. Each
//! verb names its effect in typed arguments, which is what lets `--dry-run`
//! describe the change; see `crate::drive::sheets::structure`.

use anyhow::Result;
use clap::Parser;

use crate::cli::drive::format::{output_as, OutputFormat};
use crate::cli::drive::helpers;
use crate::cli::drive::helpers::StructureWriteArgs;
use crate::cli::format::sanitize_for_terminal;
use crate::drive::client::DriveClient;
use crate::drive::sheets::client::SheetsClient;
use crate::drive::sheets::structure::{
    describe_lines, structure, IterativeCalculationToggle, StructureOptions, StructureVerb,
};

/// The spreadsheet-id positional argument shared by every structural command
/// in this file (17 structs at last count) — flattened so a wording tweak
/// can't drift between them the way `StructureWriteArgs` (#1990) already
/// stops for the dry-run/lease/output trio.
#[derive(Parser)]
pub struct SpreadsheetIdArg {
    /// Spreadsheet id (the `/d/<ID>/` segment of a Sheets URL).
    pub spreadsheet_id: String,
}

/// Adds a new sheet to a spreadsheet.
#[derive(Parser)]
pub struct AddSheetCommand {
    #[command(flatten)]
    pub target: SpreadsheetIdArg,

    /// Title for the new sheet. Must not already exist in the workbook.
    #[arg(long, value_name = "TITLE")]
    pub title: String,

    /// Zero-based position in the workbook. Omitted appends to the end.
    #[arg(long, value_name = "N")]
    pub index: Option<i64>,

    /// Initial row count. Omitted takes Sheets' own default (1000).
    #[arg(long, value_name = "N")]
    pub rows: Option<i64>,

    /// Initial column count. Omitted takes Sheets' own default (26).
    #[arg(long, value_name = "N")]
    pub columns: Option<i64>,

    #[command(flatten)]
    pub write: StructureWriteArgs,
}

/// Renames an existing sheet.
#[derive(Parser)]
pub struct RenameSheetCommand {
    #[command(flatten)]
    pub target: SpreadsheetIdArg,

    /// Current title of the sheet to rename.
    #[arg(long, value_name = "NAME")]
    pub sheet: String,

    /// The new title.
    #[arg(long, value_name = "TITLE")]
    pub title: String,

    #[command(flatten)]
    pub write: StructureWriteArgs,
}

/// Inserts empty rows, shifting existing rows down.
#[derive(Parser)]
pub struct InsertRowsCommand {
    #[command(flatten)]
    pub target: SpreadsheetIdArg,

    /// Title of the sheet to modify.
    #[arg(long, value_name = "NAME")]
    pub sheet: String,

    /// Insert before this row, 1-based — the row number the spreadsheet
    /// itself shows. `--at 5` puts the new rows above the current row 5.
    #[arg(long, value_name = "ROW")]
    pub at: i64,

    /// How many rows to insert.
    #[arg(long, value_name = "N", default_value_t = 1)]
    pub count: i64,

    #[command(flatten)]
    pub write: StructureWriteArgs,
}

/// Inserts empty columns, shifting existing columns right.
#[derive(Parser)]
pub struct InsertColumnsCommand {
    #[command(flatten)]
    pub target: SpreadsheetIdArg,

    /// Title of the sheet to modify.
    #[arg(long, value_name = "NAME")]
    pub sheet: String,

    /// Insert before this column, 1-based (column A is 1).
    #[arg(long, value_name = "COLUMN")]
    pub at: i64,

    /// How many columns to insert.
    #[arg(long, value_name = "N", default_value_t = 1)]
    pub count: i64,

    #[command(flatten)]
    pub write: StructureWriteArgs,
}

/// Moves a contiguous block of rows to a new position within a sheet,
/// shifting the rows in between to close the gap.
#[derive(Parser)]
pub struct MoveRowsCommand {
    #[command(flatten)]
    pub target: SpreadsheetIdArg,

    /// Title of the sheet to modify.
    #[arg(long, value_name = "NAME")]
    pub sheet: String,

    /// First row of the block to move, 1-based inclusive — the row number
    /// the spreadsheet itself shows.
    #[arg(long, value_name = "ROW")]
    pub at: i64,

    /// How many rows the block spans.
    #[arg(long, value_name = "N", default_value_t = 1)]
    pub count: i64,

    /// Move the block to before this row, numbered as the sheet stands
    /// *before* the move — the same numbering `--at` uses. `--before` one
    /// past the sheet's last row moves the block to the end. A `--before`
    /// inside or immediately after the block being moved is refused (it
    /// would move nothing).
    #[arg(long, value_name = "ROW")]
    pub before: i64,

    #[command(flatten)]
    pub write: StructureWriteArgs,
}

/// Moves a contiguous block of columns to a new position within a sheet,
/// shifting the columns in between to close the gap.
#[derive(Parser)]
pub struct MoveColumnsCommand {
    #[command(flatten)]
    pub target: SpreadsheetIdArg,

    /// Title of the sheet to modify.
    #[arg(long, value_name = "NAME")]
    pub sheet: String,

    /// First column of the block to move, 1-based inclusive (column A is
    /// 1) — the column number the spreadsheet itself shows.
    #[arg(long, value_name = "COLUMN")]
    pub at: i64,

    /// How many columns the block spans.
    #[arg(long, value_name = "N", default_value_t = 1)]
    pub count: i64,

    /// Move the block to before this column, numbered as the sheet stands
    /// *before* the move — the same numbering `--at` uses (column A is 1).
    /// `--before` one past the sheet's last column moves the block to the
    /// end. A `--before` inside or immediately after the block being moved
    /// is refused (it would move nothing).
    #[arg(long, value_name = "COLUMN")]
    pub before: i64,

    #[command(flatten)]
    pub write: StructureWriteArgs,
}

/// Deletes an entire sheet from a spreadsheet.
///
/// Gated by the folder write-permission rules' `sheets-delete` operation
/// (issue #1623) — distinct from `sheets-structure`, so an existing
/// `allow: ["sheets-structure"]` rule does not also grant this. This cannot
/// be undone through omni-dev; the `--lease` this delete requires (ADR-0080
/// §9) backed the whole spreadsheet up when it was acquired, and that copy
/// — named in the real-run message, not Google Drive's own version history
/// — is the primary recovery path. A rule that opts out with
/// `require_lease: false` takes no backup, and the message then says so.
#[derive(Parser)]
pub struct DeleteSheetCommand {
    #[command(flatten)]
    pub target: SpreadsheetIdArg,

    /// Title of the sheet to delete.
    #[arg(long, value_name = "NAME")]
    pub sheet: String,

    #[command(flatten)]
    pub write: StructureWriteArgs,
}

/// Deletes whole rows, shifting the remainder up to close the gap.
///
/// Gated by `sheets-delete` (issue #1623); see [`DeleteSheetCommand`]'s doc
/// comment.
#[derive(Parser)]
pub struct DeleteRowsCommand {
    #[command(flatten)]
    pub target: SpreadsheetIdArg,

    /// Title of the sheet to modify.
    #[arg(long, value_name = "NAME")]
    pub sheet: String,

    /// First row to delete, 1-based inclusive — the row number the
    /// spreadsheet itself shows.
    #[arg(long, value_name = "ROW")]
    pub at: i64,

    /// How many rows to delete.
    #[arg(long, value_name = "N", default_value_t = 1)]
    pub count: i64,

    #[command(flatten)]
    pub write: StructureWriteArgs,
}

/// Deletes whole columns, shifting the remainder left to close the gap.
///
/// Gated by `sheets-delete` (issue #1623); see [`DeleteSheetCommand`]'s doc
/// comment.
#[derive(Parser)]
pub struct DeleteColumnsCommand {
    #[command(flatten)]
    pub target: SpreadsheetIdArg,

    /// Title of the sheet to modify.
    #[arg(long, value_name = "NAME")]
    pub sheet: String,

    /// First column to delete, 1-based inclusive (column A is 1).
    #[arg(long, value_name = "COLUMN")]
    pub at: i64,

    /// How many columns to delete.
    #[arg(long, value_name = "N", default_value_t = 1)]
    pub count: i64,

    #[command(flatten)]
    pub write: StructureWriteArgs,
}

/// Which way a range operation shifts cells, mirroring
/// [`crate::drive::sheets::types::ShiftDimension`].
///
/// A CLI-facing copy for the same reason
/// [`crate::cli::drive::permissions::check::OperationArg`] mirrors
/// `DriveOperation`: the pure engine module stays free of `clap`.
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
pub enum ShiftArg {
    /// Cells below a range shift up after deletion or down after insertion.
    Rows,
    /// Cells to the right of a range shift left after deletion or right after
    /// insertion.
    Columns,
}

impl From<ShiftArg> for crate::drive::sheets::types::ShiftDimension {
    fn from(arg: ShiftArg) -> Self {
        match arg {
            ShiftArg::Rows => Self::Rows,
            ShiftArg::Columns => Self::Columns,
        }
    }
}

/// The rectangle-plus-shift-direction arguments shared verbatim by
/// [`InsertRangeCommand`] and [`DeleteRangeCommand`] — `insert-range`'s exact
/// inverse (issue #1838). Flattened rather than duplicated so the two
/// commands' bounds can't drift apart field by field.
#[derive(Parser)]
pub struct GridRangeArgs {
    /// First row of the range, 1-based inclusive.
    #[arg(long, value_name = "ROW")]
    pub start_row: i64,

    /// Last row of the range, 1-based inclusive.
    #[arg(long, value_name = "ROW")]
    pub end_row: i64,

    /// First column of the range, 1-based inclusive.
    #[arg(long, value_name = "COLUMN")]
    pub start_column: i64,

    /// Last column of the range, 1-based inclusive.
    #[arg(long, value_name = "COLUMN")]
    pub end_column: i64,

    /// Which way to shift cells to make room for or close the gap left by
    /// this range.
    #[arg(long, value_enum)]
    pub shift: ShiftArg,
}

/// Inserts empty cells into a rectangular range, shifting existing cells
/// down or right within the same grid.
///
/// Gated by the folder write-permission rules' `sheets-structure` operation
/// (issue #1838). Cells shifted past the sheet's grid extent are dropped by
/// the Sheets API.
#[derive(Parser)]
pub struct InsertRangeCommand {
    #[command(flatten)]
    pub target: SpreadsheetIdArg,

    /// Title of the sheet to modify.
    #[arg(long, value_name = "NAME")]
    pub sheet: String,

    #[command(flatten)]
    pub range: GridRangeArgs,

    #[command(flatten)]
    pub write: StructureWriteArgs,
}

/// Deletes a rectangular cell range, shifting the remainder along one axis
/// to close the gap.
///
/// Gated by `sheets-delete` (issue #1623); see [`DeleteSheetCommand`]'s doc
/// comment. All four bounds are required together — a rectangle, not an
/// open-ended span; `delete-rows`/`delete-columns` cover the whole-dimension
/// case.
#[derive(Parser)]
pub struct DeleteRangeCommand {
    #[command(flatten)]
    pub target: SpreadsheetIdArg,

    /// Title of the sheet to modify.
    #[arg(long, value_name = "NAME")]
    pub sheet: String,

    #[command(flatten)]
    pub range: GridRangeArgs,

    #[command(flatten)]
    pub write: StructureWriteArgs,
}

/// Copies an existing sheet within the same workbook.
#[derive(Parser)]
pub struct DuplicateSheetCommand {
    #[command(flatten)]
    pub target: SpreadsheetIdArg,

    /// Title of the sheet to copy.
    #[arg(long, value_name = "NAME")]
    pub sheet: String,

    /// Title for the copy. Omitted takes Sheets' own "Copy of X" default.
    /// Must not already exist in the workbook (checked against the source's
    /// own title too — the source keeps its name).
    #[arg(long, value_name = "TITLE")]
    pub title: Option<String>,

    /// Zero-based position for the copy. Omitted takes Sheets' own default
    /// — confirmed against the live API to be the *front* of the workbook
    /// (index 0), not the end: unlike `add-sheet`, `duplicateSheetRequest`
    /// does not default to appending.
    #[arg(long, value_name = "N")]
    pub index: Option<i64>,

    #[command(flatten)]
    pub write: StructureWriteArgs,
}

/// Moves an existing sheet to a new position among its siblings.
#[derive(Parser)]
pub struct ReorderSheetCommand {
    #[command(flatten)]
    pub target: SpreadsheetIdArg,

    /// Title of the sheet to move.
    #[arg(long, value_name = "NAME")]
    pub sheet: String,

    /// The new zero-based position among the workbook's existing sheets.
    #[arg(long, value_name = "N")]
    pub index: i64,

    #[command(flatten)]
    pub write: StructureWriteArgs,
}

/// Hides an existing sheet.
#[derive(Parser)]
pub struct HideSheetCommand {
    #[command(flatten)]
    pub target: SpreadsheetIdArg,

    /// Title of the sheet to hide.
    #[arg(long, value_name = "NAME")]
    pub sheet: String,

    #[command(flatten)]
    pub write: StructureWriteArgs,
}

/// Shows an existing hidden sheet.
#[derive(Parser)]
pub struct ShowSheetCommand {
    #[command(flatten)]
    pub target: SpreadsheetIdArg,

    /// Title of the sheet to show.
    #[arg(long, value_name = "NAME")]
    pub sheet: String,

    #[command(flatten)]
    pub write: StructureWriteArgs,
}

/// Changes a sheet's view properties — frozen rows/columns, tab color,
/// right-to-left layout, and whether gridlines are hidden (issue #1835).
/// Every flag is independently optional; only the ones passed are sent, in
/// a field mask naming exactly them.
#[derive(Parser)]
#[command(group(clap::ArgGroup::new("change")
    .args(["freeze_rows", "freeze_columns", "tab_color", "clear_tab_color", "right_to_left", "hide_gridlines"])
    .multiple(true)
    .required(true)))]
pub struct UpdateSheetPropertiesCommand {
    #[command(flatten)]
    pub target: SpreadsheetIdArg,

    /// Title of the sheet to modify.
    #[arg(long, value_name = "NAME")]
    pub sheet: String,

    /// Rows to freeze at the top of the grid; 0 unfreezes.
    #[arg(long, value_name = "N")]
    pub freeze_rows: Option<i64>,

    /// Columns to freeze at the left of the grid; 0 unfreezes.
    #[arg(long, value_name = "N")]
    pub freeze_columns: Option<i64>,

    /// The new tab color, `#RRGGBB`.
    #[arg(long, value_name = "HEX", conflicts_with = "clear_tab_color")]
    pub tab_color: Option<String>,

    /// Clears the tab color back to none.
    #[arg(long, conflicts_with = "tab_color")]
    pub clear_tab_color: bool,

    /// Whether the sheet is laid out right-to-left.
    #[arg(long, value_name = "BOOL")]
    pub right_to_left: Option<bool>,

    /// Whether to hide the grid's lines.
    #[arg(long, value_name = "BOOL")]
    pub hide_gridlines: Option<bool>,

    #[command(flatten)]
    pub write: StructureWriteArgs,
}

/// Sheets' auto-recalculation intervals, from `--auto-recalc`.
///
/// A CLI-facing copy for the same reason [`ShiftArg`] mirrors
/// `ShiftDimension`: the pure engine module stays free of `clap`. Excludes
/// `RECALCULATION_INTERVAL_UNSPECIFIED` — Sheets' way of saying the field
/// was never set, never a value a caller would deliberately choose.
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
pub enum AutoRecalcArg {
    /// Recalculate on every edit (Sheets' own default).
    OnChange,
    /// Recalculate at most once a minute.
    Minute,
    /// Recalculate at most once an hour.
    Hour,
}

impl From<AutoRecalcArg> for crate::drive::sheets::types::RecalculationInterval {
    fn from(arg: AutoRecalcArg) -> Self {
        match arg {
            AutoRecalcArg::OnChange => Self::OnChange,
            AutoRecalcArg::Minute => Self::Minute,
            AutoRecalcArg::Hour => Self::Hour,
        }
    }
}

/// Whether `--iterative-calculation` turns iterative calculation on or off.
///
/// A CLI-facing copy of [`IterativeCalculationToggle`] for the same reason
/// [`ShiftArg`] mirrors `ShiftDimension`.
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
pub enum IterativeCalculationArg {
    /// Turn iterative calculation on (or update its settings).
    On,
    /// Turn iterative calculation off.
    Off,
}

impl From<IterativeCalculationArg> for IterativeCalculationToggle {
    fn from(arg: IterativeCalculationArg) -> Self {
        match arg {
            IterativeCalculationArg::On => Self::On,
            IterativeCalculationArg::Off => Self::Off,
        }
    }
}

/// Changes workbook-level properties: locale, time zone, automatic
/// recalculation, and iterative calculation (issue #1836).
///
/// Deliberately omits `spreadsheetTheme` — a large nested type (font family
/// plus a full color palette) left for a future issue, matching this
/// crate's established pattern of shipping a documented subset. At least one
/// of `--locale`/`--time-zone`/`--auto-recalc`/`--iterative-calculation` is
/// required; `--iterative-calculation-max-iterations`/
/// `--iterative-calculation-convergence-threshold` are only valid alongside
/// `--iterative-calculation on` — both checked by the engine so a `--dry-run`
/// reports the same refusal a real run would
/// (`structure.rs::validate_verb_args`).
#[derive(Parser)]
pub struct UpdateWorkbookPropertiesCommand {
    #[command(flatten)]
    pub target: SpreadsheetIdArg,

    /// The workbook's new locale, e.g. `en_US`. Omitted leaves it unchanged.
    #[arg(long, value_name = "LOCALE")]
    pub locale: Option<String>,

    /// The workbook's new IANA time zone, e.g. `America/New_York`. Omitted
    /// leaves it unchanged.
    #[arg(long, value_name = "TIME_ZONE")]
    pub time_zone: Option<String>,

    /// The workbook's new automatic-recalculation interval. Omitted leaves
    /// it unchanged.
    #[arg(long, value_enum, value_name = "INTERVAL")]
    pub auto_recalc: Option<AutoRecalcArg>,

    /// Turns iterative calculation on or off. Omitted leaves it unchanged.
    #[arg(long, value_enum, value_name = "ON_OFF")]
    pub iterative_calculation: Option<IterativeCalculationArg>,

    /// Maximum calculation rounds per recalculation. Only valid alongside
    /// `--iterative-calculation on`; omitted takes Sheets' own default.
    #[arg(long, value_name = "N")]
    pub iterative_calculation_max_iterations: Option<i64>,

    /// The maximum change between two consecutive rounds that still counts
    /// as converged. Only valid alongside `--iterative-calculation on`;
    /// omitted takes Sheets' own default.
    #[arg(long, value_name = "THRESHOLD")]
    pub iterative_calculation_convergence_threshold: Option<f64>,

    #[command(flatten)]
    pub write: StructureWriteArgs,
}

impl AddSheetCommand {
    /// Runs the command against the shared Drive client.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        run_verb(
            client,
            self.target.spreadsheet_id,
            StructureVerb::AddSheet {
                title: self.title,
                index: self.index,
                rows: self.rows,
                columns: self.columns,
            },
            self.write,
        )
        .await
    }
}

impl RenameSheetCommand {
    /// Runs the command against the shared Drive client.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        run_verb(
            client,
            self.target.spreadsheet_id,
            StructureVerb::RenameSheet {
                sheet: self.sheet,
                new_title: self.title,
            },
            self.write,
        )
        .await
    }
}

impl InsertRowsCommand {
    /// Runs the command against the shared Drive client.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        run_verb(
            client,
            self.target.spreadsheet_id,
            StructureVerb::InsertRows {
                sheet: self.sheet,
                at: self.at,
                count: self.count,
            },
            self.write,
        )
        .await
    }
}

impl InsertColumnsCommand {
    /// Runs the command against the shared Drive client.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        run_verb(
            client,
            self.target.spreadsheet_id,
            StructureVerb::InsertColumns {
                sheet: self.sheet,
                at: self.at,
                count: self.count,
            },
            self.write,
        )
        .await
    }
}

impl MoveRowsCommand {
    /// Runs the command against the shared Drive client.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        run_verb(
            client,
            self.target.spreadsheet_id,
            StructureVerb::MoveRows {
                sheet: self.sheet,
                at: self.at,
                count: self.count,
                before: self.before,
            },
            self.write,
        )
        .await
    }
}

impl MoveColumnsCommand {
    /// Runs the command against the shared Drive client.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        run_verb(
            client,
            self.target.spreadsheet_id,
            StructureVerb::MoveColumns {
                sheet: self.sheet,
                at: self.at,
                count: self.count,
                before: self.before,
            },
            self.write,
        )
        .await
    }
}

impl DeleteSheetCommand {
    /// Runs the command against the shared Drive client.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        run_verb(
            client,
            self.target.spreadsheet_id,
            StructureVerb::DeleteSheet { sheet: self.sheet },
            self.write,
        )
        .await
    }
}

impl DeleteRowsCommand {
    /// Runs the command against the shared Drive client.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        run_verb(
            client,
            self.target.spreadsheet_id,
            StructureVerb::DeleteRows {
                sheet: self.sheet,
                at: self.at,
                count: self.count,
            },
            self.write,
        )
        .await
    }
}

impl DeleteColumnsCommand {
    /// Runs the command against the shared Drive client.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        run_verb(
            client,
            self.target.spreadsheet_id,
            StructureVerb::DeleteColumns {
                sheet: self.sheet,
                at: self.at,
                count: self.count,
            },
            self.write,
        )
        .await
    }
}

impl InsertRangeCommand {
    /// Runs the command against the shared Drive client.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        run_verb(
            client,
            self.target.spreadsheet_id,
            StructureVerb::InsertRange {
                sheet: self.sheet,
                start_row: self.range.start_row,
                end_row: self.range.end_row,
                start_column: self.range.start_column,
                end_column: self.range.end_column,
                shift: self.range.shift.into(),
            },
            self.write,
        )
        .await
    }
}

impl DeleteRangeCommand {
    /// Runs the command against the shared Drive client.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        run_verb(
            client,
            self.target.spreadsheet_id,
            StructureVerb::DeleteRange {
                sheet: self.sheet,
                start_row: self.range.start_row,
                end_row: self.range.end_row,
                start_column: self.range.start_column,
                end_column: self.range.end_column,
                shift: self.range.shift.into(),
            },
            self.write,
        )
        .await
    }
}

impl DuplicateSheetCommand {
    /// Runs the command against the shared Drive client.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        run_verb(
            client,
            self.target.spreadsheet_id,
            StructureVerb::DuplicateSheet {
                sheet: self.sheet,
                title: self.title,
                index: self.index,
            },
            self.write,
        )
        .await
    }
}

impl ReorderSheetCommand {
    /// Runs the command against the shared Drive client.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        run_verb(
            client,
            self.target.spreadsheet_id,
            StructureVerb::ReorderSheet {
                sheet: self.sheet,
                index: self.index,
            },
            self.write,
        )
        .await
    }
}

impl HideSheetCommand {
    /// Runs the command against the shared Drive client.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        run_verb(
            client,
            self.target.spreadsheet_id,
            StructureVerb::SetSheetVisibility {
                sheet: self.sheet,
                hidden: true,
            },
            self.write,
        )
        .await
    }
}

impl ShowSheetCommand {
    /// Runs the command against the shared Drive client.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        run_verb(
            client,
            self.target.spreadsheet_id,
            StructureVerb::SetSheetVisibility {
                sheet: self.sheet,
                hidden: false,
            },
            self.write,
        )
        .await
    }
}

impl UpdateSheetPropertiesCommand {
    /// Runs the command against the shared Drive client.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        run_verb(
            client,
            self.target.spreadsheet_id,
            StructureVerb::UpdateSheetProperties {
                sheet: self.sheet,
                freeze_rows: self.freeze_rows,
                freeze_columns: self.freeze_columns,
                tab_color: self.tab_color,
                clear_tab_color: self.clear_tab_color,
                right_to_left: self.right_to_left,
                hide_gridlines: self.hide_gridlines,
            },
            self.write,
        )
        .await
    }
}

impl UpdateWorkbookPropertiesCommand {
    /// Runs the command against the shared Drive client.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        run_verb(
            client,
            self.target.spreadsheet_id,
            StructureVerb::UpdateWorkbookProperties {
                locale: self.locale,
                time_zone: self.time_zone,
                auto_recalc: self.auto_recalc.map(Into::into),
                iterative_calculation: self.iterative_calculation.map(Into::into),
                iterative_calculation_max_iterations: self.iterative_calculation_max_iterations,
                iterative_calculation_convergence_threshold: self
                    .iterative_calculation_convergence_threshold,
            },
            self.write,
        )
        .await
    }
}

/// Builds `StructureOptions` from a resolved verb and the shared write
/// trio, then runs it. Every `execute()` above becomes a single expression
/// constructing its verb and delegating here.
async fn run_verb(
    client: &DriveClient,
    spreadsheet_id: String,
    verb: StructureVerb,
    write: StructureWriteArgs,
) -> Result<()> {
    let opts = StructureOptions {
        spreadsheet_id,
        verb,
        dry_run: write.dry_run,
        lease_token: write.lease.lease,
        ledger_path: helpers::resolve_ledger_path(write.dry_run)?,
    };
    run_structure(client, &opts, &write.output).await
}

/// Shared tail for every structural verb: derive the Sheets client, load the
/// account's rules, run the engine, render.
///
/// The CLI layer deliberately does no gating and no logging — both live in
/// the engine, so a future MCP caller gets them by construction.
async fn run_structure(
    client: &DriveClient,
    opts: &StructureOptions,
    output: &OutputFormat,
) -> Result<()> {
    let sheets = SheetsClient::from_drive_client(client)?;
    let rules = helpers::active_account_rules()?;
    let outcome = structure(client, &sheets, opts, &rules).await;
    if output_as(&outcome, output)? {
        return Ok(());
    }
    println!("{}", sanitize_rendered(&describe_lines(&outcome)));
    Ok(())
}

/// Strips terminal control sequences from a rendered outcome, then joins it,
/// as `sheets write` and `sheets create` do to theirs.
///
/// Every line interpolates a Drive-supplied file name, sheet titles read out
/// of the workbook (including the whole `available` list on a not-found
/// refusal) and raw API error details, so it is exactly as untrusted as
/// theirs.
///
/// The one difference from the siblings is that this takes the **lines**
/// rather than a finished string. Their rendered form is a single line
/// containing no control character of its own, so filtering it whole is
/// equivalent to filtering each interpolation. A structural insert preview
/// is deliberately two lines — the second is the shift, and it is the
/// substance of the dry run (ADR-0075 §6) — so filtering the joined string
/// would eat the separator along with the escapes it is there to remove,
/// while filtering per line after joining could not tell that separator from
/// a newline that arrived inside a sheet title. Taking the parts and
/// supplying the separators here removes the ambiguity rather than
/// documenting it: every newline in the output is one this function wrote,
/// and every newline in the input is stripped as the control character it is.
fn sanitize_rendered(lines: &[String]) -> String {
    lines
        .iter()
        .map(|line| sanitize_for_terminal(line))
        .collect::<Vec<_>>()
        .join("\n")
}

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

    fn line(s: &str) -> Vec<String> {
        vec![s.to_string()]
    }

    #[test]
    fn add_sheet_still_parses_spreadsheet_id_positionally() {
        let cmd =
            AddSheetCommand::try_parse_from(["add-sheet", "abc123", "--title", "Sheet2"]).unwrap();
        assert_eq!(cmd.target.spreadsheet_id, "abc123");

        let err = AddSheetCommand::try_parse_from(["add-sheet", "--title", "Sheet2"])
            .map(|_| ())
            .unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::MissingRequiredArgument);
    }

    #[test]
    fn rename_sheet_still_parses_spreadsheet_id_positionally() {
        let cmd = RenameSheetCommand::try_parse_from([
            "rename-sheet",
            "abc123",
            "--sheet",
            "Sheet1",
            "--title",
            "Sheet2",
        ])
        .unwrap();
        assert_eq!(cmd.target.spreadsheet_id, "abc123");

        let err = RenameSheetCommand::try_parse_from([
            "rename-sheet",
            "--sheet",
            "Sheet1",
            "--title",
            "Sheet2",
        ])
        .map(|_| ())
        .unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::MissingRequiredArgument);
    }

    #[test]
    fn update_sheet_properties_still_parses_spreadsheet_id_positionally() {
        let cmd = UpdateSheetPropertiesCommand::try_parse_from([
            "update-sheet-properties",
            "abc123",
            "--sheet",
            "Sheet1",
            "--freeze-rows",
            "1",
        ])
        .unwrap();
        assert_eq!(cmd.target.spreadsheet_id, "abc123");

        let err = UpdateSheetPropertiesCommand::try_parse_from([
            "update-sheet-properties",
            "--sheet",
            "Sheet1",
            "--freeze-rows",
            "1",
        ])
        .map(|_| ())
        .unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::MissingRequiredArgument);
    }

    #[test]
    fn shift_arg_maps_onto_the_engine_dimension() {
        assert_eq!(
            crate::drive::sheets::types::ShiftDimension::from(ShiftArg::Rows),
            crate::drive::sheets::types::ShiftDimension::Rows
        );
        assert_eq!(
            crate::drive::sheets::types::ShiftDimension::from(ShiftArg::Columns),
            crate::drive::sheets::types::ShiftDimension::Columns
        );
    }

    #[test]
    fn auto_recalc_arg_maps_onto_the_engine_interval() {
        use crate::drive::sheets::types::RecalculationInterval;
        assert_eq!(
            RecalculationInterval::from(AutoRecalcArg::OnChange),
            RecalculationInterval::OnChange
        );
        assert_eq!(
            RecalculationInterval::from(AutoRecalcArg::Minute),
            RecalculationInterval::Minute
        );
        assert_eq!(
            RecalculationInterval::from(AutoRecalcArg::Hour),
            RecalculationInterval::Hour
        );
    }

    #[test]
    fn iterative_calculation_arg_maps_onto_the_engine_toggle() {
        assert_eq!(
            IterativeCalculationToggle::from(IterativeCalculationArg::On),
            IterativeCalculationToggle::On
        );
        assert_eq!(
            IterativeCalculationToggle::from(IterativeCalculationArg::Off),
            IterativeCalculationToggle::Off
        );
    }

    #[test]
    fn sanitize_rendered_strips_escapes_from_an_injected_sheet_title() {
        let clean = sanitize_rendered(&line(
            "Refused: 'Budget' has no sheet titled 'Q9'. Available: '\u{1b}[31mQ1\u{7}'",
        ));
        assert!(!clean.contains('\u{1b}'), "{clean}");
        assert!(!clean.contains('\u{7}'), "{clean}");
        assert!(clean.contains("Available: '[31mQ1'"), "{clean}");
    }

    #[test]
    fn sanitize_rendered_keeps_the_inserts_own_second_line() {
        // The separator between these two is supplied here rather than
        // carried in the text: the shift is the substance of a structural dry
        // run, and a whole-string filter would eat the newline joining them.
        let clean = sanitize_rendered(&[
            "Would insert 3 row(s) before row 5 of 'Q2' in 'Budget'".to_string(),
            "  (500 rows -> 503; existing rows 5-500 shift down)".to_string(),
        ]);
        assert_eq!(clean.lines().count(), 2, "{clean}");
        assert!(clean.contains("500 rows -> 503"), "{clean}");
    }

    #[test]
    fn a_newline_inside_a_line_cannot_forge_a_second_line() {
        // The residual the line-list signature exists to remove: a sheet
        // title (or Drive file name) carrying a newline plus a plausible
        // shift line must not be able to add one to a single-line preview.
        let clean = sanitize_rendered(&line(
            "Would rename sheet 'Q2\n  (500 rows -> 500; nothing shifts)' to 'Q3' in 'Budget'",
        ));
        assert_eq!(clean.lines().count(), 1, "{clean}");
        assert!(!clean.contains('\n'), "{clean}");
    }

    #[test]
    fn sanitize_rendered_strips_bidi_overrides() {
        let clean = sanitize_rendered(&line("Renamed sheet 'a\u{202E}b' to 'c' in 'Budget'"));
        assert!(!clean.contains('\u{202E}'), "{clean}");
    }
}