portaki-cli 9.2.1

Portaki module CLI (portaki) — init, build, test, hosted sandbox, OCI publish and registry announcement
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
//! `portaki sdk upgrade` — move a module to another SDK version, and prove nothing broke.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::Command;

use anyhow::{bail, Context, Result};
use clap::{Parser, Subcommand};
use serde::Deserialize;
use toml_edit::{DocumentMut, Item, Value};

use crate::commands::dev;
use crate::{ui, workspace};

/// The crates that move up together. The SDK publishes them at the same version, and mixing two
/// would compile a module against the macros of one generation and the runtime of another.
const SDK_FAMILY: [&str; 4] = [
    "portaki-sdk",
    "portaki-sdk-macros",
    "portaki-connectors",
    "portaki-test-utils",
];

#[derive(Debug, Parser)]
/// Arguments for `portaki sdk`.
pub struct SdkArgs {
    #[command(subcommand)]
    pub command: SdkCommand,
}

#[derive(Debug, Subcommand)]
pub enum SdkCommand {
    /// Move the module to another SDK version, then check it still builds, passes and renders.
    Upgrade(UpgradeArgs),
}

#[derive(Debug, Parser)]
/// Arguments for `portaki sdk upgrade`.
pub struct UpgradeArgs {
    /// Target version. Defaults to the latest stable release the platform serves.
    #[arg(long)]
    pub to: Option<String>,
    /// Skip the sandbox render comparison (build, tests and lint still run).
    #[arg(long)]
    pub no_render: bool,
    /// Treat a changed render as a failure, not only a surface that stopped rendering.
    #[arg(long)]
    pub strict: bool,
    /// Alias of the global --api, kept for older scripts.
    #[arg(long, hide = true)]
    pub url: Option<String>,
    /// Build, test and lint against the new version locally, then put every file it changed
    /// back. Touches no sandbox: the renders are not compared.
    #[arg(long)]
    pub dry_run: bool,
    #[command(flatten)]
    pub modules: workspace::ModuleArgs,
}

pub async fn run(args: SdkArgs) -> Result<()> {
    let SdkCommand::Upgrade(upgrade) = args.command;
    ui::warn(crate::tr!(
        "portaki sdk upgrade is now portaki upgrade — use that from now on",
        "portaki sdk upgrade devient portaki upgrade — utilisez désormais ce nom"
    ));
    self::upgrade(upgrade).await
}

/// Runs `portaki upgrade`.
pub async fn upgrade(upgrade: UpgradeArgs) -> Result<()> {
    // With no flag, the current directory decides, as before: from the root of a
    // monorepo, every module moves together when the workspace fixes the version.
    if upgrade.modules.module.is_none() && !upgrade.modules.all {
        return run_upgrade(&upgrade).await;
    }
    // One module after another: when the version is inherited from the workspace, the
    // first moves everyone and the ones after it say "already resolves".
    for member in upgrade.modules.resolve()? {
        workspace::enter(&member)?;
        run_upgrade(&upgrade)
            .await
            .with_context(|| format!("module {}", member.id))?;
    }
    Ok(())
}

// ─── Where the version is declared ───────────────────────────────────────────

/// The files that carry the version requirement, and what changing it there touches.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Declaration {
    pub files: Vec<PathBuf>,
    /// The workspace fixes the version for everyone: inherited (`workspace = true`), or pinned
    /// at the root and copied into each module. Moving one without the others would break the
    /// repository.
    pub workspace_wide: bool,
}

/// Where `portaki-sdk` is required from, read in the module's own `Cargo.toml`.
///
/// Three layouts. `portaki-sdk = { workspace = true }` sends the question to the workspace root.
/// A root that pins the family in `[workspace.dependencies]` while each module writes its own
/// number (portaki-modules: release-please attributes a bump per module path) moves as one —
/// the root and every member that declares a number. A lone module moves alone.
///
/// @param workspace_toml the root `Cargo.toml`, when the module sits in a workspace
/// @param members each member's root and `Cargo.toml`
pub fn locate_declaration(
    module_toml: &str,
    module_root: &Path,
    workspace_root: &Path,
    workspace_toml: Option<&str>,
    members: &[(PathBuf, String)],
) -> Result<Declaration> {
    let doc: DocumentMut = module_toml.parse().context("parse Cargo.toml")?;
    let sdk = doc
        .get("dependencies")
        .and_then(|deps| deps.get("portaki-sdk"))
        .context("this crate does not depend on portaki-sdk")?;
    let inherited = sdk
        .as_table_like()
        .and_then(|table| table.get("workspace"))
        .and_then(|value| value.as_bool())
        .unwrap_or(false);
    let root_pins = workspace_toml.is_some_and(pins_the_family);
    if !inherited && !root_pins {
        return Ok(Declaration {
            files: vec![module_root.join("Cargo.toml")],
            workspace_wide: false,
        });
    }
    let mut files = vec![workspace_root.join("Cargo.toml")];
    for (root, toml) in members {
        if declares_a_number(toml) {
            files.push(root.join("Cargo.toml"));
        }
    }
    Ok(Declaration {
        files,
        workspace_wide: true,
    })
}

/// Does the root pin a member of the family in `[workspace.dependencies]`?
fn pins_the_family(workspace_toml: &str) -> bool {
    let Ok(doc) = workspace_toml.parse::<DocumentMut>() else {
        return false;
    };
    doc.get("workspace")
        .and_then(|workspace| workspace.get("dependencies"))
        .and_then(Item::as_table_like)
        .is_some_and(|deps| SDK_FAMILY.iter().any(|name| deps.contains_key(name)))
}

/// A member that writes a number for the family itself — not `workspace = true`.
fn declares_a_number(member_toml: &str) -> bool {
    bump_requirements(member_toml, "0.0.0").is_ok_and(|(_, changed)| !changed.is_empty())
}

/// Rewrites every SDK-family requirement to `target`, keeping the file as it was otherwise.
///
/// Comments, ordering and other keys survive: this is the author's `Cargo.toml`, not a file the
/// CLI owns. An inline table keeps its other keys (`features`, `default-features`…); only its
/// `version` moves. An entry inherited from the workspace is left alone — it has no number here.
/// A root reads `[workspace.dependencies]`, a module its own dependency tables: one pass covers both.
///
/// @returns the new file and the crates it changed, in family order
pub fn bump_requirements(toml: &str, target: &str) -> Result<(String, Vec<String>)> {
    let mut doc: DocumentMut = toml.parse().context("parse Cargo.toml")?;
    let sections: [&[&str]; 4] = [
        &["workspace", "dependencies"],
        &["dependencies"],
        &["dev-dependencies"],
        &["build-dependencies"],
    ];
    let mut changed = Vec::new();
    for path in sections {
        let Some(table) = walk_mut(doc.as_item_mut(), path) else {
            continue;
        };
        for name in SDK_FAMILY {
            let Some(entry) = table.get_mut(name) else {
                continue;
            };
            if set_version(entry, target) && !changed.iter().any(|c: &String| c == name) {
                changed.push(name.to_string());
            }
        }
    }
    Ok((doc.to_string(), changed))
}

fn walk_mut<'a>(item: &'a mut Item, path: &[&str]) -> Option<&'a mut dyn toml_edit::TableLike> {
    let mut current = item;
    for key in path {
        current = current.as_table_like_mut()?.get_mut(key)?;
    }
    current.as_table_like_mut()
}

fn set_version(entry: &mut Item, target: &str) -> bool {
    if entry.as_value().is_some_and(Value::is_str) {
        return entry
            .as_value_mut()
            .is_some_and(|value| replace_requirement(value, target));
    }
    let Some(table) = entry.as_table_like_mut() else {
        return false;
    };
    if table.get("workspace").and_then(|v| v.as_bool()) == Some(true) {
        return false;
    }
    table
        .get_mut("version")
        .and_then(Item::as_value_mut)
        .is_some_and(|value| replace_requirement(value, target))
}

/// Swaps the number, keeps the operator: `=2.2.0` pinned the SDK on purpose, and must stay
/// pinned at the new version — dropping the `=` would silently turn it into a caret range.
fn replace_requirement(value: &mut Value, target: &str) -> bool {
    let Some(current) = value.as_str() else {
        return false;
    };
    let operator: String = current
        .chars()
        .take_while(|c| matches!(c, '=' | '^' | '~' | ' '))
        .collect();
    let decor = value.decor().clone();
    *value = Value::from(format!("{}{target}", operator.trim_end()));
    *value.decor_mut() = decor;
    true
}

// ─── Versions ────────────────────────────────────────────────────────────────

#[derive(Debug, Deserialize)]
pub struct SdkRelease {
    pub version: String,
    pub channel: String,
    #[serde(default = "yes")]
    pub supported: bool,
}

fn yes() -> bool {
    true
}

pub(crate) fn parse_version(version: &str) -> Option<(u64, u64, u64)> {
    let core = version.trim().split(['-', '+']).next()?;
    let mut parts = core.split('.').map(|part| part.parse::<u64>().ok());
    Some((
        parts.next()??,
        parts.next().flatten().unwrap_or(0),
        parts.next().flatten().unwrap_or(0),
    ))
}

/// The latest supported stable release — computed, not read at the head of the list, whose
/// order is promised nowhere. Numeric: as text, `10.0` would sort before `2.0`.
pub fn latest_stable(releases: &[SdkRelease]) -> Option<String> {
    releases
        .iter()
        .filter(|release| release.channel == "stable" && release.supported)
        .filter_map(|release| parse_version(&release.version).map(|v| (v, &release.version)))
        .max_by_key(|(parsed, _)| *parsed)
        .map(|(_, version)| version.clone())
}

/// What to say when the lock resolved something other than the version asked for.
///
/// A plain `"3.0.1"` requirement is a caret: once 3.1.0 is out, it resolves 3.1.0. That is
/// usually what one wants — but not what one typed, and the commit message must not claim
/// otherwise.
pub fn resolution_note(target: &str, resolved: &str) -> Option<String> {
    let (wanted, got) = (parse_version(target)?, parse_version(resolved)?);
    if wanted == got {
        return None;
    }
    Some(if got > wanted {
        format!(
            "the requirement {target} resolved {resolved}, the newest compatible release — \
             write ={target} to hold {target} instead"
        )
    } else {
        format!("the requirement {target} resolved {resolved}, below what was asked")
    })
}

// ─── Renders ─────────────────────────────────────────────────────────────────

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct DeclaredSurface {
    id: String,
}

#[derive(Debug, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Rendered {
    pub rendered: bool,
    #[serde(default)]
    pub tree: String,
    #[serde(default)]
    pub error_code: String,
}

/// What a version upgrade did to a surface.
#[derive(Debug, PartialEq, Eq)]
pub enum RenderOutcome {
    Same,
    /// It still renders, differently — not necessarily a fault: a primitive may have gained a
    /// field. `--strict` makes it one.
    Changed {
        before: usize,
        after: usize,
    },
    /// It used to render, it does not any more. This is the breakage the command exists to find.
    Broke {
        error: String,
    },
    /// It was not rendering before either — the upgrade has nothing to do with it.
    StillFailing,
    /// It was not rendering, now it does — rare, and worth knowing.
    Fixed,
}

pub fn compare_render(before: &Rendered, after: &Rendered) -> RenderOutcome {
    match (before.rendered, after.rendered) {
        (true, false) => RenderOutcome::Broke {
            error: if after.error_code.is_empty() {
                "sans motif".into()
            } else {
                after.error_code.clone()
            },
        },
        (false, false) => RenderOutcome::StillFailing,
        (false, true) => RenderOutcome::Fixed,
        (true, true) => {
            let parse = |raw: &str| serde_json::from_str::<serde_json::Value>(raw).ok();
            match (parse(&before.tree), parse(&after.tree)) {
                // serde_json equality ignores key order: a reordered object has not changed
                // its render.
                (Some(a), Some(b)) if a == b => RenderOutcome::Same,
                (Some(a), Some(b)) => RenderOutcome::Changed {
                    before: nodes(&a),
                    after: nodes(&b),
                },
                _ if before.tree == after.tree => RenderOutcome::Same,
                _ => RenderOutcome::Changed {
                    before: 0,
                    after: 0,
                },
            }
        }
    }
}

/// The SDUI nodes of a tree — objects that carry a `type`. A cheap size to report a change by.
fn nodes(value: &serde_json::Value) -> usize {
    match value {
        serde_json::Value::Object(map) => {
            usize::from(map.contains_key("type")) + map.values().map(nodes).sum::<usize>()
        }
        serde_json::Value::Array(items) => items.iter().map(nodes).sum(),
        _ => 0,
    }
}

/// A failing conformance check.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FailingCheck {
    pub id: String,
    pub detail: String,
}

/// What the sandbox said about the module before the upgrade.
struct Baseline {
    renders: BTreeMap<String, Rendered>,
    /// The checks that were already failing — the upgrade has nothing to do with them.
    failing: std::collections::BTreeSet<String>,
}

/// The conformance failures after the upgrade: the ones it caused, and the ones from before.
///
/// Same rule as for the renders ([`RenderOutcome::StillFailing`]): a check that was already
/// failing is not a regression. Without it, a module that declares an e-mail without a command
/// simply could not move to a newer SDK any more — the command restored Cargo.toml, blaming the
/// upgrade for a fault it had not committed.
pub fn split_failures(
    before: &std::collections::BTreeSet<String>,
    after: Vec<FailingCheck>,
) -> (Vec<FailingCheck>, Vec<FailingCheck>) {
    after
        .into_iter()
        .partition(|check| !before.contains(&check.id))
}

// ─── The sequence ────────────────────────────────────────────────────────────

struct Backup {
    files: Vec<(PathBuf, Option<String>)>,
}

impl Backup {
    fn take(paths: &[PathBuf]) -> Self {
        Self {
            files: paths
                .iter()
                .map(|p| (p.clone(), std::fs::read_to_string(p).ok()))
                .collect(),
        }
    }

    fn restore(&self) -> Result<()> {
        for (path, content) in &self.files {
            match content {
                Some(content) => std::fs::write(path, content)
                    .with_context(|| format!("restore {}", path.display()))?,
                None => {
                    let _ = std::fs::remove_file(path);
                }
            }
        }
        Ok(())
    }
}

struct Sandbox {
    base_url: String,
    auth_url: String,
    module_id: String,
    token: String,
    session: crate::dev_session::DevSession,
}

impl Sandbox {
    async fn deploy_and_render(
        &mut self,
        module_root: &Path,
    ) -> Result<BTreeMap<String, Rendered>> {
        let wasm_path = crate::oci::pack::find_wasm_artifact(module_root, &self.module_id)?;
        let wasm =
            std::fs::read(&wasm_path).with_context(|| format!("read {}", wasm_path.display()))?;
        let manifest = dev::sandbox_manifest(module_root)?;
        let migrations = dev::migrations_bundle(module_root)?;
        let deploying = ui::step(format!("deploying {} to the sandbox", self.module_id));
        let deployed = match dev::deploy(
            &self.base_url,
            &self.module_id,
            &self.token,
            &wasm,
            &manifest,
            migrations.as_deref(),
            self.session.session_id(),
        )
        .await
        {
            Ok(deployed) => deployed,
            // On a 401 only: renewing on any failure at all rotated the token for nothing, and
            // every rotation too many is one more race with the account's other `portaki`
            // processes.
            Err(failure) if failure.is::<dev::Unauthorized>() => {
                self.token = dev::renew(&self.auth_url, &self.token).await?;
                dev::deploy(
                    &self.base_url,
                    &self.module_id,
                    &self.token,
                    &wasm,
                    &manifest,
                    migrations.as_deref(),
                    self.session.session_id(),
                )
                .await?
            }
            Err(failure) => {
                deploying.abandon();
                return Err(failure);
            }
        };
        deploying.done(format!("deployed {}", dev::short(&deployed.digest)));

        let client = crate::http::client();
        let surfaces: Vec<DeclaredSurface> = dev::read_json(
            client
                .get(format!(
                    "{}/dev/v1/modules/{}/surfaces",
                    self.base_url, self.module_id
                ))
                .bearer_auth(&self.token)
                .send()
                .await
                .context("list the declared surfaces")?,
        )
        .await?;
        let mut rendered = BTreeMap::new();
        for surface in surfaces {
            let rendering = ui::step(format!("rendering {}", surface.id));
            let result: Rendered = dev::read_json(
                client
                    .post(format!(
                        "{}/dev/v1/modules/{}/surfaces/{}/render",
                        self.base_url, self.module_id, surface.id
                    ))
                    .bearer_auth(&self.token)
                    .send()
                    .await
                    .with_context(|| format!("render {}", surface.id))?,
            )
            .await?;
            if result.rendered {
                rendering.done(format!("{} rendered", surface.id));
            } else {
                rendering.done(format!(
                    "{} did not render ({})",
                    surface.id, result.error_code
                ));
            }
            rendered.insert(surface.id, result);
        }
        Ok(rendered)
    }

    /// The failing conformance checks — the ones that would lock a stable publication.
    async fn failing_checks(&self) -> Result<Vec<FailingCheck>> {
        #[derive(Deserialize)]
        struct Report {
            checks: Vec<Check>,
        }
        #[derive(Deserialize)]
        struct Check {
            id: String,
            status: String,
            #[serde(default)]
            detail: String,
        }
        let report: Report = dev::read_json(
            crate::http::client()
                .get(format!(
                    "{}/dev/v1/modules/{}/conformance",
                    self.base_url, self.module_id
                ))
                .bearer_auth(&self.token)
                .send()
                .await
                .context("read the conformance checklist")?,
        )
        .await?;
        Ok(report
            .checks
            .into_iter()
            .filter(|check| check.status == "FAIL")
            .map(|check| FailingCheck {
                id: check.id,
                detail: check.detail,
            })
            .collect())
    }
}

#[derive(Debug, Deserialize)]
struct Metadata {
    workspace_root: PathBuf,
    /// Where `cargo` writes, according to the configuration seen from the current directory.
    target_directory: PathBuf,
    packages: Vec<MetadataPackage>,
    workspace_members: Vec<String>,
}

#[derive(Debug, Deserialize)]
struct MetadataPackage {
    id: String,
    name: String,
    version: String,
    manifest_path: PathBuf,
}

fn cargo_metadata(module_root: &Path) -> Result<Metadata> {
    let output = Command::new("cargo")
        .args(["metadata", "--format-version", "1"])
        .current_dir(module_root)
        .output()
        .context("run cargo metadata")?;
    if !output.status.success() {
        bail!(
            "cargo metadata failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }
    serde_json::from_slice(&output.stdout).context("parse cargo metadata")
}

fn cargo(module_root: &Path, label: &str, args: &[&str]) -> Result<()> {
    let mut cmd = Command::new("cargo");
    cmd.current_dir(module_root).args(args);
    ui::command(label, &mut cmd).with_context(|| format!("cargo {}", args.join(" ")))
}

async fn run_upgrade(args: &UpgradeArgs) -> Result<()> {
    ui::header(
        "portaki upgrade",
        "Move to another SDK version — then build, test, lint and render to prove nothing broke.",
    );
    let cwd = std::env::current_dir().context("current_dir")?;
    let (module_root, from_repository_root) = anchor(&cwd)?;
    let module_id = dev::read_module_id(&module_root)?;
    if from_repository_root {
        ui::field(
            "anchor",
            format!("{module_id} (repository root — every module moves)"),
        );
    }
    let base_url = crate::profile::api_url(args.url.as_deref());

    let metadata = cargo_metadata(&module_root)?;
    let current = metadata
        .packages
        .iter()
        .find(|package| package.name == "portaki-sdk")
        .map(|package| package.version.clone())
        .context("portaki-sdk is not in the dependency graph")?;

    let target = match &args.to {
        Some(version) => version.trim().to_string(),
        None => {
            let reading = ui::step("reading the SDK releases the platform serves");
            let releases: Vec<SdkRelease> = dev::read_json(
                crate::http::client()
                    .get(format!("{base_url}/registry/v1/sdk-releases"))
                    .send()
                    .await
                    .context("read the SDK releases")?,
            )
            .await?;
            let latest =
                latest_stable(&releases).context("the platform lists no stable SDK release")?;
            reading.done(format!("latest stable: {latest}"));
            latest
        }
    };
    ui::field("current", &current);
    ui::field("target", &target);
    if parse_version(&current) == parse_version(&target) {
        ui::success(format!(
            "{module_id} already resolves portaki-sdk {current}"
        ));
        return Ok(());
    }

    let module_toml =
        std::fs::read_to_string(module_root.join("Cargo.toml")).context("read Cargo.toml")?;
    let workspace_toml = std::fs::read_to_string(metadata.workspace_root.join("Cargo.toml")).ok();
    let member_tomls: Vec<(PathBuf, String)> = workspace::members(&metadata.workspace_root)
        .into_iter()
        .filter_map(|member| {
            let toml = std::fs::read_to_string(member.root.join("Cargo.toml")).ok()?;
            Some((member.root, toml))
        })
        .collect();
    let declaration = locate_declaration(
        &module_toml,
        &module_root,
        &metadata.workspace_root,
        workspace_toml.as_deref(),
        &member_tomls,
    )?;
    ui::field(
        "declared in",
        match declaration.files.as_slice() {
            [only] => only.display().to_string(),
            many => format!("{} Cargo.toml (workspace root and modules)", many.len()),
        },
    );
    if declaration.workspace_wide {
        ui::warn(format!(
            "the workspace fixes the SDK for every module: the {} members move together, and all of them are built and tested",
            metadata.workspace_members.len()
        ));
    }

    let members = verified_members(
        &declaration,
        &metadata.workspace_root,
        &module_root,
        &module_id,
    );

    let mut sandbox = if let Some(reason) = no_sandbox(args, from_repository_root) {
        ui::skipped(reason);
        None
    } else {
        let token = crate::auth::access_token(&base_url)
            .context("sign in with `portaki login`, or pass --no-render")?;
        let auth_url = crate::profile::api_url(args.url.as_deref());
        let session = crate::dev_session::start(&base_url, &auth_url, &module_id, &token).await?;
        Some(Sandbox {
            base_url: base_url.clone(),
            auth_url,
            module_id: module_id.clone(),
            token,
            session,
        })
    };

    let baseline = match sandbox.as_mut() {
        Some(sandbox) => {
            ui::section(&format!("before — portaki-sdk {current}"));
            // A current version that no longer builds is precisely a reason to upgrade: often
            // the code is already waiting for the next one. What is lost is the render
            // comparison, not the upgrade — build, tests and lint still judge it.
            match take_baseline(sandbox, &module_root).await {
                Ok(baseline) => Some(baseline),
                Err(failure) => {
                    ui::warn(format!(
                        "portaki-sdk {current} does not build or render here — upgrading without a render comparison"
                    ));
                    ui::detail(format!("{failure:#}"));
                    None
                }
            }
        }
        None => None,
    };

    ui::section(&format!("after — portaki-sdk {target}"));
    let lock = metadata.workspace_root.join("Cargo.lock");
    let manifests = module_manifests(&metadata, &declaration, &module_root);
    let backup = Backup::take(
        &declaration
            .files
            .iter()
            .cloned()
            .chain([lock])
            .chain(manifests.iter().cloned())
            .collect::<Vec<_>>(),
    );

    let outcome = upgrade_and_verify(
        args,
        &module_root,
        &declaration,
        &metadata,
        &members,
        &target,
        sandbox.as_mut(),
        baseline.as_ref(),
    )
    .await;
    // The verification steps into each module: come back to where we started from.
    std::env::set_current_dir(&cwd).context("return to the starting directory")?;
    let subject = subject(&module_id, members.len());

    if let Some(sandbox) = &sandbox {
        sandbox.session.release().now().await;
    }
    if args.dry_run {
        backup.restore()?;
    }
    match outcome {
        Ok(resolved) if args.dry_run => {
            ui::blank();
            ui::success(format!(
                "{subject} would move to portaki-sdk {resolved} — dry run, nothing was changed"
            ));
            ui::detail(
                "built, tested and linted locally; the sandbox renders were not compared — \
                 drop --dry-run to compare them",
            );
            Ok(())
        }
        Ok(resolved) => {
            ui::blank();
            // The resolved version, not the target: `"3.0.1"` is a caret, and resolves 3.1.0
            // as soon as 3.1.0 exists. Announcing the target would have committed a false
            // message.
            let verb = if members.len() > 1 { "are" } else { "is" };
            ui::success(format!("{subject} {verb} on portaki-sdk {resolved}"));
            // When inherited, the change is at the root: a `git diff` run from the module would
            // only show its own manifest, not those of the other members.
            let review = if declaration.workspace_wide {
                format!("git -C {} diff", metadata.workspace_root.display())
            } else {
                "git diff Cargo.toml Cargo.lock portaki.module.json".to_string()
            };
            ui::next(&[
                ("review", &review),
                (
                    "commit",
                    &format!("chore(deps): bump portaki-sdk to {resolved}"),
                ),
            ]);
            Ok(())
        }
        Err(failure) => {
            if !args.dry_run {
                backup.restore()?;
            }
            ui::blank();
            ui::failure("the upgrade broke something — every file it changed is restored");
            if baseline.is_some() {
                ui::advice("the sandbox now holds the attempted build: run `portaki dev` to put yours back");
            }
            Err(failure)
        }
    }
}

/// Why the sandbox is left untouched, or `None` to compare the renders.
///
/// `--dry-run` deploys nothing there and takes no lease on it: a trial run that overwrites
/// someone else's sandbox is not a trial run.
fn no_sandbox(args: &UpgradeArgs, from_repository_root: bool) -> Option<&'static str> {
    if args.dry_run {
        Some("render comparison skipped (--dry-run) — the sandbox is left untouched")
    } else if args.no_render {
        Some("render comparison skipped (--no-render)")
    } else if from_repository_root {
        // A sandbox session targets one module: from the root, none of them stands out.
        Some("render comparison skipped — run from a module directory to compare its renders")
    } else {
        None
    }
}

/// The module to start from, and whether we are at the root of a monorepo.
///
/// From the root, the first module will do: the version there is inherited from the workspace, so
/// it is the same for everyone, and that is all this module is there to find.
fn anchor(cwd: &Path) -> Result<(PathBuf, bool)> {
    if crate::manifest::source::is_module(cwd) {
        return Ok((cwd.to_path_buf(), false));
    }
    let members = workspace::members(cwd);
    match members.first() {
        Some(first) => Ok((first.root.clone(), true)),
        None => anyhow::bail!(
            "no module here, and no modules/*/ below — run from a module or a monorepo root"
        ),
    }
}

/// The modules to build and lint: every module of the repository when the version is inherited
/// from the workspace, the single module otherwise.
fn verified_members(
    declaration: &Declaration,
    workspace_root: &Path,
    module_root: &Path,
    module_id: &str,
) -> Vec<workspace::Member> {
    let all = if declaration.workspace_wide {
        workspace::members(workspace_root)
    } else {
        Vec::new()
    };
    if all.is_empty() {
        vec![workspace::Member {
            id: module_id.to_string(),
            root: module_root.to_path_buf(),
        }]
    } else {
        all
    }
}

/// "weather" or "21 modules" — the sentence says how many moved.
fn subject(module_id: &str, count: usize) -> String {
    if count > 1 {
        format!("{count} modules")
    } else {
        module_id.to_string()
    }
}

/// The `portaki.module.json` files the upgrade concerns: every member's when the version comes
/// from the workspace, the module's own otherwise.
fn module_manifests(
    metadata: &Metadata,
    declaration: &Declaration,
    module_root: &Path,
) -> Vec<PathBuf> {
    let roots: Vec<PathBuf> = if declaration.workspace_wide {
        metadata
            .packages
            .iter()
            .filter(|package| metadata.workspace_members.contains(&package.id))
            .filter_map(|package| package.manifest_path.parent().map(Path::to_path_buf))
            .collect()
    } else {
        vec![module_root.to_path_buf()]
    };
    roots
        .into_iter()
        .map(|root| root.join("portaki.module.json"))
        .filter(|path| path.is_file())
        .collect()
}

/// Replaces the value of `requiresModuleSdk` without touching the rest of the file — read back
/// and rewritten by serde, a manifest would lose its ordering and its formatting in the diff.
/// `None` when the field is not there: the build then writes it itself.
pub fn set_required_sdk(raw: &str, version: &str) -> Option<String> {
    const KEY: &str = "\"requiresModuleSdk\"";
    let after_key = raw.find(KEY)? + KEY.len();
    let colon = after_key + raw[after_key..].find(':')?;
    let open = colon + 1 + raw[colon + 1..].find('"')?;
    let close = open + 1 + raw[open + 1..].find('"')?;
    Some(format!("{}{version}{}", &raw[..=open], &raw[close..]))
}

async fn take_baseline(sandbox: &mut Sandbox, module_root: &Path) -> Result<Baseline> {
    dev::build(module_root)?;
    crate::commands::build::refresh_outputs(module_root)?;
    let renders = sandbox.deploy_and_render(module_root).await?;
    let failing = sandbox.failing_checks().await?;
    for check in &failing {
        ui::detail(format!(
            "conformance {}: failing before the upgrade — {}",
            check.id, check.detail
        ));
    }
    Ok(Baseline {
        renders,
        failing: failing.into_iter().map(|check| check.id).collect(),
    })
}

// Every argument is a decision the caller has already taken (declaration, members, sandbox):
// grouping them would only move the list into a struct read in a single place.
#[allow(clippy::too_many_arguments)]
async fn upgrade_and_verify(
    args: &UpgradeArgs,
    module_root: &Path,
    declaration: &Declaration,
    metadata: &Metadata,
    members: &[workspace::Member],
    target: &str,
    sandbox: Option<&mut Sandbox>,
    baseline: Option<&Baseline>,
) -> Result<String> {
    let mut changed: Vec<String> = Vec::new();
    let mut touched = 0;
    for file in &declaration.files {
        let original =
            std::fs::read_to_string(file).with_context(|| format!("read {}", file.display()))?;
        let (bumped, in_file) = bump_requirements(&original, target)?;
        if in_file.is_empty() {
            continue;
        }
        std::fs::write(file, bumped).with_context(|| format!("write {}", file.display()))?;
        touched += 1;
        for name in in_file {
            if !changed.contains(&name) {
                changed.push(name);
            }
        }
    }
    if changed.is_empty() {
        bail!("no SDK requirement with a version number to move");
    }
    ui::wrote(
        "requirement",
        format!("{} → {target} in {touched} Cargo.toml", changed.join(", ")),
    );

    // Only the crates the graph resolves: `cargo update -p` refuses an unknown name.
    let resolved: Vec<&str> = SDK_FAMILY
        .into_iter()
        .filter(|name| {
            metadata
                .packages
                .iter()
                .any(|package| package.name == *name)
        })
        .collect();
    let mut update = vec!["update"];
    for name in &resolved {
        update.push("-p");
        update.push(name);
    }
    cargo(module_root, "resolving the new version", &update)?;
    let resolved_version = cargo_metadata(module_root)?
        .packages
        .into_iter()
        .find(|package| package.name == "portaki-sdk")
        .map(|package| package.version)
        .context("portaki-sdk left the dependency graph")?;
    ui::field("resolved", &resolved_version);
    if let Some(note) = resolution_note(target, &resolved_version) {
        ui::warn(note);
    }

    // The build refuses a manifest announcing a version other than the one linked: without this,
    // every upgrade failed on the first module, with no advice but to edit twenty files.
    let mut aligned = 0;
    for path in &module_manifests(metadata, declaration, module_root) {
        let raw =
            std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
        if let Some(updated) = set_required_sdk(&raw, &resolved_version) {
            if updated != raw {
                std::fs::write(path, updated)
                    .with_context(|| format!("write {}", path.display()))?;
                aligned += 1;
            }
        }
    }
    if aligned > 0 {
        ui::wrote(
            "manifests",
            format!("requiresModuleSdk → {resolved_version} in {aligned} portaki.module.json"),
        );
    }

    let scope: &[&str] = if declaration.workspace_wide {
        &["--workspace"]
    } else {
        &[]
    };
    let build: Vec<&str> = ["build", "--release", "--target", "wasm32-unknown-unknown"]
        .into_iter()
        .chain(scope.iter().copied())
        .collect();
    cargo(
        module_root,
        "compiling wasm32-unknown-unknown (release)",
        &build,
    )?;
    let test: Vec<&str> = ["test"].into_iter().chain(scope.iter().copied()).collect();
    cargo(module_root, "running the tests", &test)?;
    // Outputs and lint for every module that moved, not only the one we start from: otherwise
    // the output named only it, and one believed it had moved on its own.
    for member in members {
        if members.len() > 1 {
            ui::rule(&member.id);
        }
        // The emissions are where the workspace build wrote them — not necessarily under the
        // member's `target/`, which a `.cargo/config.toml` can point elsewhere.
        crate::commands::build::refresh_outputs_from(&member.root, &metadata.target_directory)?;
        workspace::enter(member)?;
        crate::commands::lint::run(crate::commands::lint::LintArgs {
            manifest: None,
            channel: "stable".to_string(),
            modules: Default::default(),
            nested: members.len() > 1,
        })?;
    }
    std::env::set_current_dir(module_root).context("return to the module")?;

    let (Some(sandbox), Some(baseline)) = (sandbox, baseline) else {
        return Ok(resolved_version);
    };
    let after = sandbox.deploy_and_render(module_root).await?;

    let mut broken = Vec::new();
    let mut changed_renders = Vec::new();
    for (id, before) in &baseline.renders {
        let Some(now) = after.get(id) else {
            broken.push(format!("{id} is no longer declared"));
            continue;
        };
        match compare_render(before, now) {
            RenderOutcome::Same => ui::detail(format!("{id}: same render")),
            RenderOutcome::Changed { before, after } => {
                ui::warn(format!(
                    "{id}: renders differently ({before} → {after} nodes)"
                ));
                changed_renders.push(id.clone());
            }
            RenderOutcome::Broke { error } => {
                broken.push(format!("{id} stopped rendering: {error}"))
            }
            RenderOutcome::StillFailing => {
                ui::detail(format!("{id}: did not render before either"))
            }
            RenderOutcome::Fixed => ui::detail(format!("{id}: renders now, it did not before")),
        }
    }
    let (introduced, preexisting) =
        split_failures(&baseline.failing, sandbox.failing_checks().await?);
    for check in &preexisting {
        ui::detail(format!(
            "conformance {}: still failing, as before the upgrade",
            check.id
        ));
    }
    for check in introduced {
        broken.push(format!("conformance: {} — {}", check.id, check.detail));
    }
    if args.strict {
        broken.extend(
            changed_renders
                .iter()
                .map(|id| format!("{id} renders differently (--strict)")),
        );
    }
    if !broken.is_empty() {
        for line in &broken {
            ui::failure(line);
        }
        bail!("{} regression(s) after the upgrade", broken.len());
    }
    Ok(resolved_version)
}

#[cfg(test)]
mod tests {

    fn monorepo(ids: &[&str]) -> tempfile::TempDir {
        let dir = tempfile::tempdir().unwrap();
        for id in ids {
            let root = dir.path().join("modules").join(id);
            std::fs::create_dir_all(&root).unwrap();
            std::fs::write(
                root.join("portaki.module.json"),
                format!(r#"{{"id":"{id}","version":"0.1.0"}}"#),
            )
            .unwrap();
        }
        dir
    }

    /// From the root of a monorepo, one module serves as the anchor: the inherited version is
    /// the same for everyone.
    #[test]
    fn the_repository_root_anchors_on_a_module() {
        let repo = monorepo(&["weather", "nuki"]);

        let (root, from_repository_root) = anchor(repo.path()).unwrap();

        assert!(from_repository_root);
        assert_eq!(root, repo.path().join("modules/nuki"));
        let (root, from_repository_root) = anchor(&repo.path().join("modules/weather")).unwrap();
        assert!(!from_repository_root);
        assert_eq!(root, repo.path().join("modules/weather"));
        assert!(anchor(tempfile::tempdir().unwrap().path()).is_err());
    }

    /// Inherited from the workspace, every module is verified — not only the one we start from.
    #[test]
    fn an_inherited_sdk_verifies_every_module() {
        let repo = monorepo(&["weather", "nuki", "wifi-guest"]);
        let weather = repo.path().join("modules/weather");
        let inherited = Declaration {
            files: vec![repo.path().join("Cargo.toml")],
            workspace_wide: true,
        };
        let own = Declaration {
            files: vec![weather.join("Cargo.toml")],
            workspace_wide: false,
        };

        let ids = |members: Vec<workspace::Member>| {
            members
                .into_iter()
                .map(|member| member.id)
                .collect::<Vec<_>>()
        };
        assert_eq!(
            ids(verified_members(
                &inherited,
                repo.path(),
                &weather,
                "weather"
            )),
            vec!["nuki", "weather", "wifi-guest"]
        );
        assert_eq!(
            ids(verified_members(&own, repo.path(), &weather, "weather")),
            vec!["weather"]
        );
        assert_eq!(subject("weather", 1), "weather");
        assert_eq!(subject("weather", 3), "3 modules");
    }

    use super::*;

    #[test]
    fn the_required_sdk_changes_alone() {
        let raw = "{\n  \"id\": \"weather\",\n  \"requiresModuleSdk\": \"6.3.0\",\n  \"version\": \"0.3.24\"\n}\n";
        assert_eq!(
            set_required_sdk(raw, "6.4.0").unwrap(),
            raw.replace("6.3.0", "6.4.0")
        );
        assert_eq!(set_required_sdk("{\"id\": \"weather\"}", "6.4.0"), None);
    }

    #[test]
    fn a_workspace_inherited_sdk_points_at_the_workspace_root() {
        let module = "[package]\nname = \"ical-sync\"\n\n[dependencies]\nportaki-sdk = { workspace = true }\n";
        let declaration =
            locate_declaration(module, Path::new("/m/ical"), Path::new("/m"), None, &[]).unwrap();

        assert_eq!(
            declaration,
            Declaration {
                files: vec![PathBuf::from("/m/Cargo.toml")],
                workspace_wide: true
            }
        );
    }

    #[test]
    fn an_own_requirement_points_at_the_module() {
        let module = "[dependencies]\nportaki-sdk = \"2.4.0\"\n";
        let declaration =
            locate_declaration(module, Path::new("/m/ical"), Path::new("/m"), None, &[]).unwrap();

        assert!(!declaration.workspace_wide);
        assert_eq!(declaration.files, vec![PathBuf::from("/m/ical/Cargo.toml")]);
    }

    /// portaki-modules: the root pins the family and each module writes the same number (so that
    /// release-please sees a bump in every module path). `portaki sdk upgrade` once moved the
    /// anchor module alone, and `check-sdk-pin.sh` failed on main: they move as one.
    #[test]
    fn a_root_pin_copied_into_each_module_moves_everywhere() {
        let root = "[workspace]\nmembers = [\"modules/*\"]\n\n[workspace.dependencies]\nportaki-sdk = \"8.0.0\"\nportaki-sdk-macros = \"8.0.0\"\n";
        let own = |features: &str| {
            format!("[dependencies]\nportaki-sdk = {{ version = \"8.0.0\", features = [{features}] }}\nportaki-sdk-macros = {{ workspace = true }}\n")
        };
        let members = vec![
            (PathBuf::from("/m/modules/access-guide"), own("\"kv\"")),
            (PathBuf::from("/m/modules/nuki"), own("")),
            (
                PathBuf::from("/m/modules/weather"),
                "[dependencies]\nportaki-sdk = { workspace = true }\n".to_string(),
            ),
        ];

        let declaration = locate_declaration(
            &members[0].1,
            &members[0].0,
            Path::new("/m"),
            Some(root),
            &members,
        )
        .unwrap();

        assert!(declaration.workspace_wide);
        assert_eq!(
            declaration.files,
            vec![
                PathBuf::from("/m/Cargo.toml"),
                PathBuf::from("/m/modules/access-guide/Cargo.toml"),
                PathBuf::from("/m/modules/nuki/Cargo.toml"),
            ]
        );
        let (root_after, _) = bump_requirements(root, "8.0.1").unwrap();
        assert!(root_after.contains("portaki-sdk = \"8.0.1\""));
        let (member_after, changed) = bump_requirements(&members[0].1, "8.0.1").unwrap();
        assert!(member_after.contains("portaki-sdk = { version = \"8.0.1\", features = [\"kv\"] }"));
        assert!(member_after.contains("portaki-sdk-macros = { workspace = true }"));
        assert_eq!(changed, vec!["portaki-sdk"]);
    }

    /// Outside a workspace, or without a pin at the root, a module moves only itself.
    #[test]
    fn a_root_without_the_family_leaves_the_module_alone() {
        let root =
            "[workspace]\nmembers = [\"modules/*\"]\n\n[workspace.dependencies]\nserde = \"1\"\n";
        let module = "[dependencies]\nportaki-sdk = \"8.0.0\"\n";

        let declaration = locate_declaration(
            module,
            Path::new("/m/modules/nuki"),
            Path::new("/m"),
            Some(root),
            &[(PathBuf::from("/m/modules/nuki"), module.to_string())],
        )
        .unwrap();

        assert!(!declaration.workspace_wide);
        assert_eq!(
            declaration.files,
            vec![PathBuf::from("/m/modules/nuki/Cargo.toml")]
        );
    }

    /// The workspace root of portaki-modules, as it is.
    #[test]
    fn the_whole_family_moves_and_the_rest_of_the_file_stays() {
        let root = "[workspace]\nmembers = [\"modules/*\"]\n\n[workspace.dependencies]\n# the SDK family moves together\nportaki-sdk = \"2.2.0\"\nportaki-sdk-macros = \"2.2.0\"\nportaki-connectors = \"2.2.0\"\nportaki-test-utils = \"2.2.0\"\nserde = { version = \"1\", features = [\"derive\"] }\n";

        let (bumped, changed) = bump_requirements(root, "3.0.1").unwrap();

        assert_eq!(
            changed,
            vec![
                "portaki-sdk",
                "portaki-sdk-macros",
                "portaki-connectors",
                "portaki-test-utils"
            ]
        );
        assert!(bumped.contains("portaki-sdk = \"3.0.1\""));
        assert!(bumped.contains("# the SDK family moves together"));
        assert!(bumped.contains("serde = { version = \"1\", features = [\"derive\"] }"));
    }

    #[test]
    fn an_inline_table_keeps_its_other_keys() {
        let module = "[dependencies]\nportaki-sdk = { version = \"2.4.0\", default-features = false }\n\n[dev-dependencies]\nportaki-test-utils = \"2.4.0\"\n";

        let (bumped, changed) = bump_requirements(module, "3.0.1").unwrap();

        assert!(bumped.contains("portaki-sdk = { version = \"3.0.1\", default-features = false }"));
        assert!(bumped.contains("portaki-test-utils = \"3.0.1\""));
        assert_eq!(changed, vec!["portaki-sdk", "portaki-test-utils"]);
    }

    /// No number here: the command must not invent one next to `workspace = true`.
    #[test]
    fn an_inherited_entry_is_left_alone_in_the_module() {
        let module = "[dependencies]\nportaki-sdk = { workspace = true }\n";

        let (bumped, changed) = bump_requirements(module, "3.0.1").unwrap();

        assert!(changed.is_empty());
        assert_eq!(bumped, module);
    }

    #[test]
    fn a_pinned_requirement_stays_pinned() {
        let module = "[dependencies]\nportaki-sdk = \"=2.4.0\"\nportaki-sdk-macros = { version = \"~2.4\" }\n";

        let (bumped, _) = bump_requirements(module, "3.0.1").unwrap();

        assert!(bumped.contains("portaki-sdk = \"=3.0.1\""));
        assert!(bumped.contains("portaki-sdk-macros = { version = \"~3.0.1\" }"));
    }

    /// A caret requirement resolves the newest compatible release — say so, don't claim the target.
    #[test]
    fn a_newer_compatible_resolution_is_reported() {
        let note = resolution_note("3.0.1", "3.1.0").unwrap();

        assert!(note.contains("resolved 3.1.0"));
        assert!(note.contains("=3.0.1"));
        assert_eq!(resolution_note("3.1.0", "3.1.0"), None);
    }

    /// `--dry-run` deploys nothing and does not take the `dev-watch` lease.
    #[test]
    fn a_dry_run_leaves_the_sandbox_alone() {
        let args = |flags: &[&str]| {
            let mut argv = vec!["upgrade"];
            argv.extend_from_slice(flags);
            UpgradeArgs::try_parse_from(argv).unwrap()
        };

        assert!(no_sandbox(&args(&["--dry-run"]), false)
            .unwrap()
            .contains("--dry-run"));
        assert!(no_sandbox(&args(&[]), false).is_none());
        assert!(no_sandbox(&args(&["--no-render"]), false).is_some());
        assert!(no_sandbox(&args(&[]), true).is_some());
    }

    fn check(id: &str) -> FailingCheck {
        FailingCheck {
            id: id.into(),
            detail: String::new(),
        }
    }

    /// ical-sync declares e-mails without a command: failing before, failing after — not the
    /// upgrade's doing, so it must not roll the upgrade back.
    #[test]
    fn a_check_that_already_failed_is_not_a_regression() {
        let before = ["emails".to_string()].into_iter().collect();

        let (introduced, preexisting) =
            split_failures(&before, vec![check("emails"), check("surfaces")]);

        assert_eq!(introduced, vec![check("surfaces")]);
        assert_eq!(preexisting, vec![check("emails")]);
    }

    fn release(version: &str, channel: &str, supported: bool) -> SdkRelease {
        SdkRelease {
            version: version.into(),
            channel: channel.into(),
            supported,
        }
    }

    #[test]
    fn the_latest_stable_is_computed_numerically() {
        let releases = [
            release("2.6.0", "stable", true),
            release("10.0.0", "stable", true),
            release("3.0.1", "stable", true),
            release("11.0.0-rc.1", "rc", true),
            release("12.0.0", "stable", false),
        ];

        assert_eq!(latest_stable(&releases).as_deref(), Some("10.0.0"));
    }

    fn render(rendered: bool, tree: &str, error: &str) -> Rendered {
        Rendered {
            rendered,
            tree: tree.into(),
            error_code: error.into(),
        }
    }

    #[test]
    fn a_surface_that_stops_rendering_is_a_break() {
        assert_eq!(
            compare_render(
                &render(true, r#"{"type":"Text"}"#, ""),
                &render(false, "", "wasm_trap")
            ),
            RenderOutcome::Broke {
                error: "wasm_trap".into()
            }
        );
    }

    /// Key order is not a render change.
    #[test]
    fn a_reordered_tree_is_the_same_render() {
        assert_eq!(
            compare_render(
                &render(true, r#"{"type":"Text","content":"a"}"#, ""),
                &render(true, r#"{"content":"a","type":"Text"}"#, ""),
            ),
            RenderOutcome::Same
        );
    }

    #[test]
    fn a_different_tree_is_reported_with_its_size() {
        assert_eq!(
            compare_render(
                &render(true, r#"{"type":"Stack","children":[{"type":"Text"}]}"#, ""),
                &render(
                    true,
                    r#"{"type":"Stack","children":[{"type":"Text"},{"type":"Button"}]}"#,
                    ""
                ),
            ),
            RenderOutcome::Changed {
                before: 2,
                after: 3
            }
        );
    }

    #[test]
    fn a_surface_that_already_failed_is_not_blamed_on_the_upgrade() {
        assert_eq!(
            compare_render(&render(false, "", "x"), &render(false, "", "x")),
            RenderOutcome::StillFailing
        );
    }
}