cratefield-cli 0.6.0

The fz CLI for Cratefield ventures: migrations collect/apply, doctor, modules, push
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
//! The agent-safe workflow commands (harness #140): `fz plan`, `fz
//! deploy --plan <digest>`, `fz add`, `fz init` and `fz verify`. They
//! work on the venture manifest — the desired composition — and two
//! on-disk records: the migration lockfile (`.harness-lock.json`) and
//! the deploy record (`.harness-deploy.json`) that `fz deploy` writes.
//! They never run wrangler, never touch a database and never prompt:
//! turning the recorded composition into a running Worker stays with
//! `worker-build` and `wrangler deploy`, and applying migrations stays
//! with `fz migrations collect` / `wrangler d1 migrations apply` — the
//! same needs-human boundary `fz build` draws.
//!
//! Every command speaks the two disciplines `fz doctor --json`
//! established (harness #140). With `--json` it prints exactly one JSON
//! object on stdout — `schema` 1, `ok`, the `failures` each carrying a
//! stable code from [`crate::codes`] — and nothing else. Without it the
//! output is prose for the operator. `--non-interactive` is accepted on
//! every command: the workflow never prompts by construction, so the
//! flag's one effect is suppressing the human `next:` steps from prose
//! output; anything that would need a human is a coded refusal, never a
//! blocked process.
//!
//! [`PlanContent`] is the whole normalised plan; its sha256 (`fz plan
//! --json`'s `digest`) is the approval token. `fz deploy` recomputes the
//! plan from the current inputs and refuses any other digest — a stale
//! approval cannot deploy — and records the plan it applied. `fz
//! verify` diffs that record against the manifest and reports the drift
//! as coded failures in the doctor's JSON shape.

use crate::codes::{CODES, DoctorCodeDef};
use crate::doctor::DoctorFailure;
use crate::doctor::DoctorReport;
use crate::lock::{Lock, read_lock, sha256_hex};
use cratefield_core::VentureEnv;
use cratefield_manifest::{Catalog, ModuleSet, VentureManifest, builtin};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::ExitCode;

/// The `schema` field of every workflow JSON object — the same wire
/// contract `fz doctor --json` carries ([`crate::doctor::REPORT_SCHEMA`]).
pub const SCHEMA: u32 = 1;

/// The deploy record `fz deploy` writes next to the manifest: the plan
/// it applied, bound to the digest that approved it.
pub const RECORD_FILE: &str = ".harness-deploy.json";

/// A recorded deployment. `plan` is the full [`PlanContent`] that was
/// applied, so `fz verify` can name precisely which part of the
/// manifest drifted, and a stale `fz deploy` can name what moved.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DeployRecord {
    /// [`SCHEMA`]; consumers branch on it.
    pub schema: u32,
    /// The digest that approved the recorded plan.
    pub digest: String,
    /// The normalised plan content as it was deployed.
    pub plan: PlanContent,
}

/// The destination a plan describes: what the venture will become,
/// independent of what it is now. The sha256 over this struct's JSON
/// is the plan digest — the approval token — because an approval is of
/// the destination, not of the journey: the baseline-dependent deltas
/// ([`PlanContent`]'s added/removed lists) describe the journey and
/// change the moment a deployment is recorded, so hashing them would
/// make every deploy stale by its own success.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PlanState {
    /// The venture name from the manifest.
    pub venture: String,
    /// The primary host from the manifest.
    pub host: String,
    /// The canonical public URL, when the manifest sets one.
    pub public_url: Option<String>,
    /// Browser origins allowed to call the API, sorted.
    pub cors_origins: Vec<String>,
    /// The resolved deployment environment (the manifest config's
    /// `ENV` key; `development` when unset or unrecognised).
    pub env: String,
    /// The resolved module set — dependencies before dependants —
    /// sorted, so manifest order cannot move the digest.
    pub modules: Vec<String>,
    /// The author's selection normalised: slug plus per-module config,
    /// sorted by slug. Per-module config changes are digest-visible
    /// here even when the resolved set is unchanged.
    pub selected: Vec<SelectedModule>,
    /// The venture-wide config the manifest declares.
    pub config: BTreeMap<String, String>,
    /// The seed SQL the manifest declares, if any.
    pub seed_sql: Option<String>,
    /// Migration status per resolved module, from the lockfile.
    pub migrations: MigrationState,
}

/// The full plan: the destination ([`PlanState`], flattened on the
/// wire, the only part the digest hashes) plus the deltas against the
/// current baseline — the deploy record when one exists, else the
/// modules the migration lockfile knows. Every list is sorted and
/// every map ordered, so output is a pure function of the inputs.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PlanContent {
    /// The hashed destination.
    #[serde(flatten)]
    pub state: PlanState,
    /// Slugs in the resolved set that the baseline does not have,
    /// sorted.
    pub modules_added: Vec<String>,
    /// Baseline slugs the resolved set no longer carries, sorted.
    /// Removing a module takes its data out of the served venture, so
    /// a plan with any of these is destructive and `fz deploy` demands
    /// the second consent for it.
    pub modules_removed: Vec<String>,
    /// What each added module needs, from the catalog: its tier, the
    /// modules it requires, and whether the author selected it or a
    /// dependency pulled it in. Sorted by slug.
    pub capabilities: Vec<Capability>,
    /// Config keys the baseline does not have, sorted.
    pub config_added: Vec<String>,
    /// Baseline config keys the manifest drops, sorted.
    pub config_removed: Vec<String>,
    /// Baseline config keys whose value changed, sorted.
    pub config_changed: Vec<String>,
}

/// One manifest module reference, normalised: the slug and its
/// per-module config (empty for the bare-slug form).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct SelectedModule {
    /// The module slug.
    pub slug: String,
    /// Per-module config keys, ordered.
    pub config: BTreeMap<String, String>,
}

/// What one added module needs, as the catalog declares it.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Capability {
    /// The module slug.
    pub slug: String,
    /// `core` or `optional`.
    pub tier: String,
    /// The slugs this module requires; the catalog pulls them in, and
    /// resolution orders them before it.
    pub requires: Vec<String>,
    /// `selected` when the author listed it; `dependency` when another
    /// module's requirement pulled it into the set.
    pub via: String,
}

/// Migration status, read from the lockfile. The manifest world cannot
/// know whether a module ships migrations at all — only what has been
/// collected — so `not_collected` means "no locked migration exists",
/// phrased exactly that way in output.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct MigrationState {
    /// Resolved module -> number of locked migration files, ordered.
    pub collected: BTreeMap<String, usize>,
    /// Resolved modules with no locked migrations, sorted.
    pub not_collected: Vec<String>,
    /// Lockfile entries (`module/id`) whose module the resolved set no
    /// longer carries, sorted — the migration files a removal orphans.
    pub orphaned: Vec<String>,
}

/// What the plan diffed against, and the slugs it saw there.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Baseline {
    /// `deploy-record`, `lockfile` or `nothing`.
    pub source: &'static str,
    /// The baseline module slugs, sorted.
    pub modules: Vec<String>,
}

/// The two consents `fz deploy` can require, kept apart on purpose.
///
/// One flag for both would mean removing a module from a *development*
/// venture required asserting "I am deploying to production" — which is
/// untrue, and which teaches an operator to pass the production flag by
/// habit. A gate that is passed habitually is not a gate.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Consent {
    /// `--i-am-deploying-to-production`: this venture resolves to
    /// production.
    pub production: bool,
    /// `--i-am-removing-modules`: the plan drops modules from the served
    /// composition.
    pub removal: bool,
}

/// The outcome of `fz plan`: the normalised content and its digest.
#[derive(Debug, Clone)]
pub struct PlanOutcome {
    /// The normalised plan.
    pub content: PlanContent,
    /// sha256 over the JSON of [`PlanContent`] — the approval token
    /// `fz deploy --plan` demands.
    pub digest: String,
    /// What the deltas were computed against.
    pub baseline: Baseline,
}

/// The outcome of `fz deploy`.
#[derive(Debug, Clone)]
pub struct DeployOutcome {
    /// The plan that was applied.
    pub content: PlanContent,
    /// The digest that approved it.
    pub digest: String,
    /// `false` when the exact plan was already recorded — the
    /// idempotent second run changes nothing and says so.
    pub changed: bool,
    /// Where the record lives (or would live).
    pub record_path: PathBuf,
}

/// The outcome of `fz add`.
#[derive(Debug, Clone)]
pub struct AddOutcome {
    /// `false` when the module was already in the manifest — the
    /// no-op second run changes nothing and says so.
    pub changed: bool,
    /// The module slug named on the command line.
    pub module: String,
    /// The manifest file.
    pub manifest: PathBuf,
}

/// The outcome of `fz verify`: the doctor-shaped report plus the
/// recomputed digest when the manifest resolved far enough to compute
/// one.
#[derive(Debug)]
pub struct VerifyOutcome {
    /// Coded failures in the doctor's shape.
    pub report: DoctorReport,
    /// The recomputed plan digest, when available.
    pub digest: Option<String>,
}

/// Builds one coded failure.
fn failure(code: &'static DoctorCodeDef, message: impl Into<String>) -> DoctorFailure {
    DoctorFailure {
        code,
        message: message.into(),
    }
}

/// The prose form of a failure list, byte-compatible with the doctor's.
fn joined(failures: &[DoctorFailure]) -> String {
    failures
        .iter()
        .map(|f| f.message.as_str())
        .collect::<Vec<_>>()
        .join("\n  - ")
}

/// The deployment environment the manifest declares: its `ENV` config
/// key, `development` when absent or unrecognised. Unlike the deployed
/// runtime (issue #143), the manifest world has no compiled environment
/// to take the stricter of — the manifest is the declaration, and the
/// deployment's own `ENV` binding is checked where the harness exists,
/// by `fz doctor`.
fn resolved_env(manifest: &VentureManifest) -> VentureEnv {
    manifest
        .config
        .get("ENV")
        .and_then(|value| VentureEnv::parse(value))
        .unwrap_or_default()
}

/// Where the deploy record for this manifest lives: beside it.
fn record_path(manifest_path: &Path) -> PathBuf {
    let mut path = manifest_path.parent().map_or_else(PathBuf::new, |parent| {
        if parent.as_os_str().is_empty() {
            PathBuf::new()
        } else {
            parent.to_path_buf()
        }
    });
    path.push(RECORD_FILE);
    path
}

/// Reads the deploy record. Absent means never deployed (`None`); a
/// record that cannot be read or parsed is a real error.
fn read_record(manifest_path: &Path) -> Result<Option<DeployRecord>, String> {
    let path = record_path(manifest_path);
    let raw = match std::fs::read_to_string(&path) {
        Ok(raw) => raw,
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(err) => return Err(format!("cannot read {}: {err}", path.display())),
    };
    let record: DeployRecord = serde_json::from_str(&raw)
        .map_err(|err| format!("cannot parse {}: {err}", path.display()))?;
    if record.schema != SCHEMA {
        return Err(format!(
            "{}: unsupported schema {} (this fz speaks {SCHEMA})",
            path.display(),
            record.schema
        ));
    }
    Ok(Some(record))
}

/// Writes the deploy record atomically — write a sibling temp file,
/// then rename — so an interrupted deploy leaves either the previous
/// record or the new one, never a torn file, and re-running `fz
/// deploy` reconciles.
fn write_record(manifest_path: &Path, record: &DeployRecord) -> Result<PathBuf, String> {
    let path = record_path(manifest_path);
    let body = serde_json::to_string_pretty(record)
        .map_err(|err| format!("cannot serialize the deploy record: {err}"))?;
    let mut tmp = path.clone();
    tmp.set_extension("tmp");
    std::fs::write(&tmp, body + "\n")
        .map_err(|err| format!("cannot write {}: {err}", tmp.display()))?;
    std::fs::rename(&tmp, &path).map_err(|err| {
        format!(
            "cannot finalize {} (partial file left at {}): {err}",
            path.display(),
            tmp.display()
        )
    })?;
    Ok(path)
}

/// Writes a manifest back in the format its extension names — JSON by
/// default, TOML for `.toml`. Comments and formatting of the original
/// file are not preserved; the parsed document is.
fn write_manifest(path: &Path, manifest: &VentureManifest) -> Result<(), String> {
    let body = match path.extension().and_then(|ext| ext.to_str()) {
        Some("toml") => toml::to_string_pretty(manifest)
            .map_err(|err| format!("cannot serialize TOML manifest: {err}"))?,
        _ => serde_json::to_string_pretty(manifest)
            .map_err(|err| format!("cannot serialize manifest: {err}"))?,
    };
    std::fs::write(path, body + "\n")
        .map_err(|err| format!("cannot write {}: {err}", path.display()))
}

/// Everything the workflow commands read: the manifest (parsed and
/// resolved), the migration lockfile and the deploy record.
struct Inputs {
    manifest: VentureManifest,
    set: ModuleSet,
    lock: Lock,
    record: Option<DeployRecord>,
    catalog: Catalog,
}

/// Reads and resolves the inputs. The manifest is upstream of
/// everything, so it fails fast; lockfile and deploy-record problems
/// accumulate and surface together.
fn load(manifest_path: &Path, migrations_dir: &Path) -> Result<Inputs, Vec<DoctorFailure>> {
    let raw = std::fs::read_to_string(manifest_path).map_err(|err| {
        vec![failure(
            &CODES.manifest_unreadable,
            format!("cannot read {}: {err}", manifest_path.display()),
        )]
    })?;
    let manifest = crate::build::parse(manifest_path, &raw).map_err(|err| {
        vec![failure(
            &CODES.manifest_unreadable,
            format!("{}: {err}", manifest_path.display()),
        )]
    })?;
    let catalog = builtin();
    let set = manifest
        .resolve(&catalog)
        .map_err(|err| vec![failure(&CODES.manifest_invalid, err.to_string())])?;

    let mut failures: Vec<DoctorFailure> = Vec::new();
    let lock = match read_lock(migrations_dir) {
        Ok(lock) => lock,
        Err(err) => {
            failures.push(failure(&CODES.lockfile_unreadable, err));
            Lock::default()
        }
    };
    let record = match read_record(manifest_path) {
        Ok(record) => record,
        Err(err) => {
            failures.push(failure(&CODES.deploy_record_unreadable, err));
            None
        }
    };
    if failures.is_empty() {
        Ok(Inputs {
            manifest,
            set,
            lock,
            record,
            catalog,
        })
    } else {
        Err(failures)
    }
}

/// The module slugs the lockfile knows, sorted — the collected
/// composition, as close to "what deployment tooling last saw" as the
/// manifest world gets without a deploy record.
fn lockfile_modules(lock: &Lock) -> Vec<String> {
    let mut modules: Vec<String> = lock
        .keys()
        .filter_map(|key| key.split('/').next())
        .filter(|module| !module.is_empty())
        .map(str::to_owned)
        .collect();
    modules.sort_unstable();
    modules.dedup();
    modules
}

/// What the plan diffs against: the deploy record when one exists,
/// else the lockfile's modules, else nothing.
fn baseline_of(lock: &Lock, record: Option<&DeployRecord>) -> Baseline {
    if let Some(record) = record {
        let mut modules = record.plan.state.modules.clone();
        modules.sort_unstable();
        return Baseline {
            source: "deploy-record",
            modules,
        };
    }
    let modules = lockfile_modules(lock);
    if modules.is_empty() {
        Baseline {
            source: "nothing",
            modules: Vec::new(),
        }
    } else {
        Baseline {
            source: "lockfile",
            modules,
        }
    }
}

/// What each added module needs, as the catalog declares it: tier,
/// required modules, and whether the author selected it or a
/// dependency pulled it in.
fn capabilities_of(added: &[String], selected: &[&str], catalog: &Catalog) -> Vec<Capability> {
    added
        .iter()
        .filter_map(|slug| {
            let module = catalog.modules.iter().find(|m| &m.slug == slug)?;
            let tier = match module.tier {
                cratefield_manifest::Tier::Core => "core",
                cratefield_manifest::Tier::Optional => "optional",
            };
            let mut requires = module.depends_on.clone();
            requires.sort_unstable();
            Some(Capability {
                slug: slug.clone(),
                tier: tier.to_owned(),
                requires,
                via: if selected.contains(&slug.as_str()) {
                    "selected".to_owned()
                } else {
                    "dependency".to_owned()
                },
            })
        })
        .collect()
}

/// The venture-wide config deltas against the recorded config.
fn config_deltas(
    manifest: &VentureManifest,
    recorded: &BTreeMap<String, String>,
) -> (Vec<String>, Vec<String>, Vec<String>) {
    let config_added: Vec<String> = manifest
        .config
        .keys()
        .filter(|key| !recorded.contains_key(*key))
        .cloned()
        .collect();
    let config_removed: Vec<String> = recorded
        .keys()
        .filter(|key| !manifest.config.contains_key(*key))
        .cloned()
        .collect();
    let config_changed: Vec<String> = manifest
        .config
        .iter()
        .filter(|(key, value)| {
            recorded
                .get(*key)
                .is_some_and(|recorded| recorded != *value)
        })
        .map(|(key, _)| key.clone())
        .collect();
    (config_added, config_removed, config_changed)
}

/// Migration status per resolved module, read from the lockfile.
fn migration_state(desired: &[String], lock: &Lock) -> MigrationState {
    let mut state = MigrationState::default();
    for key in lock.keys() {
        let Some(module) = key.split('/').next() else {
            continue;
        };
        if desired.iter().any(|slug| slug == module) {
            *state.collected.entry(module.to_owned()).or_insert(0) += 1;
        } else {
            state.orphaned.push(key.clone());
        }
    }
    state.not_collected = desired
        .iter()
        .filter(|slug| !state.collected.contains_key(*slug))
        .cloned()
        .collect();
    state.orphaned.sort_unstable();
    state
}

/// Computes the normalised plan and its baseline. Pure: the same
/// inputs always produce the same content, so the same digest.
#[must_use]
fn compute_plan(
    manifest: &VentureManifest,
    set: &ModuleSet,
    lock: &Lock,
    record: Option<&DeployRecord>,
    catalog: &Catalog,
) -> (PlanContent, Baseline) {
    let mut desired = set.slugs().to_vec();
    desired.sort_unstable();
    let baseline = baseline_of(lock, record);
    let modules_added: Vec<String> = desired
        .iter()
        .filter(|slug| !baseline.modules.contains(slug))
        .cloned()
        .collect();
    let modules_removed: Vec<String> = baseline
        .modules
        .iter()
        .filter(|slug| !desired.contains(slug))
        .cloned()
        .collect();

    let selected_slugs = manifest.module_slugs();
    let capabilities = capabilities_of(&modules_added, &selected_slugs, catalog);
    let recorded_config: &BTreeMap<String, String> = match record {
        Some(record) => &record.plan.state.config,
        None => &BTreeMap::new(),
    };
    let (config_added, config_removed, config_changed) = config_deltas(manifest, recorded_config);

    let mut selected: Vec<SelectedModule> = manifest
        .modules
        .iter()
        .map(|module| SelectedModule {
            slug: module.slug().to_owned(),
            config: module.config(),
        })
        .collect();
    selected.sort_unstable();

    let migrations = migration_state(&desired, lock);
    let mut cors_origins = manifest.cors_origins.clone();
    cors_origins.sort_unstable();

    let state = PlanState {
        venture: manifest.name.clone(),
        host: manifest.host.clone(),
        public_url: manifest.public_url.clone(),
        cors_origins,
        env: resolved_env(manifest).as_str().to_owned(),
        modules: desired,
        selected,
        config: manifest.config.clone(),
        seed_sql: manifest.seed_sql.clone(),
        migrations,
    };
    let content = PlanContent {
        state,
        modules_added,
        modules_removed,
        capabilities,
        config_added,
        config_removed,
        config_changed,
    };
    (content, baseline)
}

/// The digest of a plan: sha256 over the normalised destination
/// state's JSON — deliberately not over the baseline-dependent deltas,
/// so a deploy does not go stale by its own success.
///
/// # Errors
///
/// Only if `serde_json` cannot serialize the content — a struct of
/// strings, maps and lists cannot hit that, but the Result keeps every
/// caller total instead of panicking.
fn plan_digest(content: &PlanContent) -> Result<String, Vec<DoctorFailure>> {
    serde_json::to_vec(&content.state)
        .map(|bytes| sha256_hex(&bytes))
        .map_err(|err| {
            vec![failure(
                &CODES.manifest_invalid,
                format!("the plan content does not serialize: {err}"),
            )]
        })
}

/// `fz plan`: describes what the manifest would change, and nothing
/// else. Read-only by construction — nothing here touches the disk
/// beyond reading its inputs.
///
/// # Errors
///
/// Coded failures when the manifest cannot be read or resolved, or the
/// lockfile or deploy record cannot be parsed.
pub fn plan(
    manifest_path: &Path,
    migrations_dir: &Path,
) -> Result<PlanOutcome, Vec<DoctorFailure>> {
    let inputs = load(manifest_path, migrations_dir)?;
    let (content, baseline) = compute_plan(
        &inputs.manifest,
        &inputs.set,
        &inputs.lock,
        inputs.record.as_ref(),
        &inputs.catalog,
    );
    let digest = plan_digest(&content)?;
    Ok(PlanOutcome {
        content,
        digest,
        baseline,
    })
}

/// What moved between the recorded state and the one recomputed now —
/// the message a stale `fz deploy` shows. Every field is named; when
/// none differs the digests can disagree only by a plan-format
/// evolution, and the message says that too.
fn moved_since(current: &PlanState, recorded: &PlanState) -> Vec<String> {
    let mut moved: Vec<String> = Vec::new();
    if let Some(what) = diff_modules(&current.modules, &recorded.modules) {
        moved.push(format!("modules: {what}"));
    }
    if let Some(what) = diff_config(&current.config, &recorded.config) {
        moved.push(format!("config: {what}"));
    }
    if current.env != recorded.env {
        moved.push(format!("environment: {} -> {}", recorded.env, current.env));
    }
    if current.host != recorded.host {
        moved.push(format!("host: {} -> {}", recorded.host, current.host));
    }
    if current.public_url != recorded.public_url {
        moved.push("public URL changed".to_owned());
    }
    if current.cors_origins != recorded.cors_origins {
        moved.push("CORS origins changed".to_owned());
    }
    if current.seed_sql != recorded.seed_sql {
        moved.push("seed SQL changed".to_owned());
    }
    if current.selected != recorded.selected {
        moved.push("the module selection or its per-module config changed".to_owned());
    }
    moved
}

/// One line about a module-set difference, or `None` when equal.
fn diff_modules(current: &[String], recorded: &[String]) -> Option<String> {
    let added: Vec<&String> = current
        .iter()
        .filter(|slug| !recorded.contains(slug))
        .collect();
    let removed: Vec<&String> = recorded
        .iter()
        .filter(|slug| !current.contains(slug))
        .collect();
    if added.is_empty() && removed.is_empty() {
        return None;
    }
    let mut parts: Vec<String> = Vec::new();
    if !added.is_empty() {
        parts.push(format!(
            "added {}",
            added
                .iter()
                .map(|slug| slug.as_str())
                .collect::<Vec<_>>()
                .join(", ")
        ));
    }
    if !removed.is_empty() {
        parts.push(format!(
            "removed {}",
            removed
                .iter()
                .map(|slug| slug.as_str())
                .collect::<Vec<_>>()
                .join(", ")
        ));
    }
    Some(parts.join("; "))
}

/// One line about a config difference, or `None` when equal.
fn diff_config(
    current: &BTreeMap<String, String>,
    recorded: &BTreeMap<String, String>,
) -> Option<String> {
    let added: Vec<&String> = current
        .keys()
        .filter(|key| !recorded.contains_key(*key))
        .collect();
    let removed: Vec<&String> = recorded
        .keys()
        .filter(|key| !current.contains_key(*key))
        .collect();
    let changed: Vec<&String> = current
        .iter()
        .filter(|(key, value)| recorded.get(*key).is_some_and(|r| r != *value))
        .map(|(key, _)| key)
        .collect();
    if added.is_empty() && removed.is_empty() && changed.is_empty() {
        return None;
    }
    let mut parts: Vec<String> = Vec::new();
    let list = |keys: &[&String]| {
        keys.iter()
            .map(|key| key.as_str())
            .collect::<Vec<_>>()
            .join(", ")
    };
    if !added.is_empty() {
        parts.push(format!("added {}", list(&added)));
    }
    if !removed.is_empty() {
        parts.push(format!("removed {}", list(&removed)));
    }
    if !changed.is_empty() {
        parts.push(format!("changed {}", list(&changed)));
    }
    Some(parts.join("; "))
}

/// `fz deploy --plan <digest>`: applies exactly the approved plan — by
/// recording it, bound to its digest, in `.harness-deploy.json` beside
/// the manifest. It refuses:
///
/// - without `--plan` at all (approval is the point);
/// - a digest that does not match a plan recomputed now, naming what
///   moved since the recorded deployment;
/// - a production venture without `--i-am-deploying-to-production` —
///   the second consent, deliberately unlike the first;
/// - a plan that removes modules without `--i-am-removing-modules`, a
///   consent separate from the production one.
///
/// Writing the composition itself — compiling, standing up the Worker,
/// applying migrations — stays with the needs-human steps `fz build`
/// and the wrangler flow own. Running the same approved deploy twice
/// is safe: the second run records nothing and reports `changed:
/// false`.
///
/// # Errors
///
/// Coded failures for every refusal above, plus unreadable inputs and
/// a record that cannot be written.
pub fn deploy(
    approved: Option<&str>,
    manifest_path: &Path,
    migrations_dir: &Path,
    consent: Consent,
) -> Result<DeployOutcome, Vec<DoctorFailure>> {
    let Some(approved) = approved else {
        return Err(vec![failure(
            &CODES.deploy_plan_required,
            "deploy requires an approved plan — run `fz plan --json` and pass its `digest` \
             as --plan; there is no default",
        )]);
    };
    let inputs = load(manifest_path, migrations_dir)?;
    let (planned, _) = compute_plan(
        &inputs.manifest,
        &inputs.set,
        &inputs.lock,
        inputs.record.as_ref(),
        &inputs.catalog,
    );
    let digest = plan_digest(&planned)?;

    let mut failures: Vec<DoctorFailure> = Vec::new();
    if approved != digest {
        failures.push(failure(
            &CODES.stale_plan,
            stale_plan_message(&planned, inputs.record.as_ref(), approved, &digest),
        ));
    }
    if resolved_env(&inputs.manifest) == VentureEnv::Production && !consent.production {
        failures.push(failure(
            &CODES.production_deploy_unauthorized,
            "this venture resolves to production (manifest config ENV=production) — deploying \
             needs a second, explicit consent: pass --i-am-deploying-to-production alongside \
             the approved digest",
        ));
    }
    // Every locked migration still has to be the file that was locked.
    //
    // `fz doctor` checks this against a compiled harness; deploy does not
    // have one, so it checks the lockfile directly — which is the stronger
    // read for this purpose, because it covers entries whose module the
    // resolved set no longer carries. Without it an edited migration
    // deploys silently: the recorded plan claims a schema the files no
    // longer produce, and the next environment to apply them gets
    // something different from the one already running.
    for (key, entry) in &inputs.lock {
        if let Err(err) = crate::collect::verify_locked(migrations_dir, key, entry) {
            let code = match &err {
                crate::collect::LockedMigrationError::Missing { .. } => {
                    &CODES.locked_migration_missing
                }
                crate::collect::LockedMigrationError::Edited { .. } => {
                    &CODES.locked_migration_edited
                }
            };
            failures.push(failure(code, err.to_string()));
        }
    }

    if !planned.modules_removed.is_empty() && !consent.removal {
        // Deliberately precise about what a removal does and does not do.
        // `fz deploy` never touches a database, so nothing is deleted: the
        // modules stop being compiled in and stop serving, and their
        // tables stay exactly as they are, holding what they held. That
        // matters in both directions — an operator who reads "its data
        // leaves the venture" reaches for a backup nobody needs, and one
        // who *wanted* those rows gone walks away believing they are.
        let orphans = &planned.state.migrations.orphaned;
        let leftovers = if orphans.is_empty() {
            String::new()
        } else {
            format!(
                " The migrations {} stay applied and the tables they created keep their rows; \
                 dropping them is a separate, manual step (docs/ROLLBACK.md).",
                orphans.join(", ")
            )
        };
        failures.push(failure(
            &CODES.destructive_change_unauthorized,
            format!(
                "this plan removes {} from the served composition: those modules stop being \
                 served, and no data is deleted.{leftovers} Pass --i-am-removing-modules to \
                 accept that",
                planned.modules_removed.join(", ")
            ),
        ));
    }
    if !failures.is_empty() {
        return Err(failures);
    }

    let record_path = record_path(manifest_path);
    if inputs
        .record
        .as_ref()
        .is_some_and(|record| record.digest == digest)
    {
        return Ok(DeployOutcome {
            content: planned,
            digest,
            changed: false,
            record_path,
        });
    }
    let record = DeployRecord {
        schema: SCHEMA,
        digest: digest.clone(),
        plan: planned.clone(),
    };
    let record_path = write_record(manifest_path, &record)
        .map_err(|err| vec![failure(&CODES.manifest_write_failed, err)])?;
    Ok(DeployOutcome {
        content: planned,
        digest,
        changed: true,
        record_path,
    })
}

/// Why the approved digest is stale, naming what moved: every field
/// that differs from the recorded deployment, or — when none does —
/// the honest answer that the digest came from a different fz or an
/// older plan format.
fn stale_plan_message(
    planned: &PlanContent,
    record: Option<&DeployRecord>,
    approved: &str,
    digest: &str,
) -> String {
    let mut message = format!(
        "the approved digest {approved} does not match a plan recomputed from the current \
         inputs (the current digest is {digest})"
    );
    let Some(record) = record else {
        let mut what: Vec<String> = Vec::new();
        if !planned.modules_added.is_empty() {
            what.push(format!("add {}", planned.modules_added.join(", ")));
        }
        if !planned.modules_removed.is_empty() {
            what.push(format!("remove {}", planned.modules_removed.join(", ")));
        }
        if what.is_empty() {
            message
                .push_str("; no deployment is recorded yet, so there is nothing to diff against");
        } else {
            message.push_str("; no deployment is recorded yet and the current plan would ");
            message.push_str(&what.join(" and "));
        }
        return message;
    };
    let moved = moved_since(&planned.state, &record.plan.state);
    if moved.is_empty() {
        message.push_str(
            "; the recorded deployment matches every plan field, so the approved digest was \
             computed by a different fz or an older plan format",
        );
    } else {
        message.push_str("; since the recorded deployment: ");
        message.push_str(&moved.join("; "));
    }
    message
}

/// `fz add <module>`: adds a module to the manifest's desired
/// composition and nothing else — it never deploys, never provisions
/// and never touches a database. Adding a module the manifest already
/// lists is a no-op that succeeds with `changed: false`.
///
/// # Errors
///
/// Coded failures when the manifest cannot be read or resolved, the
/// slug is not in the catalog, or the manifest cannot be written back.
pub fn add(module: &str, manifest_path: &Path) -> Result<AddOutcome, Vec<DoctorFailure>> {
    let raw = std::fs::read_to_string(manifest_path).map_err(|err| {
        vec![failure(
            &CODES.manifest_unreadable,
            format!("cannot read {}: {err}", manifest_path.display()),
        )]
    })?;
    let mut manifest = crate::build::parse(manifest_path, &raw).map_err(|err| {
        vec![failure(
            &CODES.manifest_unreadable,
            format!("{}: {err}", manifest_path.display()),
        )]
    })?;
    let catalog = builtin();
    manifest
        .resolve(&catalog)
        .map_err(|err| vec![failure(&CODES.manifest_invalid, err.to_string())])?;

    if manifest.module_slugs().contains(&module) {
        return Ok(AddOutcome {
            changed: false,
            module: module.to_owned(),
            manifest: manifest_path.to_path_buf(),
        });
    }

    let known: Vec<&str> = catalog.modules.iter().map(|m| m.slug.as_str()).collect();
    if !known.contains(&module) {
        return Err(vec![failure(
            &CODES.module_unknown,
            format!(
                "`{module}` is not a module in the catalog; available: {}",
                known.join(", ")
            ),
        )]);
    }
    manifest
        .modules
        .push(cratefield_manifest::ModuleRef::Slug(module.to_owned()));
    manifest
        .resolve(&catalog)
        .map_err(|err| vec![failure(&CODES.manifest_invalid, err.to_string())])?;
    write_manifest(manifest_path, &manifest)
        .map_err(|err| vec![failure(&CODES.manifest_write_failed, err)])?;
    Ok(AddOutcome {
        changed: true,
        module: module.to_owned(),
        manifest: manifest_path.to_path_buf(),
    })
}

/// `fz init`: writes a new venture manifest — name and host, no
/// modules yet. Refuses to overwrite an existing manifest unless
/// `--force`.
///
/// # Errors
///
/// Coded failures when the file exists without `--force`, the name or
/// host is empty, or the manifest cannot be written.
pub fn init(
    name: &str,
    host: &str,
    manifest_path: &Path,
    force: bool,
) -> Result<PathBuf, Vec<DoctorFailure>> {
    if manifest_path.exists() && !force {
        return Err(vec![failure(
            &CODES.manifest_exists,
            format!(
                "{} already exists — init refuses to overwrite a manifest; pass --force to \
                 replace it",
                manifest_path.display()
            ),
        )]);
    }
    let manifest = VentureManifest {
        name: name.to_owned(),
        host: host.to_owned(),
        // The venture's own URL, which its problem `type` URIs are named
        // under (`<public_url>/problems/<slug>` — issue #557). Scaffolded
        // for the same reason as `cors_origins` below: without it the
        // harness falls back to `about:blank`, and a manifest that builds
        // into an error vocabulary with no URI is a worse first step than
        // one line the author rarely has to change.
        public_url: Some(format!("https://{host}")),
        // The venture's own host, which is the origin a browser on its
        // site sends. Scaffolded rather than left empty because the
        // harness refuses a venture with none — `fz init` writing a
        // manifest that `fz build` would reject is a first step that
        // fails on the second.
        //
        // A guess, and the one an author is most likely to want: a front
        // end on another domain is a line they edit, which is a better
        // failure than a manifest that does not build.
        cors_origins: vec![format!("https://{host}")],
        modules: Vec::new(),
        config: BTreeMap::new(),
        seed_sql: None,
        // `fz init` scaffolds a venture with no tables of its own; a
        // declaration is something an author adds (issue #153).
        ..Default::default()
    };
    manifest
        .validate()
        .map_err(|err| vec![failure(&CODES.manifest_invalid, err.to_string())])?;
    write_manifest(manifest_path, &manifest)
        .map_err(|err| vec![failure(&CODES.manifest_write_failed, err)])?;
    Ok(manifest_path.to_path_buf())
}

/// `fz verify`: diffs the recorded deployment against the manifest and
/// reports every drift as a coded failure in the doctor's shape —
/// composition, config, environment, and (when nothing narrower
/// explains it) the recorded digest no longer matching a recomputed
/// plan.
///
/// # Panics
///
/// Never; every problem is a coded failure in the report.
#[must_use]
pub fn verify(manifest_path: &Path, migrations_dir: &Path) -> VerifyOutcome {
    let inputs = match load(manifest_path, migrations_dir) {
        Ok(inputs) => inputs,
        Err(failures) => {
            return VerifyOutcome {
                report: DoctorReport { failures },
                digest: None,
            };
        }
    };
    let (content, _) = compute_plan(
        &inputs.manifest,
        &inputs.set,
        &inputs.lock,
        inputs.record.as_ref(),
        &inputs.catalog,
    );
    let mut failures: Vec<DoctorFailure> = Vec::new();
    let digest = match plan_digest(&content) {
        Ok(digest) => digest,
        Err(new_failures) => {
            return VerifyOutcome {
                report: DoctorReport {
                    failures: new_failures,
                },
                digest: None,
            };
        }
    };

    let Some(record) = &inputs.record else {
        failures.push(failure(
            &CODES.not_deployed,
            "no deployment is recorded for this manifest — run `fz plan --json`, approve the \
             digest, then `fz deploy --plan <digest>`",
        ));
        return VerifyOutcome {
            report: DoctorReport { failures },
            digest: Some(digest),
        };
    };

    if let Some(what) = diff_modules(&content.state.modules, &record.plan.state.modules) {
        failures.push(failure(
            &CODES.composition_drift,
            format!("the recorded deployment's module set drifted from the manifest: {what}"),
        ));
    }
    if let Some(what) = diff_config(&content.state.config, &record.plan.state.config) {
        failures.push(failure(
            &CODES.config_drift,
            format!("the recorded deployment's config drifted from the manifest: {what}"),
        ));
    }
    if content.state.env != record.plan.state.env {
        failures.push(failure(
            &CODES.env_drift,
            format!(
                "the deployment environment drifted: recorded {}, manifest resolves to {}",
                record.plan.state.env, content.state.env
            ),
        ));
    }
    let narrow = failures.len();
    if record.digest != digest {
        let moved = moved_since(&content.state, &record.plan.state);
        let message = if moved.is_empty() {
            format!(
                "the recorded digest does not match a plan recomputed from the manifest, and \
                 no module, config or environment drift explains it — the venture's host, \
                 public URL, CORS origins, seed SQL or per-module config changed since the \
                 deployment was recorded (recorded {}, current {digest})",
                record.digest
            )
        } else {
            format!(
                "the recorded digest does not match a plan recomputed from the manifest \
                 (recorded {}, current {digest}): {}",
                record.digest,
                moved.join("; ")
            )
        };
        if failures.len() == narrow {
            failures.push(failure(&CODES.manifest_drift, message));
        }
    }
    VerifyOutcome {
        report: DoctorReport { failures },
        digest: Some(digest),
    }
}

/// One failure as it travels on the wire: the catalogue slug plus the
/// message, in the doctor's shape.
#[derive(Serialize)]
struct FailRef<'a> {
    code: &'a str,
    message: &'a str,
}

/// Every workflow failure payload: the doctor's object, nothing more.
#[derive(Serialize)]
struct BarePayload<'a> {
    schema: u32,
    ok: bool,
    failures: Vec<FailRef<'a>>,
}

/// The `fz plan --json` object: the verdict plus the plan content and
/// its digest.
#[derive(Serialize)]
struct PlanPayload<'a> {
    schema: u32,
    ok: bool,
    failures: Vec<FailRef<'a>>,
    digest: &'a str,
    #[serde(flatten)]
    content: &'a PlanContent,
    baseline: &'a Baseline,
}

/// The `fz deploy --json` object.
#[derive(Serialize)]
struct DeployPayload<'a> {
    schema: u32,
    ok: bool,
    failures: Vec<FailRef<'a>>,
    changed: bool,
    digest: &'a str,
    venture: &'a str,
    env: &'a str,
    modules_added: &'a [String],
    modules_removed: &'a [String],
    record: String,
}

/// The `fz add --json` object.
#[derive(Serialize)]
struct AddPayload<'a> {
    schema: u32,
    ok: bool,
    failures: Vec<FailRef<'a>>,
    changed: bool,
    module: &'a str,
    manifest: String,
}

/// The `fz init --json` object.
#[derive(Serialize)]
struct InitPayload<'a> {
    schema: u32,
    ok: bool,
    failures: Vec<FailRef<'a>>,
    name: &'a str,
    host: &'a str,
    manifest: String,
}

fn refs(failures: &[DoctorFailure]) -> Vec<FailRef<'_>> {
    failures
        .iter()
        .map(|failure| FailRef {
            code: failure.code.code,
            message: &failure.message,
        })
        .collect()
}

/// Prints one JSON object — the payload plus the exit code it implies.
/// Serialization cannot fail for these structs; the stderr fallback
/// mirrors [`crate::doctor::doctor_json`].
fn emit(payload: &impl Serialize, exit: ExitCode) -> ExitCode {
    match serde_json::to_string(payload) {
        Ok(line) => {
            println!("{line}");
            exit
        }
        Err(err) => {
            eprintln!("fz: cannot serialize the report: {err}");
            ExitCode::FAILURE
        }
    }
}

/// Prints a failure list under the active discipline: one JSON object
/// under `--json`, the joined prose on stderr otherwise.
fn fail(failures: &[DoctorFailure], json: bool) -> ExitCode {
    if json {
        let payload = BarePayload {
            schema: SCHEMA,
            ok: false,
            failures: refs(failures),
        };
        return emit(&payload, ExitCode::FAILURE);
    }
    eprintln!("fz: {}", joined(failures));
    ExitCode::FAILURE
}

/// The `fz plan` CLI entry: both output disciplines.
#[must_use = "call process::exit with the returned ExitCode"]
pub fn plan_cli(
    manifest_path: &Path,
    migrations_dir: &Path,
    json: bool,
    non_interactive: bool,
) -> ExitCode {
    match plan(manifest_path, migrations_dir) {
        Ok(outcome) => {
            if json {
                let payload = PlanPayload {
                    schema: SCHEMA,
                    ok: true,
                    failures: Vec::new(),
                    digest: &outcome.digest,
                    content: &outcome.content,
                    baseline: &outcome.baseline,
                };
                return emit(&payload, ExitCode::SUCCESS);
            }
            println!(
                "fz plan: {} (env: {})",
                outcome.content.state.venture, outcome.content.state.env
            );
            println!("  digest:     {}", outcome.digest);
            println!(
                "  baseline:   {} ({})",
                outcome.baseline.source,
                or_none(&outcome.baseline.modules)
            );
            println!("  added:      {}", or_none(&outcome.content.modules_added));
            println!(
                "  removed:    {}",
                or_none(&outcome.content.modules_removed)
            );
            let mut config = Vec::new();
            for key in &outcome.content.config_added {
                config.push(format!("+{key}"));
            }
            for key in &outcome.content.config_removed {
                config.push(format!("-{key}"));
            }
            for key in &outcome.content.config_changed {
                config.push(format!("~{key}"));
            }
            println!(
                "  config:     {}",
                if config.is_empty() {
                    "(unchanged)".to_owned()
                } else {
                    config.join(" ")
                }
            );
            println!(
                "  migrations: not collected for {} / orphaned {}",
                or_none(&outcome.content.state.migrations.not_collected),
                or_none(&outcome.content.state.migrations.orphaned)
            );
            for capability in &outcome.content.capabilities {
                println!(
                    "  needs:      {} ({} module, requires {}, {})",
                    capability.slug,
                    capability.tier,
                    or_none(&capability.requires),
                    capability.via
                );
            }
            if !non_interactive {
                println!();
                println!("next:");
                println!(
                    "  fz deploy --plan {}   # apply exactly this plan",
                    outcome.digest
                );
            }
            ExitCode::SUCCESS
        }
        Err(failures) => fail(&failures, json),
    }
}

/// `"(none)"` for an empty list, the comma-joined list otherwise.
fn or_none(items: &[String]) -> String {
    if items.is_empty() {
        "(none)".to_owned()
    } else {
        items.join(", ")
    }
}

/// The `fz deploy` CLI entry: both output disciplines.
#[must_use = "call process::exit with the returned ExitCode"]
pub fn deploy_cli(
    approved: Option<&str>,
    manifest_path: &Path,
    migrations_dir: &Path,
    consent: Consent,
    json: bool,
    non_interactive: bool,
) -> ExitCode {
    match deploy(approved, manifest_path, migrations_dir, consent) {
        Ok(outcome) => {
            if json {
                let payload = DeployPayload {
                    schema: SCHEMA,
                    ok: true,
                    failures: Vec::new(),
                    changed: outcome.changed,
                    digest: &outcome.digest,
                    venture: &outcome.content.state.venture,
                    env: &outcome.content.state.env,
                    modules_added: &outcome.content.modules_added,
                    modules_removed: &outcome.content.modules_removed,
                    record: outcome.record_path.display().to_string(),
                };
                return emit(&payload, ExitCode::SUCCESS);
            }
            if !outcome.changed {
                println!(
                    "fz deploy: nothing to do — plan {} is already the recorded deployment",
                    outcome.digest
                );
                return ExitCode::SUCCESS;
            }
            println!(
                "fz deploy: {} (env: {})",
                outcome.content.state.venture, outcome.content.state.env
            );
            println!("  digest:     {}", outcome.digest);
            println!("  added:      {}", or_none(&outcome.content.modules_added));
            println!(
                "  removed:    {}",
                or_none(&outcome.content.modules_removed)
            );
            println!("  record:     {}", outcome.record_path.display());
            if !non_interactive {
                println!();
                println!("next (needs a human or credentials fz does not hold):");
                println!(
                    "  fz migrations collect        # materialise the wrangler migration files"
                );
                println!("  fz doctor                    # harness validity, production rules");
                println!("  worker-build --release       # compile the venture to wasm");
                println!("  wrangler deploy              # stand up the Worker + D1");
            }
            ExitCode::SUCCESS
        }
        Err(failures) => fail(&failures, json),
    }
}

/// The `fz add` CLI entry: both output disciplines.
#[must_use = "call process::exit with the returned ExitCode"]
pub fn add_cli(module: &str, manifest_path: &Path, json: bool, non_interactive: bool) -> ExitCode {
    match add(module, manifest_path) {
        Ok(outcome) => {
            if json {
                let payload = AddPayload {
                    schema: SCHEMA,
                    ok: true,
                    failures: Vec::new(),
                    changed: outcome.changed,
                    module: &outcome.module,
                    manifest: outcome.manifest.display().to_string(),
                };
                return emit(&payload, ExitCode::SUCCESS);
            }
            if outcome.changed {
                println!(
                    "fz add: added `{}` to {} — the desired composition only; nothing was \
                     deployed, provisioned or migrated",
                    outcome.module,
                    outcome.manifest.display()
                );
                if !non_interactive {
                    println!();
                    println!("next:");
                    println!("  fz plan --json   # see what this would change and get its digest");
                }
            } else {
                println!(
                    "fz add: `{}` is already in {} — nothing changed",
                    outcome.module,
                    outcome.manifest.display()
                );
            }
            ExitCode::SUCCESS
        }
        Err(failures) => fail(&failures, json),
    }
}

/// The `fz init` CLI entry: both output disciplines.
#[must_use = "call process::exit with the returned ExitCode"]
pub fn init_cli(
    name: &str,
    host: &str,
    manifest_path: &Path,
    force: bool,
    json: bool,
    non_interactive: bool,
) -> ExitCode {
    match init(name, host, manifest_path, force) {
        Ok(path) => {
            if json {
                let payload = InitPayload {
                    schema: SCHEMA,
                    ok: true,
                    failures: Vec::new(),
                    name,
                    host,
                    manifest: path.display().to_string(),
                };
                return emit(&payload, ExitCode::SUCCESS);
            }
            println!(
                "fz init: wrote {} (venture {name}, host {host}, no modules yet)",
                path.display()
            );
            if !non_interactive {
                println!();
                println!("next:");
                println!(
                    "  fz add <module>   # grow the desired composition, one module at a time"
                );
            }
            ExitCode::SUCCESS
        }
        Err(failures) => fail(&failures, json),
    }
}

/// The `fz verify` CLI entry: both output disciplines. The JSON shape
/// is the doctor's, byte for byte.
#[must_use = "call process::exit with the returned ExitCode"]
pub fn verify_cli(manifest_path: &Path, migrations_dir: &Path, json: bool) -> ExitCode {
    let outcome = verify(manifest_path, migrations_dir);
    if json {
        match outcome.report.render_json() {
            Ok(payload) => {
                println!("{payload}");
                return if outcome.report.ok() {
                    ExitCode::SUCCESS
                } else {
                    ExitCode::FAILURE
                };
            }
            Err(err) => {
                eprintln!("fz: cannot serialize the report: {err}");
                return ExitCode::FAILURE;
            }
        }
    }
    if outcome.report.ok() {
        match outcome.digest {
            Some(digest) => println!(
                "fz verify: the recorded deployment matches the manifest (digest {digest})"
            ),
            None => println!("fz verify: no problems found"),
        }
        ExitCode::SUCCESS
    } else {
        eprintln!("fz: {}", joined(&outcome.report.failures));
        ExitCode::FAILURE
    }
}

/// Routes the workflow commands — the ones that need no compiled-in
/// harness — or `None` for every other command.
pub(crate) fn dispatch(command: &crate::Command) -> Option<ExitCode> {
    match command {
        crate::Command::Plan {
            manifest,
            migrations,
            json,
            non_interactive,
        } => Some(plan_cli(manifest, migrations, *json, *non_interactive)),
        crate::Command::Deploy {
            plan,
            manifest,
            migrations,
            i_am_deploying_to_production,
            i_am_removing_modules,
            json,
            non_interactive,
        } => Some(deploy_cli(
            plan.as_deref(),
            manifest,
            migrations,
            Consent {
                production: *i_am_deploying_to_production,
                removal: *i_am_removing_modules,
            },
            *json,
            *non_interactive,
        )),
        crate::Command::Add {
            module,
            manifest,
            json,
            non_interactive,
        } => Some(add_cli(module, manifest, *json, *non_interactive)),
        crate::Command::Init {
            name,
            host,
            manifest,
            force,
            json,
            non_interactive,
        } => Some(init_cli(
            name,
            host,
            manifest,
            *force,
            *json,
            *non_interactive,
        )),
        crate::Command::Verify {
            manifest,
            migrations,
            json,
            ..
        } => Some(verify_cli(manifest, migrations, *json)),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::{compute_plan, init, plan_digest, resolved_env};
    use crate::lock::Lock;
    use cratefield_core::VentureEnv;
    use cratefield_manifest::{ModuleRef, VentureManifest, builtin};
    use std::collections::BTreeMap;

    fn manifest(modules: &[&str], config: &[(&str, &str)]) -> VentureManifest {
        VentureManifest {
            name: "acme".to_owned(),
            host: "acme.factory0.dev".to_owned(),
            public_url: None,
            // Required since the manifest began refusing an empty list:
            // the harness refuses a venture with no origin, so a manifest
            // that allows one generates a venture that panics at boot.
            cors_origins: vec!["https://acme.example".to_owned()],
            modules: modules
                .iter()
                .map(|slug| ModuleRef::Slug((*slug).to_owned()))
                .collect(),
            config: config
                .iter()
                .map(|(key, value)| ((*key).to_owned(), (*value).to_owned()))
                .collect::<BTreeMap<_, _>>(),
            seed_sql: None,
            ..Default::default()
        }
    }

    #[test]
    fn env_reads_the_manifest_config_key() {
        assert_eq!(resolved_env(&manifest(&[], &[])), VentureEnv::Development);
        assert_eq!(
            resolved_env(&manifest(&[], &[("ENV", "production")])),
            VentureEnv::Production
        );
        assert_eq!(
            resolved_env(&manifest(&[], &[("ENV", "nonsense")])),
            VentureEnv::Development,
            "unrecognised values fall back to development"
        );
    }

    /// The digest is a pure function of the normalised content: the
    /// same inputs twice give the same digest, and any input change —
    /// here one config key — gives a different one.
    #[test]
    fn digest_is_stable_and_input_sensitive() {
        let catalog = builtin();
        let first = manifest(&["waitlist"], &[]);
        let set = first.resolve(&catalog).expect("resolves");
        let (content, _) = compute_plan(&first, &set, &Lock::default(), None, &catalog);
        let (again, _) = compute_plan(&first, &set, &Lock::default(), None, &catalog);
        let digest = plan_digest(&content).expect("digests");
        assert_eq!(digest, plan_digest(&again).expect("digests"));

        let changed = manifest(&["waitlist"], &[("ENV", "production")]);
        let changed_set = changed.resolve(&catalog).expect("resolves");
        let (changed_content, _) =
            compute_plan(&changed, &changed_set, &Lock::default(), None, &catalog);
        assert_ne!(
            digest,
            plan_digest(&changed_content).expect("digests"),
            "a config change must move the digest"
        );
        assert_eq!(changed_content.state.env, "production");
    }

    /// Manifest module order cannot move the digest: the content is
    /// normalised before it is hashed.
    #[test]
    fn digest_is_order_insensitive_over_the_selection() {
        let catalog = builtin();
        let a = manifest(&["waitlist", "email-signup"], &[]);
        let b = manifest(&["email-signup", "waitlist"], &[]);
        let set_a = a.resolve(&catalog).expect("resolves");
        let set_b = b.resolve(&catalog).expect("resolves");
        let (content_a, _) = compute_plan(&a, &set_a, &Lock::default(), None, &catalog);
        let (content_b, _) = compute_plan(&b, &set_b, &Lock::default(), None, &catalog);
        assert_eq!(
            plan_digest(&content_a).expect("digests"),
            plan_digest(&content_b).expect("digests")
        );
    }

    /// `fz init` had no test, and its own comment says why one was
    /// wanted: "`fz init` writing a manifest that `fz build` would reject
    /// is a first step that fails on the second". The scaffolded origin
    /// was added for that reason and nothing checked it stayed true.
    #[test]
    fn init_scaffolds_a_manifest_the_rest_of_the_toolchain_accepts() {
        let dir = cratefield_testing::TempDir::new("fz-init");
        let path = dir.path().join("venture.json");
        init("acme-signups", "acme.factory0.dev", &path, false).expect("init writes one");
        let written = std::fs::read_to_string(&path).expect("it is there");
        let manifest = VentureManifest::from_json_str(&written).expect("it parses");
        manifest.validate().expect("and it is one fz build accepts");
        assert_eq!(manifest.cors_origins, ["https://acme.factory0.dev"]);
        // The problem base (issue #557): `fz init` scaffolds the public URL
        // so the venture's error `type`s are named under its own domain
        // rather than falling back to `about:blank`.
        assert_eq!(
            manifest.public_url.as_deref(),
            Some("https://acme.factory0.dev")
        );
    }

    #[test]
    fn init_refuses_a_name_that_is_not_one_and_writes_nothing() {
        // The refusal has to come before the file: a manifest on disk
        // that cannot build is worse than no manifest, because the next
        // command reads it rather than the author's intent.
        let dir = cratefield_testing::TempDir::new("fz-init");
        let path = dir.path().join("venture.json");
        let failures = init("My Venture", "acme.factory0.dev", &path, false)
            .expect_err("a venture name is a slug");
        assert!(
            failures
                .iter()
                .any(|failure| failure.message.contains("name")),
            "{failures:?}"
        );
        assert!(!path.exists(), "a manifest that cannot build was written");
    }
}