djogi-cli 0.1.0-alpha.7

CLI for the Djogi framework — migrations, shell, db reset, status
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
//! Djogi CLI library — entry points for the `djogi` binary and for
//! adopter-linked binaries that inject their own [`DescriptorProvider`].
//!
//! The published standalone `djogi` binary links no adopter model crates,
//! so reading the global `inventory` registry directly yields zero adopter
//! models. Injecting a [`DescriptorProvider`] lets an adopter-linked binary
//! supply its own models. See [`run_with_provider`].

use std::path::PathBuf;
use std::process::ExitCode;

use clap::{Parser, Subcommand};

mod analyze;
mod db;
mod live;
mod migrations;
mod schema;
mod verify;

// Re-export CLI types so the thin `main.rs` shim and downstream crates
// can reference them without duplicating definitions.
#[allow(ambiguous_glob_reexports)]
pub use crate::analyze::*;
pub use crate::db::*;
pub use crate::live::*;
pub use crate::migrations::*;
pub use crate::schema::*;
pub use crate::verify::*;

// Re-export proc macros so adopters write `djogi_cli::djogi_main!(…)` and
// `djogi_cli::link_anchor!()` instead of depending on `djogi-macros` directly.
// `link_anchor!` takes no arguments — it is a per-crate marker placed once in
// each model crate's `lib.rs`.
pub use djogi_macros::{djogi_main, link_anchor};

// Re-export the boundary types so adopters/tests can name them without a
// direct `djogi` dependency line.
pub use djogi::migrate::{DescriptorProvider, InventoryDescriptorProvider};

/// Print a support-boundary preflight error to stderr.
///
/// Used by every CLI entry point that runs `check_postgres_version`.
/// The "support boundary" prefix distinguishes infrastructure refusals
/// (wrong PG version, missing extension) from policy refusals (localhost
/// gate, production profile) and runtime failures (SQL error, network).
pub fn print_support_boundary_error(subcommand: &str, err: &dyn std::fmt::Display) {
    eprintln!("djogi {subcommand}: support boundary: {err}");
}

#[derive(Parser)]
#[command(name = "djogi", about = "Djogi framework CLI")]
pub struct Cli {
    #[command(subcommand)]
    pub command: TopCommand,
}

#[derive(Subcommand)]
pub enum TopCommand {
    /// Launch interactive Rhai shell.
    Shell,
    /// Database management.
    Db {
        #[command(subcommand)]
        command: DbCommand,
    },
    /// Schema migration tooling (Phase 7).
    Migrations {
        #[command(subcommand)]
        command: MigrationsCommand,
    },
    /// Compatibility alias for `djogi migrations`. See
    /// `djogi migrations --help` for the full command tree.
    /// Currently only `apply` is supported as an alias:
    /// `djogi migrate apply` delegates to `djogi migrations apply`.
    Migrate {
        #[command(subcommand)]
        command: MigrateCommand,
    },
    /// Phase 7.5 live-migration operator surface — drives expand →
    /// backfill → flip → contract sequences for `ExpandContract`-
    /// classified deltas.
    ///
    /// Requires PostgreSQL 18 or later.
    Live {
        #[command(subcommand)]
        command: live::LiveCmd,
    },
    /// Render Markdown documentation from the descriptor inventory.
    ///
    /// One file per registered model under `<output>/<app>/`, plus a
    /// top-level `README.md` index. Output is byte-deterministic
    /// against the same descriptor set.
    Docs {
        /// Output directory. Defaults to
        /// `<workspace>/target/djogi-docs/`.
        #[arg(long)]
        output: Option<PathBuf>,
        /// Workspace root override. Defaults to the current working
        /// directory.
        #[arg(long)]
        workspace: Option<PathBuf>,
    },
    /// Cluster 8ε T9.6 — read-only HMAC cross-check of every
    /// `migrations/<target>/<app>/schema_snapshot.json` against the
    /// audit DB's `djogi_ddl_audit` ledger.
    ///
    /// Requires PostgreSQL 18 or later — exits with code 2 if the
    /// server is below the minimum.
    ///
    /// Exit codes: `0` when every snapshot reports `OK` or `Skipped`
    /// (audit table absent or no audit row yet), `1` on any mismatch
    /// or runtime error (config / connect / I/O / key decode).
    ///
    /// **Read-only.** Verify never issues `INSERT`, `UPDATE`,
    /// `DELETE`, or DDL — the only SQL leaving the CLI is a
    /// positional-bind `SELECT` against `djogi_ddl_audit`.
    Verify {
        /// Workspace root override. Defaults to the current working
        /// directory.
        #[arg(long)]
        workspace: Option<PathBuf>,
    },
    /// Cluster 8ζ T12.2 — JSON descriptor dump.
    ///
    /// Emits a deterministic JSON document covering every model
    /// registered via `inventory::submit!`. Use for agent
    /// integration, CI assertions on schema drift, and
    /// machine-readable handoffs to downstream codegen.
    ///
    /// **Read-only.** Schema never opens a Postgres connection;
    /// the inventory walk is fully in-process.
    Schema {
        /// Output format. `json` is the only value in v0.1.0;
        /// `openapi` and `markdown` are reserved for Phase 9.
        #[arg(long, value_enum, default_value_t = SchemaFormat::Json)]
        format: SchemaFormat,
        /// Optional output file. Absent means stdout.
        #[arg(long)]
        output: Option<PathBuf>,
    },
    /// Cluster 8ε T10 — partition / vacuum analysis for adopter
    /// Postgres tables. Queries `pg_stat_user_tables` (and, when
    /// installed, `pg_partman`) and recommends vacuum / partition
    /// actions per the precedence laid out in [`analyze::Recommendation`].
    ///
    /// Requires PostgreSQL 18 or later — exits with code 2 if the
    /// server is below the minimum.
    ///
    /// **Read-only.** Analyze issues only `SELECT` against system
    /// catalogues; it never writes.
    Analyze {
        /// Output format. `human` (default) prints one line per table;
        /// `json` emits a deterministic, sorted array of
        /// `{table, recommendation}` objects suitable for CI
        /// dashboards.
        #[arg(long, value_enum, default_value_t = AnalyzeFormat::Human)]
        format: AnalyzeFormat,
        /// Dead-tuple ratio strictly above which `VacuumNeeded` fires.
        /// Default `0.2` (20% bloat) — typical OLTP workloads tighten
        /// this; warehouse workloads tend to leave it as-is. Validated
        /// at parse time via [`parse_threshold_vacuum`]: rejects NaN /
        /// infinity / values outside `[0.0, 1.0]` so silent
        /// "never-fires" misconfigurations are impossible.
        #[arg(long, default_value_t = 0.2, value_parser = parse_threshold_vacuum)]
        threshold_vacuum: f64,
        /// Live row count strictly above which an unpartitioned table
        /// triggers `PartitionRecommended`. Default `10_000_000`. The
        /// same threshold drives the per-partition row average that
        /// fires `PartitionCountIncrease`.
        #[arg(long, default_value_t = 10_000_000)]
        threshold_partition_rows: i64,
        /// Workspace root override. Defaults to the current working
        /// directory. Mirrors `djogi verify --workspace`.
        #[arg(long)]
        workspace: Option<PathBuf>,
    },
}

/// Output format for `djogi schema`. Mirrors
/// [`schema::SchemaFormat`] so `clap::ValueEnum` lives at the CLI
/// boundary and the `schema` module stays clap-free.
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
pub enum SchemaFormat {
    Json,
}

impl SchemaFormat {
    fn into_schema(self) -> schema::SchemaFormat {
        match self {
            SchemaFormat::Json => schema::SchemaFormat::Json,
        }
    }
}

/// Output format for `djogi analyze` — clap-side mirror of
/// [`analyze::AnalyzeFormat`].
///
/// This enum exists only so `clap::ValueEnum` can derive the
/// `--format human|json` parser without dragging the clap-derive
/// dependency into the `analyze` module's pure-substrate header.
/// Conversion to the canonical [`analyze::AnalyzeFormat`] happens at
/// the dispatch site via [`Self::into_analyze`].
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
pub enum AnalyzeFormat {
    Human,
    Json,
}

impl AnalyzeFormat {
    /// Project the clap-side enum onto the canonical
    /// [`analyze::AnalyzeFormat`] consumed by [`analyze::run`].
    fn into_analyze(self) -> analyze::AnalyzeFormat {
        match self {
            AnalyzeFormat::Human => analyze::AnalyzeFormat::Human,
            AnalyzeFormat::Json => analyze::AnalyzeFormat::Json,
        }
    }
}

/// Parse + validate `--threshold-vacuum` at the CLI boundary.
///
/// Rejects three classes of nonsense input that plain `f64::parse`
/// otherwise lets through:
///
/// 1. **Non-finite values** (`NaN`, `inf`, `-inf`). Without this guard,
///    `ratio > NaN` evaluates to `false` for every ratio, so
///    `VacuumNeeded` would silently never fire — the worst kind of
///    silent failure for a recommendation engine.
/// 2. **Negative values.** A dead-tuple ratio is bounded in `[0.0, 1.0]`
///    by definition (it's `dead / (live + dead)`), so a negative
///    threshold is operator error, not a tuning choice.
/// 3. **Values above `1.0`.** Same reasoning — no real
///    `pg_stat_user_tables` row can produce a ratio above `1.0`, so a
///    threshold above `1.0` would mean "VacuumNeeded never fires," which
///    is again silent failure rather than legitimate configuration.
///
/// Wired via clap's `value_parser` attribute so the rejection happens at
/// argument-parsing time — operators see a clear error message and a
/// non-zero exit, never a silently-misbehaving analyze run.
fn parse_threshold_vacuum(s: &str) -> Result<f64, String> {
    let v: f64 = s
        .parse()
        .map_err(|e: std::num::ParseFloatError| e.to_string())?;
    if !v.is_finite() {
        return Err(format!("threshold_vacuum must be finite (got {s})"));
    }
    if !(0.0..=1.0).contains(&v) {
        return Err(format!("threshold_vacuum must be in [0.0, 1.0] (got {v})"));
    }
    Ok(v)
}

#[derive(Subcommand)]
pub enum DbCommand {
    /// Drop, recreate, and replay every committed migration against
    /// the application database. **Triple-gated** — refuses unless
    /// (a) `DATABASE_URL` resolves to localhost, (b)
    /// `Djogi.toml::profile != "production"`, and (c) explicit
    /// confirmation is supplied via `--yes` or the interactive
    /// prompt. Logging databases (`crud_log`, `event_log`) are NOT
    /// touched.
    ///
    /// Requires PostgreSQL 18 or later — exits with code 2 if the
    /// server is below the minimum.
    ///
    /// Exit codes: 0 on success, 1 on error (config / network / SQL
    /// / replay), 2 on gate refusal (not localhost, production
    /// profile, missing `--yes`, below PG 18).
    Reset {
        /// Skip the interactive y/N prompt and proceed. Required for
        /// non-interactive invocations (e.g. CI integration suites
        /// that call `db reset` between tests).
        #[arg(long, default_value_t = false)]
        yes: bool,
        /// Permit `db reset` to continue even when the live ledger's
        /// checksums no longer match the current on-disk migration
        /// files. Without this flag, checksum drift refuses before
        /// the destructive drop / recreate step.
        #[arg(long, default_value_t = false)]
        allow_checksum_drift_reset: bool,
        /// Maintenance database to connect to for the `DROP DATABASE`
        /// then `CREATE DATABASE` round-trip. Defaults to `postgres`,
        /// the conventional administrative DB present on every
        /// cluster. Override only if the cluster has a different
        /// administrative DB (e.g. AWS RDS uses `rdsadmin`).
        #[arg(long, default_value = "postgres")]
        maintenance_database: String,
        /// Workspace root override.
        #[arg(long)]
        workspace: Option<PathBuf>,
    },
    /// Run operator-authored SQL seed files in `seeds/<database>/`.
    /// Idempotent — re-runs skip seeds whose `V1:<sha256>` checksum
    /// matches the `djogi_seed_runs` ledger; refuses on checksum
    /// drift. Localhost-gated by default.
    ///
    /// Requires PostgreSQL 18 or later — exits with code 2 if the
    /// server is below the minimum.
    ///
    /// `--database <name>` selects BOTH the seed directory and the
    /// connection target. The CLI splices `<name>` into
    /// `database.url`'s path component so seeds always land on the
    /// matching DB; a malformed application URL refuses with exit
    /// code 1.
    ///
    /// Exit codes: 0 on success, 1 on error (config / network / SQL
    /// / checksum drift / malformed URL), 2 on gate refusal
    /// (non-localhost without `--allow-non-localhost`, below PG 18).
    Seed {
        /// Database name whose seeds directory should be run. The
        /// runner walks `seeds/<database>/*.sql` in alphabetical
        /// order.
        #[arg(long, default_value = "main")]
        database: String,
        /// Allow seeds to run against a non-localhost database. The
        /// gate is lighter than `db reset`'s — useful for CI
        /// integration suites seeding a remote test database.
        #[arg(long, default_value_t = false)]
        allow_non_localhost: bool,
        /// Workspace root override.
        #[arg(long)]
        workspace: Option<PathBuf>,
    },
    /// Drop orphaned `djogi_test_<uuid>` databases left over from
    /// crashed `#[djogi_test]` runs (SIGKILL / OOM / panic-after-spawn
    /// before teardown could fire). Triple-gated identical to
    /// `db reset` — localhost (override via `--allow-non-localhost`),
    /// non-production profile, explicit `--yes` (waived under
    /// `--dry-run`).
    ///
    /// Requires PostgreSQL 18 or later — exits with code 2 if the
    /// server is below the minimum.
    ///
    /// Exit codes: 0 on success, 1 on error (config / connect / SQL),
    /// 2 on gate refusal (non-localhost, production profile, missing
    /// `--yes` without `--dry-run`, below PG 18).
    CleanupTestDbs {
        /// List candidates without dropping. Skips the `--yes`
        /// confirmation gate because no destructive side effect
        /// occurs.
        #[arg(long, default_value_t = false)]
        dry_run: bool,
        /// Skip the `--yes` confirmation gate. Required for
        /// non-interactive invocations unless `--dry-run` is also set.
        #[arg(long, default_value_t = false)]
        yes: bool,
        /// Maintenance database to connect to. Defaults to `postgres`,
        /// the conventional administrative DB on every cluster.
        /// Override only when the cluster uses a different admin DB
        /// (e.g. AWS RDS uses `rdsadmin`).
        #[arg(long, default_value = "postgres")]
        maintenance_database: String,
        /// Allow cleanup against a non-localhost cluster. Off by
        /// default — the gate matches `db reset`'s localhost
        /// requirement so destructive ops stay local unless the
        /// operator explicitly opts out.
        #[arg(long, default_value_t = false)]
        allow_non_localhost: bool,
        /// Workspace root override.
        #[arg(long)]
        workspace: Option<PathBuf>,
    },
}

#[derive(Subcommand)]
pub enum MigrateCommand {
    /// Alias for `djogi migrations apply`. See
    /// `djogi migrations apply --help` for full documentation.
    ///
    /// Record pending migrations as applied in the ledger, optionally
    /// without executing their SQL (`--fake`).
    ///
    /// See `djogi migrations apply --help` for crash-recovery behavior,
    /// including already-faked reruns and snapshot rebuilds.
    Apply {
        #[arg(long)]
        workspace: Option<PathBuf>,

        #[arg(long, default_value_t = false)]
        fake: bool,

        #[arg(long)]
        reason: Option<String>,
    },
}

#[derive(Subcommand)]
pub enum MigrationsCommand {
    /// Compose a new migration from descriptor inventory + last
    /// snapshot.
    Compose {
        /// Operator-facing migration name. Sanitised down to a strict
        /// identifier; defaults to `migration` when empty.
        #[arg(long, default_value = "")]
        name: String,
        /// Allow destructive (drop) operations or tombstoned-app
        /// migrations. Without this flag the compose path refuses
        /// destructive deltas with a structural error.
        #[arg(long, default_value_t = false)]
        allow_destructive: bool,
        /// Discard hand-edits to existing migration files. Without
        /// this flag compose refuses to overwrite any up or down
        /// migration file whose current bytes do NOT match what the
        /// deterministic emitter would freshly produce — the
        /// byte-equality check stands in for a checksum compare
        /// because the emitter is deterministic (same inputs always
        /// produce the same bytes). The check is purely byte-level;
        /// it does not read the pending JSON's `checksum_up` field.
        #[arg(long, default_value_t = false)]
        force_overwrite: bool,
        /// Workspace root override. Defaults to the current working
        /// directory.
        #[arg(long)]
        workspace: Option<PathBuf>,
    },
    /// Print the current state of the migration ledger, grouped by
    /// app. Read-only — does not acquire the workspace lock.
    ///
    /// Requires PostgreSQL 18 or later.
    Status {
        /// Workspace root override (only used when reading
        /// `Djogi.toml`).
        #[arg(long)]
        workspace: Option<PathBuf>,
    },
    /// Compare live database catalog against the schema snapshot.
    /// Read-only — does not acquire the workspace lock or execute DDL.
    ///
    /// Exits 0 if no error-level diagnostics are found. Exits 1 on
    /// runtime errors (config / pool / SQL). Exits 2 if the Postgres
    /// server is below version 18.
    ///
    /// Use `--strict` to upgrade out-of-order migration warnings (D622)
    /// to errors, causing verify to exit non-zero when the ledger
    /// contains out-of-order applied rows.
    Verify {
        /// Workspace root override (only used when reading `Djogi.toml`).
        #[arg(long)]
        workspace: Option<PathBuf>,
        /// Upgrade D622 out-of-order diagnostics from Warning to Error.
        #[arg(long, default_value_t = false)]
        strict: bool,
    },
    /// Reconcile local migration history with the ledger. Default
    /// mode is a read-only diff between the on-disk SQL files and
    /// the ledger. Attune is read-only by default — pass `--apply`
    /// to commit ledger inserts / squash / parent-pointer writes.
    /// `--record` updates the parent repo's recorded submodule
    /// pointer to the resolved Git target after successful
    /// attunement. `--squash --from <ver>` collapses local history
    /// into a single migration (localhost + dev_mode + dev profile +
    /// DJOGI_ENV gates).
    ///
    /// Requires PostgreSQL 18 or later — exits with code 2 if the
    /// server is below the minimum.
    ///
    /// Exit codes: 0 on success, 1 on runtime error (config / network
    /// / SQL / git), 2 on refusal (gate failure, arg validation,
    /// below PG 18).
    Attune {
        /// Optional Git target to attune the local migration history
        /// to — a local or remote commit / tag / branch. When
        /// omitted, attune reconciles against the current on-disk
        /// state. Resolution: tries local first, then `git fetch
        /// --all` + retries on failure.
        target: Option<String>,
        /// Mutate the database / parent index. Without `--apply`,
        /// attune is a dry-run — it scans, prints the diff, and
        /// exits without inserting / deleting ledger rows or updating
        /// the parent submodule pointer (per
        /// `docs/spec/configuration.md` §14: "does not mutate the
        /// database unless `--apply` is explicitly passed").
        #[arg(long, default_value_t = false)]
        apply: bool,
        /// In Record mode (`--record-ledger`), insert ledger rows for
        /// SQL files present on disk but absent from the ledger. With
        /// a resolved `<target>` argument AND `--apply`, also update
        /// the parent repo's recorded submodule pointer to the target
        /// SHA.
        #[arg(long, default_value_t = false)]
        record: bool,
        /// Activate Record mode — insert ledger rows for SQL files
        /// present on disk but absent from the ledger. Distinct from
        /// `--record` (which controls the parent submodule pointer).
        /// Records the operator-supplied reason in `partial_apply_note`.
        /// Does NOT execute SQL.
        #[arg(
            long = "record-ledger",
            default_value_t = false,
            conflicts_with = "squash"
        )]
        record_ledger: bool,
        /// When `--record-ledger` is set, the rationale recorded on
        /// every inserted ledger row's `partial_apply_note`.
        #[arg(long, default_value = "operator asserted out-of-band apply")]
        record_reason: String,
        /// Coalesce every committed migration from `--from` to HEAD
        /// into a single squashed migration. HISTORY REWRITE — gated
        /// on localhost + dev profile + dev_mode + DJOGI_ENV.
        #[arg(long, default_value_t = false)]
        squash: bool,
        /// Inclusive starting version for `--squash` (e.g.
        /// `V20260101000000__init`).
        #[arg(long)]
        from: Option<String>,
        /// After a successful squash, push the rewritten
        /// `migrations/` submodule to its remote. Without this flag
        /// the rewrite stays local. Squash NEVER auto-publishes.
        #[arg(long, default_value_t = false)]
        publish: bool,
        /// Optional explicit app label to scope `--squash` to a
        /// single bucket. Required when `--from` matches a version in
        /// multiple buckets; auto-detected when the version is unique
        /// to one bucket.
        #[arg(long)]
        app: Option<String>,
        /// Workspace root override.
        #[arg(long)]
        workspace: Option<PathBuf>,
    },
    /// Apply all pending migrations in ledger order. This is the canonical spelling;
    /// `djogi migrate apply` is a compatibility alias.
    ///
    /// **Transaction semantics** are per-segment: transactional
    /// segments roll back on error; non-transactional segments
    /// autocommit and may leave partial progress.
    ///
    /// **On crash** or unexpected termination, re-run
    /// `djogi migrations apply`. For partial non-transactional
    /// progress, use `djogi migrations repair resume-partial`.
    ///
    /// **Existing-database adoption:** use `--fake` to mark pending
    /// migrations as applied without executing their SQL. This is for
    /// databases whose schema already exists (from a prior tool, manual
    /// DDL, or restored backup). Use `djogi migrations verify` or
    /// manual inspection to confirm the schema matches the target state
    /// before faking. The `--fake` flag respects the same out-of-order
    /// policy as real apply; if CI/prod policy is `Reject`, fake-apply
    /// on an out-of-order version is also rejected.
    ///
    /// For previewing pending work without executing it, use
    /// `djogi migrations status`.
    ///
    /// If the command is interrupted after recording a ledger row with
    /// a terminal status (`applied`, `faked`, `baseline`), re-running
    /// reports `VersionAlreadyApplied` (exit 2). For non-terminal
    /// statuses (`failed`, `rolled_back`), the stale row is removed and
    /// re-apply proceeds automatically. If the snapshot is missing or
    /// stale, reconcile it with `djogi migrations attune` or
    /// `repair snapshot-rebuild`.
    Apply {
        /// Workspace root override. Defaults to the current working
        /// directory.
        #[arg(long)]
        workspace: Option<PathBuf>,

        /// Record pending migrations as applied without executing
        /// their SQL. For existing-database adoption only. Requires
        /// `--reason`. Subject to the same out-of-order policy as real
        /// apply; if CI/prod policy is `Reject`, fake-apply on an
        /// out-of-order version is also rejected.
        #[arg(long, default_value_t = false)]
        fake: bool,

        /// Reason for faking these migrations. Required when `--fake`
        /// is set. Persisted to the ledger's audit trail so future
        /// inspections can understand why this version was recorded
        /// without SQL execution. Has no effect on normal (non-fake)
        /// apply.
        #[arg(long)]
        reason: Option<String>,
    },
    /// Operator-confirmed repair flows for ledger drift, partial
    /// applies, and missing snapshots. Every subcommand requires
    /// explicit confirmation — invoking the CLI subcommand IS the
    /// operator acknowledgment.
    Repair {
        /// The specific repair operation to perform.
        #[command(subcommand)]
        command: RepairSubcommand,
    },
    /// Project the live database schema into a baseline ledger row and
    /// snapshot. Use for existing databases being adopted under Djogi's
    /// migration ledger, where the schema already exists and compose +
    /// apply cannot run on a populated database without a starting point.
    ///
    /// Projects the live catalog into a single `baseline` ledger row
    /// (no SQL runs against user tables) and writes the projected
    /// snapshot so future migrations diff against the real DB state.
    /// Invoking the subcommand IS the operator acknowledgment.
    ///
    /// Requires PostgreSQL 18 or later — exits with code 2 if the
    /// server is below the minimum.
    ///
    /// Exit codes: 0 on success, 1 on runtime error (config / network /
    /// SQL / projection failure), 2 on refusal (empty `--reason`, duplicate
    /// version, unresolvable database URL, snapshot-persist failure after
    /// ledger insert, session-pinning correctness failure, or below PG 18).
    Baseline {
        /// Version label for the baseline ledger row (e.g.
        /// `V00000000000000__baseline`). Must be unique in the ledger.
        version: String,
        /// One-line description stored in the ledger row.
        #[arg(long, default_value = "existing database schema baseline")]
        description: String,
        /// Required non-empty reason recorded in the baseline note
        /// (audit trail entry).
        #[arg(long)]
        reason: String,
        /// App label for the migration bucket. Defaults to the global
        /// bucket (empty string) when not specified.
        #[arg(long)]
        app: Option<String>,
        /// Database name. Defaults to `main` if not specified.
        #[arg(long)]
        database: Option<String>,
        /// Workspace root override.
        #[arg(long)]
        workspace: Option<PathBuf>,
    },
}

/// `djogi migrations repair <subcommand>` — the four operator-confirmed
/// repair flows.
///
/// Each variant maps 1:1 onto a `djogi::migrate::repair::*` library
/// function. Invoking the subcommand IS the operator acknowledgment;
/// there is no separate `--confirm` flag. Every flow pins one Postgres
/// session, takes the per-bucket advisory lock, and holds the workspace
/// file lock for its duration.
///
/// Exit codes (shared across all four): `0` success, `1`
/// runtime/I/O error (retryable), `2` refusal or structural mismatch
/// (operator must intervene).
#[derive(Clone, Subcommand)]
pub enum RepairSubcommand {
    /// Update ledger checksum when migration file content changed
    /// but the row was already applied.
    ChecksumDrift {
        /// Migration version (e.g. `V20260101000000__add_users`).
        version: String,
        /// App label for the migration bucket. Defaults to the global
        /// bucket (empty string) when not specified.
        #[arg(long)]
        app: Option<String>,
        /// Database name. Defaults to `main` if not specified.
        #[arg(long)]
        database: Option<String>,
        /// New `checksum_up` value (SHA-256 hex). If omitted, computed
        /// from the committed up SQL file.
        #[arg(long)]
        checksum_up: Option<String>,
        /// New `checksum_down` value (SHA-256 hex). If omitted and
        /// down file exists, computed from committed down SQL file.
        /// Missing down file is a no-op; other read errors abort.
        #[arg(long)]
        checksum_down: Option<String>,
        /// Workspace root override.
        #[arg(long)]
        workspace: Option<PathBuf>,
    },

    /// Resolve a partial-apply row by rewriting its status to one of
    /// `rolled_back`, `faked`, or `applied`. Does NOT execute SQL.
    PartialApply {
        /// Migration version to repair.
        version: String,
        /// Resolution: `rolled-back`, `faked`, or `applied`.
        #[arg(value_enum)]
        resolution: PartialApplyResolutionCli,
        /// Operator note persisted in the ledger row's
        /// `partial_apply_note` column.
        #[arg(long, default_value = "operator resolved partial apply via CLI")]
        note: String,
        /// App label (empty string for global bucket).
        #[arg(long)]
        app: Option<String>,
        /// Database name. Defaults to `main` if not specified.
        #[arg(long)]
        database: Option<String>,
        /// Workspace root override.
        #[arg(long)]
        workspace: Option<PathBuf>,
    },

    /// Resume an interrupted non-transactional apply by re-loading
    /// the committed replay plan and executing remaining steps.
    ResumePartial {
        /// Migration version to resume.
        version: String,
        /// App label (empty string for global bucket).
        #[arg(long)]
        app: Option<String>,
        /// Database name. Defaults to `main` if not specified.
        #[arg(long)]
        database: Option<String>,
        /// Workspace root override.
        #[arg(long)]
        workspace: Option<PathBuf>,
    },

    /// Rebuild the schema snapshot for a bucket by walking the
    /// ledger and re-projecting from live database state.
    SnapshotRebuild {
        /// App label (empty string for global bucket).
        #[arg(long)]
        app: Option<String>,
        /// Database name. Defaults to `main` if not specified.
        #[arg(long)]
        database: Option<String>,
        /// Explicit snapshot path override. If omitted, derived from
        /// `migrations/<database>/<app>/schema_snapshot.json`.
        #[arg(long)]
        snapshot_path: Option<PathBuf>,
        /// Workspace root override.
        #[arg(long)]
        workspace: Option<PathBuf>,
    },
}

/// CLI-side mirror of [`djogi::migrate::PartialApplyResolution`] for the
/// `repair partial-apply` resolution argument.
///
/// This enum exists only so `clap::ValueEnum` can parse
/// `rolled-back | faked | applied` at the CLI boundary without the
/// library enum carrying a clap-derive dependency. Conversion to the
/// canonical [`djogi::migrate::PartialApplyResolution`] happens via the
/// `From` impl in the `migrations` module.
#[derive(clap::ValueEnum, Clone, Debug)]
pub enum PartialApplyResolutionCli {
    RolledBack,
    Faked,
    Applied,
}

// ── Entrypoints ───────────────────────────────────────────────────────────

/// Run the CLI by parsing arguments from `std::env::args_os()`.
///
/// This is the entry point used by the published standalone `djogi`
/// binary. It reads the global link-time [`inventory`] registry via
/// [`djogi::migrate::InventoryDescriptorProvider`].
pub fn run_from_env() -> ExitCode {
    let cli = match Cli::try_parse_from(std::env::args_os()) {
        Ok(c) => c,
        Err(e) => {
            let _ = e.print();
            return ExitCode::from(if e.use_stderr() { 2 } else { 0 });
        }
    };
    dispatch_command(
        &cli.command,
        &djogi::migrate::InventoryDescriptorProvider::new(),
    )
}

/// Run the CLI with an explicit argument iterable. Useful for testing and
/// embedding.
///
/// Accepts any `IntoIterator<Item = T>` where `T: Into<OsString> + Clone`,
/// matching the bound of [`clap::Parser::try_parse_from`]. In practice,
/// arrays of `&str` (e.g. `["djogi", "migrations", "compose"]`) and
/// `Vec<String>` both satisfy this bound.
///
/// Falls back to [`djogi::migrate::InventoryDescriptorProvider`] for
/// descriptors.
pub fn run_with_args<I, T>(args: I) -> ExitCode
where
    I: IntoIterator<Item = T>,
    T: Into<std::ffi::OsString> + Clone,
{
    let cli = match Cli::try_parse_from(args) {
        Ok(c) => c,
        Err(e) => {
            // Print the clap error / `--help` / `--version` text before
            // returning, matching `run_from_env`. Without this, parse
            // errors and `--help` would be silent.
            let _ = e.print();
            return ExitCode::from(if e.use_stderr() { 2 } else { 0 });
        }
    };
    dispatch_command(
        &cli.command,
        &djogi::migrate::InventoryDescriptorProvider::new(),
    )
}

/// Run the CLI with an explicit argument iterable and a [`DescriptorProvider`].
///
/// Accepts any `IntoIterator<Item = T>` where `T: Into<OsString> + Clone`,
/// matching the bound of [`clap::Parser::try_parse_from`].
///
/// Adopter-linked binaries pass their own provider so descriptor-dependent
/// commands (`compose`, `verify`, `schema`, `docs`) see the adopter's
/// models instead of an empty inventory.
pub fn run_with_provider<I, T>(
    args: I,
    provider: &dyn djogi::migrate::DescriptorProvider,
) -> ExitCode
where
    I: IntoIterator<Item = T>,
    T: Into<std::ffi::OsString> + Clone,
{
    let cli = match Cli::try_parse_from(args) {
        Ok(c) => c,
        Err(e) => {
            // Print the clap error / `--help` / `--version` text before
            // returning, matching `run_from_env`.
            let _ = e.print();
            return ExitCode::from(if e.use_stderr() { 2 } else { 0 });
        }
    };
    dispatch_command(&cli.command, provider)
}

// ── Dispatch ──────────────────────────────────────────────────────────────

fn dispatch_command(
    command: &TopCommand,
    provider: &dyn djogi::migrate::DescriptorProvider,
) -> ExitCode {
    match command {
        TopCommand::Shell => {
            eprintln!("djogi shell: not yet implemented");
            ExitCode::from(0)
        }
        TopCommand::Db { command } => match command {
            DbCommand::Reset {
                yes,
                allow_checksum_drift_reset,
                maintenance_database,
                workspace,
            } => db::reset_cmd(
                *yes,
                *allow_checksum_drift_reset,
                maintenance_database.clone(),
                workspace.clone(),
            ),
            DbCommand::Seed {
                database,
                allow_non_localhost,
                workspace,
            } => db::seed_cmd(database.clone(), *allow_non_localhost, workspace.clone()),
            DbCommand::CleanupTestDbs {
                dry_run,
                yes,
                maintenance_database,
                allow_non_localhost,
                workspace,
            } => db::cleanup_test_dbs_cmd(
                *dry_run,
                *yes,
                maintenance_database.clone(),
                *allow_non_localhost,
                workspace.clone(),
            ),
        },
        TopCommand::Docs { output, workspace } => {
            if provider.models().is_empty() {
                print_zero_descriptor_diagnostic("docs");
                return ExitCode::from(2);
            }
            db::docs_cmd(provider, output.clone(), workspace.clone())
        }
        TopCommand::Live { command } => live::dispatch(command.clone()),
        TopCommand::Verify { workspace } => {
            let runtime = match tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
            {
                Ok(r) => r,
                Err(e) => {
                    eprintln!("djogi verify: tokio runtime: {e}");
                    return ExitCode::from(1);
                }
            };
            match runtime.block_on(verify::run(workspace.clone())) {
                Ok(code) => code,
                Err(e) => {
                    eprintln!("djogi verify: {e}");
                    ExitCode::from(1)
                }
            }
        }
        TopCommand::Schema { format, output } => {
            let models: Vec<&'static djogi::descriptor::ModelDescriptor> = provider.models();
            if models.is_empty() {
                print_zero_descriptor_diagnostic("schema");
                return ExitCode::from(2);
            }
            match schema::run(format.into_schema(), &models, output.clone()) {
                Ok(()) => ExitCode::SUCCESS,
                Err(e) => {
                    eprintln!("djogi schema: {e}");
                    ExitCode::from(1)
                }
            }
        }
        TopCommand::Analyze {
            format,
            threshold_vacuum,
            threshold_partition_rows,
            workspace,
        } => {
            let runtime = match tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
            {
                Ok(r) => r,
                Err(e) => {
                    eprintln!("djogi analyze: tokio runtime: {e}");
                    return ExitCode::from(1);
                }
            };
            match runtime.block_on(analyze::run(
                workspace.clone(),
                format.into_analyze(),
                *threshold_vacuum,
                *threshold_partition_rows,
            )) {
                Ok(()) => ExitCode::SUCCESS,
                Err(e) => {
                    eprintln!("djogi analyze: {e}");
                    ExitCode::from(1)
                }
            }
        }
        TopCommand::Migrations { command } => match command {
            MigrationsCommand::Compose {
                name,
                allow_destructive,
                force_overwrite,
                workspace,
            } => {
                if provider.models().is_empty() {
                    print_zero_descriptor_diagnostic("migrations compose");
                    return ExitCode::from(2);
                }
                migrations::compose_cmd(
                    provider,
                    name.as_str(),
                    *allow_destructive,
                    *force_overwrite,
                    workspace.clone(),
                )
            }
            MigrationsCommand::Status { workspace } => migrations::status_cmd(workspace.clone()),
            MigrationsCommand::Verify { workspace, strict } => {
                migrations::verify_cmd(provider, workspace.clone(), *strict)
            }
            MigrationsCommand::Attune {
                target,
                apply,
                record,
                record_ledger,
                record_reason,
                squash,
                from,
                publish,
                app,
                workspace,
            } => migrations::attune_cmd(
                target.as_deref(),
                *apply,
                *record,
                *record_ledger,
                record_reason.as_str(),
                *squash,
                from.as_deref(),
                *publish,
                app.as_deref(),
                workspace.clone(),
            ),
            MigrationsCommand::Apply {
                workspace,
                fake,
                reason,
            } => migrations::apply_cmd(workspace.clone(), *fake, reason.clone()),
            MigrationsCommand::Repair { command } => migrations::repair_cmd(command.clone()),
            MigrationsCommand::Baseline {
                version,
                description,
                reason,
                app,
                database,
                workspace,
            } => migrations::baseline_cmd(
                version,
                description,
                reason,
                app.as_deref(),
                database.as_deref(),
                workspace.clone(),
            ),
        },
        TopCommand::Migrate { command } => match command {
            MigrateCommand::Apply {
                workspace,
                fake,
                reason,
            } => migrations::apply_cmd(workspace.clone(), *fake, reason.clone()),
        },
    }
}

/// Print the §5.6 dual-cause diagnostic when a descriptor-dependent
/// command (`compose` / `verify` / `schema` / `docs`) resolves zero model
/// descriptors, and exits the command with code `2` (refusal — the
/// command refuses because it cannot see the schema it needs).
///
/// The message is dual-cause because zero descriptors has two distinct
/// causes the operator must be able to tell apart:
///
/// 1. they ran the *standalone published* `djogi`, which links no
///    application models (build an adopter-linked `djogi` and run from it;
///    the standalone binary can still `migrations apply`); or
/// 2. this *is* their adopter-linked `djogi` but the linker dropped an
///    unreferenced model crate (ensure every `#[derive(Model)]` crate is
///    referenced via `link_models` / `djogi_main!`).
///
/// The first line is kept verbatim in sync with the troubleshooting
/// anchor in `docs/guide/adopter-cli.md` ("no djogi models are registered
/// in this binary") so an operator who searches the message lands on the
/// guide section that explains it.
///
/// `command` is the failing command name (e.g. `"migrations compose"`),
/// echoed so the operator knows which invocation refused. The single
/// emitter feeds `compose`, `verify`, `schema`, and `docs`, so one message
/// covers all four.
pub(crate) fn print_zero_descriptor_diagnostic(command: &str) {
    eprintln!("error: no djogi models are registered in this binary (djogi {command}).");
    eprintln!();
    eprintln!("Descriptor-dependent commands (compose, verify, schema, docs) require a");
    eprintln!("djogi binary linked with your model crates.");
    eprintln!();
    eprintln!("  • If you ran the standalone published `djogi`: that binary links no");
    eprintln!("    application models. Build an adopter-linked `djogi` (see the adopter");
    eprintln!("    CLI guide: docs/guide/adopter-cli.md) and run the command from it.");
    eprintln!("    The standalone binary can still run `djogi migrations apply` against");
    eprintln!("    already-composed pending artifacts.");
    eprintln!();
    eprintln!("  • If this IS your adopter-linked `djogi`: ensure your bin references");
    eprintln!("    every crate that defines `#[derive(Model)]` (link_models / djogi_main!),");
    eprintln!("    or the linker may have dropped an unreferenced model crate.");
}

#[cfg(test)]
mod tests {
    //! CLI-level argument-parsing tests. These exercise the `value_parser`
    //! attached to `--threshold-vacuum` directly; the goal is to pin the
    //! contract that nonsense input fails at parse time rather than
    //! silently producing a recommendation engine that "never fires."

    use clap::Parser as _;

    use std::path::PathBuf;

    use super::{
        Cli, DbCommand, MigrateCommand, MigrationsCommand, PartialApplyResolutionCli,
        RepairSubcommand, TopCommand, parse_threshold_vacuum,
    };

    #[test]
    fn parse_threshold_vacuum_accepts_valid_values() {
        assert_eq!(parse_threshold_vacuum("0.0").unwrap(), 0.0);
        assert_eq!(parse_threshold_vacuum("0.2").unwrap(), 0.2);
        assert_eq!(parse_threshold_vacuum("1.0").unwrap(), 1.0);
        // Boundary check: strictly inside the closed interval.
        assert_eq!(parse_threshold_vacuum("0.5").unwrap(), 0.5);
    }

    #[test]
    fn parse_threshold_vacuum_rejects_nan_inf_and_out_of_range() {
        // NaN — the entire reason this validator exists. `ratio > NaN`
        // is always false, so silent acceptance would mean VacuumNeeded
        // never fires, ever.
        let err = parse_threshold_vacuum("NaN").unwrap_err();
        assert!(err.contains("finite"), "err: {err}");

        // Positive infinity — same silent-failure mode.
        let err = parse_threshold_vacuum("inf").unwrap_err();
        assert!(err.contains("finite"), "err: {err}");

        // Negative infinity.
        let err = parse_threshold_vacuum("-inf").unwrap_err();
        assert!(err.contains("finite"), "err: {err}");

        // Negative finite — outside `[0.0, 1.0]`.
        let err = parse_threshold_vacuum("-0.1").unwrap_err();
        assert!(err.contains("[0.0, 1.0]"), "err: {err}");

        // Above 1.0 — outside `[0.0, 1.0]`.
        let err = parse_threshold_vacuum("1.5").unwrap_err();
        assert!(err.contains("[0.0, 1.0]"), "err: {err}");

        // Garbage — propagates the underlying ParseFloatError message.
        assert!(parse_threshold_vacuum("not-a-number").is_err());
    }

    #[test]
    fn db_reset_parses_allow_checksum_drift_reset_flag() {
        let cli = Cli::try_parse_from([
            "djogi",
            "db",
            "reset",
            "--yes",
            "--allow-checksum-drift-reset",
        ])
        .expect("flag should parse");

        match cli.command {
            TopCommand::Db {
                command:
                    DbCommand::Reset {
                        yes,
                        allow_checksum_drift_reset,
                        ..
                    },
            } => {
                assert!(yes, "--yes should parse through");
                assert!(
                    allow_checksum_drift_reset,
                    "checksum-drift override flag should parse through"
                );
            }
            _ => panic!("expected db reset command"),
        }
    }

    #[test]
    fn migrate_apply_alias_parses() {
        let cli = Cli::try_parse_from(["djogi", "migrate", "apply"])
            .expect("migrate apply should parse as alias");

        match cli.command {
            TopCommand::Migrate {
                command: MigrateCommand::Apply { .. },
            } => {}
            _ => panic!("expected migrate apply command"),
        }
    }

    #[test]
    fn canonical_migrations_apply_parses() {
        let cli = Cli::try_parse_from(["djogi", "migrations", "apply"])
            .expect("canonical migrations apply should parse");

        match cli.command {
            TopCommand::Migrations {
                command: MigrationsCommand::Apply { .. },
            } => {}
            _ => panic!("expected migrations apply command"),
        }
    }

    #[test]
    fn canonical_migrations_status_still_parses() {
        let cli = Cli::try_parse_from(["djogi", "migrations", "status"])
            .expect("canonical migrations status should parse");

        match cli.command {
            TopCommand::Migrations {
                command: MigrationsCommand::Status { .. },
            } => {}
            _ => panic!("expected migrations status command"),
        }
    }

    #[test]
    fn migrations_verify_parses_with_defaults() {
        let cli = Cli::try_parse_from(["djogi", "migrations", "verify"])
            .expect("migrations verify should parse with no flags");

        match cli.command {
            TopCommand::Migrations {
                command: MigrationsCommand::Verify { workspace, strict },
            } => {
                assert!(workspace.is_none());
                assert!(!strict);
            }
            _ => panic!("expected migrations verify command"),
        }
    }

    #[test]
    fn migrations_verify_parses_with_strict() {
        let cli = Cli::try_parse_from(["djogi", "migrations", "verify", "--strict"])
            .expect("migrations verify --strict should parse");

        match cli.command {
            TopCommand::Migrations {
                command: MigrationsCommand::Verify { strict, .. },
            } => {
                assert!(strict);
            }
            _ => panic!("expected migrations verify command"),
        }
    }

    #[test]
    fn migrations_verify_parses_with_workspace() {
        let cli = Cli::try_parse_from([
            "djogi",
            "migrations",
            "verify",
            "--workspace",
            "/custom/path",
        ])
        .expect("migrations verify --workspace should parse");

        match cli.command {
            TopCommand::Migrations {
                command: MigrationsCommand::Verify { workspace, .. },
            } => {
                assert_eq!(workspace, Some(PathBuf::from("/custom/path")));
            }
            _ => panic!("expected migrations verify command"),
        }
    }

    // ── repair subcommand argument parsing ─────────────────────────────────

    #[test]
    fn parse_repair_checksum_drift_accepts_required_args() {
        let cli = Cli::parse_from([
            "djogi",
            "migrations",
            "repair",
            "checksum-drift",
            "V20260101000000__test",
            "--checksum-up",
            "V1:aaaa",
        ]);
        assert!(matches!(cli.command, TopCommand::Migrations { .. }));
    }

    #[test]
    fn parse_repair_checksum_drift_rejects_missing_version() {
        let result = Cli::try_parse_from(["djogi", "migrations", "repair", "checksum-drift"]);
        assert!(result.is_err(), "must require version argument");
    }

    #[test]
    fn parse_repair_partial_apply_accepts_resolution_values() {
        for resolution in ["rolled-back", "faked", "applied"] {
            let cli = Cli::parse_from([
                "djogi",
                "migrations",
                "repair",
                "partial-apply",
                "V20260101000000__test",
                resolution,
            ]);
            assert!(
                matches!(cli.command, TopCommand::Migrations { .. }),
                "resolution={resolution}"
            );
        }
    }

    #[test]
    fn parse_repair_partial_apply_rejects_invalid_resolution() {
        let result = Cli::try_parse_from([
            "djogi",
            "migrations",
            "repair",
            "partial-apply",
            "V20260101000000__test",
            "invalid-resolution",
        ]);
        assert!(result.is_err(), "must reject unknown resolution");
    }

    #[test]
    fn parse_repair_resume_partial_accepts_version() {
        let cli = Cli::parse_from([
            "djogi",
            "migrations",
            "repair",
            "resume-partial",
            "V20260101000000__test",
        ]);
        assert!(matches!(cli.command, TopCommand::Migrations { .. }));
    }

    #[test]
    fn parse_repair_snapshot_rebuild_accepts_flags() {
        let cli = Cli::parse_from([
            "djogi",
            "migrations",
            "repair",
            "snapshot-rebuild",
            "--app",
            "myapp",
        ]);
        assert!(matches!(cli.command, TopCommand::Migrations { .. }));
    }

    // Field-binding destructuring tests — one per subcommand that carries
    // arguments. The outer-shape `matches!(..)` tests above prove the
    // variant is reached; these prove the named clap fields actually bind
    // to the supplied values (catching a `#[arg(long)]` typo or a
    // positional/flag mix-up that an outer-shape assertion would miss).

    #[test]
    fn parse_repair_checksum_drift_binds_version_and_checksum_up() {
        let cli = Cli::parse_from([
            "djogi",
            "migrations",
            "repair",
            "checksum-drift",
            "V20260101000000__add_users",
            "--checksum-up",
            "V1:aaaa",
        ]);
        if let TopCommand::Migrations {
            command: MigrationsCommand::Repair { command },
        } = cli.command
        {
            if let RepairSubcommand::ChecksumDrift {
                version,
                checksum_up,
                ..
            } = command
            {
                assert_eq!(version, "V20260101000000__add_users");
                assert_eq!(checksum_up.as_deref(), Some("V1:aaaa"));
            } else {
                panic!("wrong variant");
            }
        } else {
            panic!("wrong command");
        }
    }

    #[test]
    fn parse_repair_partial_apply_binds_resolution_and_note() {
        let cli = Cli::parse_from([
            "djogi",
            "migrations",
            "repair",
            "partial-apply",
            "V20260101000000__add_users",
            "rolled-back",
            "--note",
            "reverted by hot-fix",
        ]);
        if let TopCommand::Migrations {
            command: MigrationsCommand::Repair { command },
        } = cli.command
        {
            if let RepairSubcommand::PartialApply {
                version,
                resolution,
                note,
                ..
            } = command
            {
                assert_eq!(version, "V20260101000000__add_users");
                assert!(matches!(resolution, PartialApplyResolutionCli::RolledBack));
                assert_eq!(note, "reverted by hot-fix");
            } else {
                panic!("wrong variant");
            }
        } else {
            panic!("wrong command");
        }
    }

    #[test]
    fn parse_repair_snapshot_rebuild_binds_app_and_database() {
        let cli = Cli::parse_from([
            "djogi",
            "migrations",
            "repair",
            "snapshot-rebuild",
            "--app",
            "billing",
            "--database",
            "analytics",
        ]);
        if let TopCommand::Migrations {
            command: MigrationsCommand::Repair { command },
        } = cli.command
        {
            if let RepairSubcommand::SnapshotRebuild { app, database, .. } = command {
                assert_eq!(app.as_deref(), Some("billing"));
                assert_eq!(database.as_deref(), Some("analytics"));
            } else {
                panic!("wrong variant");
            }
        } else {
            panic!("wrong command");
        }
    }

    // ── baseline subcommand argument parsing ───────────────────────────────

    /// Extract the `MigrationsCommand::Baseline` variant from a parsed
    /// `Cli`, panicking on any other shape. Used by the baseline
    /// field-binding tests below so each test reads as a flat sequence
    /// of field assertions rather than nested `if let`s.
    fn baseline_command(cli: Cli) -> MigrationsCommand {
        match cli.command {
            TopCommand::Migrations {
                command: command @ MigrationsCommand::Baseline { .. },
            } => command,
            _ => panic!("expected migrations baseline command"),
        }
    }

    #[test]
    fn parse_baseline_accepts_required_args() {
        let cli = Cli::try_parse_from([
            "djogi",
            "migrations",
            "baseline",
            "V00000000000000__baseline",
            "--reason",
            "schema pre-exists from prior tooling",
        ])
        .unwrap();
        let MigrationsCommand::Baseline {
            version,
            reason,
            description,
            app,
            database,
            ..
        } = baseline_command(cli)
        else {
            panic!("expected Baseline");
        };
        assert_eq!(version, "V00000000000000__baseline");
        assert_eq!(reason, "schema pre-exists from prior tooling");
        assert_eq!(description, "existing database schema baseline");
        assert!(app.is_none());
        assert!(database.is_none());
    }

    #[test]
    fn parse_baseline_rejects_missing_version() {
        let result = Cli::try_parse_from(["djogi", "migrations", "baseline", "--reason", "test"]);
        assert!(
            result.is_err(),
            "baseline without version positional should fail"
        );
    }

    #[test]
    fn parse_baseline_rejects_missing_reason() {
        let result = Cli::try_parse_from([
            "djogi",
            "migrations",
            "baseline",
            "V00000000000000__baseline",
        ]);
        assert!(result.is_err(), "baseline without --reason should fail");
    }

    #[test]
    fn parse_baseline_accepts_optional_flags() {
        let cli = Cli::try_parse_from([
            "djogi",
            "migrations",
            "baseline",
            "V00000000000000__baseline",
            "--reason",
            "existing schema",
            "--description",
            "custom description",
            "--app",
            "billing",
            "--database",
            "crud_log",
        ])
        .unwrap();
        let MigrationsCommand::Baseline {
            version,
            reason,
            description,
            app,
            database,
            ..
        } = baseline_command(cli)
        else {
            panic!("expected Baseline");
        };
        assert_eq!(version, "V00000000000000__baseline");
        assert_eq!(reason, "existing schema");
        assert_eq!(description, "custom description");
        assert_eq!(app.as_deref(), Some("billing"));
        assert_eq!(database.as_deref(), Some("crud_log"));
    }
}