ignition-core 1.2.0

Core library for ign: config, profiles, gateway client, actions, error taxonomy
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
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
//! Project actions (03-01, PROJ-01/02): list with inheritance info,
//! new, copy, rename, set (reparent), delete — serde models OUT, no
//! printing (ARCHITECTURE.md layering: the Phase-6 TUI rides this same
//! layer).
//!
//! 03-02 (PROJ-03/04) adds export/import: the export result carries
//! the static scope metadata (what a project ZIP does and does not
//! contain — roadmap criterion 4), and the import action owns the
//! collision policy — the abort pre-check refuses via `project_find`
//! BEFORE any upload; overwrite skips the pre-check (the server is
//! the authority) and dispatch guards it as destructive.
//!
//! Two-column naming (LOCKED): client models stay wire-faithful; these
//! action results re-expose the SELECTED fields under unit-explicit
//! snake_case keys, ALL keys always present (null when absent) — the
//! stable agent shape; agents must never key-hunt.
//!
//! Every mutation READS BACK via `project_find` — the create/copy/
//! rename/modify response bodies are unverified LOW (the restart
//! `literal true` precedent), so the record the gateway answers with
//! IS the truth the CLI reports.
//!
//! The `parents`/`parents/{name}` endpoints stay OUT of scope: the
//! server is the reparent authority (cycle guard), and PROJ-01's
//! inheritance info comes from the list items themselves.

use std::path::{Path, PathBuf};

use serde::Serialize;

use crate::client::GatewayApi;
use crate::client::projects::{ProjectCreate, ProjectModify, ProjectRecord};
use crate::client::query::ListQuery;
use crate::error::CoreError;

/// What a project export INCLUDES — the static, documented-once
/// arrays (HIGH confidence: verified from a real git-module-managed
/// 8.3 export tree). Data, not prose — agents key off them (roadmap
/// criterion 4).
pub const EXPORT_INCLUDES: &[&str] = &[
    "views",
    "scripts",
    "named-queries",
    "vision-windows",
    "perspective-themes-styles",
    "reporting",
    "alarm-notification-profiles",
    "webdev-routes",
    "translations",
    "sfc-charts",
];

/// What a project export EXCLUDES — tag providers, tags, and UDTs are
/// GATEWAY CONFIGURATION, not project resources (the git-module
/// convention keeps a separate `tags/` tree precisely because of
/// this).
pub const EXPORT_EXCLUDES: &[&str] = &[
    "tag-providers",
    "tags",
    "udts",
    "gateway-config",
    "database-connections",
    "users-roles",
    "alarm-journal",
    "certificates",
];

/// The scope metadata carried in BOTH export and import JSON data —
/// identical consts, so the statement "what this ZIP does and does
/// not contain" never drifts between the two commands.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ExportScope {
    /// Resource families present in a project ZIP.
    pub includes: Vec<&'static str>,
    /// Resource families that live in gateway config instead.
    pub excludes: Vec<&'static str>,
}

impl ExportScope {
    /// Build from the static consts (the single source).
    pub fn new() -> Self {
        Self {
            includes: EXPORT_INCLUDES.to_vec(),
            excludes: EXPORT_EXCLUDES.to_vec(),
        }
    }
}

impl Default for ExportScope {
    fn default() -> Self {
        Self::new()
    }
}

/// Import sanity limit — 512 MB (a real project export is MB-scale;
/// anything past this is a wrong file, not a project). Checked
/// BEFORE any network I/O.
pub const IMPORT_MAX_BYTES: usize = 512 * 1024 * 1024;

/// The local-file-header magic every ZIP carries (`PK\x03\x04`) —
/// the cheap wrong-file guard (Don't-Hand-Roll table: the gateway
/// validates imports; this catches the common mistake).
const ZIP_MAGIC: [u8; 4] = [0x50, 0x4B, 0x03, 0x04];

/// The import collision policy. REST exposes exactly abort and
/// overwrite — `merge` is the Designer import popup's vocabulary and
/// is rejected at the CLI value-enum level (README documents it as
/// Designer-only).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub enum CollisionPolicy {
    /// Refuse when the project already exists (default) — the find
    /// pre-check fires BEFORE any upload.
    Abort,
    /// Replace the ENTIRE project: resources absent from the ZIP are
    /// DELETED (replace, not merge — Pitfall 4). Destructive: the CLI
    /// guards it with `--yes`.
    Overwrite,
}

impl CollisionPolicy {
    /// The stable agent-facing label.
    pub fn label(self) -> &'static str {
        match self {
            Self::Abort => "abort",
            Self::Overwrite => "overwrite",
        }
    }
}

/// The >512 MB refusal as a pure size check — testable without a
/// half-gigabyte allocation.
fn import_size_error(len: usize) -> Option<CoreError> {
    (len > IMPORT_MAX_BYTES).then(|| CoreError::InvalidImportFile {
        reason: format!(
            "{len} bytes exceeds the {} MB sanity limit",
            IMPORT_MAX_BYTES / (1024 * 1024)
        ),
    })
}

/// The cheap wrong-file guards, both usage-class (exit 2): the
/// `PK\x03\x04` magic and the 512 MB sanity limit. Runs BEFORE any
/// network I/O (the find pre-check included).
fn validate_import(zip: &[u8]) -> Result<(), CoreError> {
    if !zip.starts_with(&ZIP_MAGIC) {
        return Err(CoreError::InvalidImportFile {
            reason: "missing ZIP magic (PK\\x03\\x04) — not a project export archive".to_string(),
        });
    }
    if let Some(err) = import_size_error(zip.len()) {
        return Err(err);
    }
    // (05-07, Rule 2) Full-structure validation BEFORE any upload:
    // live-witnessed on 8.3.3, a TRUNCATED zip (valid magic, broken
    // tail) imports with `{"success":true,"changes":[]}` and — on
    // overwrite — REPLACES the project with the partial contents
    // (data loss wearing a success face). Walking every member and
    // decompressing it catches truncation/corruption here, where the
    // refusal names the caller's own file to fix (exit 2, zero
    // network).
    let mut archive = zip::ZipArchive::new(std::io::Cursor::new(zip)).map_err(|err| {
        CoreError::InvalidImportFile {
            reason: format!("not a readable ZIP archive: {err}"),
        }
    })?;
    for index in 0..archive.len() {
        let mut file = archive
            .by_index(index)
            .map_err(|err| CoreError::InvalidImportFile {
                reason: format!("cannot read import archive member {index}: {err}"),
            })?;
        let name = file.name().to_string();
        let mut sink = Vec::new();
        std::io::Read::read_to_end(&mut file, &mut sink).map_err(|err| {
            CoreError::InvalidImportFile {
                reason: format!("cannot decompress import member {name:?}: {err}"),
            }
        })?;
    }
    Ok(())
}

/// Strip any path components from a `Content-Disposition` basename —
/// the gateway names exports well, but a disposition value is header
/// input and never deserves path trust. `.`/`..`/empty refuse (the
/// caller falls back to `<name>.zip`).
fn sanitize_basename(raw: &str) -> Option<String> {
    let name = raw.rsplit(['/', '\\']).next().unwrap_or(raw).trim();
    if name.is_empty() || name == "." || name == ".." {
        None
    } else {
        Some(name.to_string())
    }
}

/// A filesystem-safe fallback stem for the default export name — a
/// project name is a single segment on the wire, but defense-in-depth
/// replaces any separator that somehow rides along.
fn safe_fallback_stem(name: &str) -> String {
    name.replace(['/', '\\'], "_")
}

/// One project row — the six fields PROJ-01 names.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ProjectSummary {
    /// Project name (unique key).
    pub name: String,
    /// Display title (null when unset).
    pub title: Option<String>,
    /// Long description (null when unset).
    pub description: Option<String>,
    /// Whether the project runs.
    pub enabled: bool,
    /// Parent project name — the inheritance link (null at the root).
    pub parent: Option<String>,
    /// Whether THIS project may serve as a parent (null when the
    /// gateway did not report it).
    pub inheritable: Option<bool>,
}

impl ProjectSummary {
    /// Select the six stable fields from a full wire record.
    fn from_record(record: &ProjectRecord) -> Self {
        Self {
            name: record.name.clone(),
            title: record.title.clone(),
            description: record.description.clone(),
            enabled: record.enabled,
            parent: record.parent.clone(),
            inheritable: record.inheritable,
        }
    }
}

/// `ign project list` output model.
#[derive(Debug, Serialize)]
pub struct ProjectsResult {
    /// Every runnable project.
    pub projects: Vec<ProjectSummary>,
}

/// `project new` flags — only provided fields ride the create body
/// (absent = NOT SENT, Pitfall 5); `enabled` is the CLI `--disabled`
/// flag inverted at the dispatch seam.
#[derive(Debug, Default, Clone)]
pub struct NewOptions {
    /// Whether the project starts enabled.
    pub enabled: bool,
    /// Display title.
    pub title: Option<String>,
    /// Long description.
    pub description: Option<String>,
    /// Parent project (inheritance).
    pub parent: Option<String>,
    /// Whether this project may serve as a parent.
    pub inheritable: Option<bool>,
}

/// `project set` flags — ONLY the `Some` fields ride the modify body
/// (absent flag = don't touch — Pitfall 5's modify half).
#[derive(Debug, Default, Clone)]
pub struct SetOptions {
    /// Display title.
    pub title: Option<String>,
    /// Long description.
    pub description: Option<String>,
    /// Parent project — the inheritance move.
    pub parent: Option<String>,
    /// Whether the project runs.
    pub enabled: Option<bool>,
    /// Whether this project may serve as a parent.
    pub inheritable: Option<bool>,
}

impl SetOptions {
    /// Which fields this set touches, in flag order — the human
    /// renderer's `set <fields> on <name>` line.
    fn fields_set(&self) -> Vec<String> {
        let mut fields = Vec::new();
        if self.title.is_some() {
            fields.push("title".to_string());
        }
        if self.description.is_some() {
            fields.push("description".to_string());
        }
        if self.parent.is_some() {
            fields.push("parent".to_string());
        }
        if self.enabled.is_some() {
            fields.push("enabled".to_string());
        }
        if self.inheritable.is_some() {
            fields.push("inheritable".to_string());
        }
        fields
    }
}

/// `ign project copy` output model: the source plus the destination's
/// read-back record (flat in JSON).
#[derive(Debug, Serialize)]
pub struct ProjectCopyResult {
    /// The source name.
    pub from: String,
    /// The destination's read-back record.
    #[serde(flatten)]
    pub project: ProjectSummary,
}

/// `ign project rename` output model: previous name plus the renamed
/// project's read-back record (flat).
#[derive(Debug, Serialize)]
pub struct ProjectRenameResult {
    /// The name before the rename.
    pub previous_name: String,
    /// The renamed project's read-back record.
    #[serde(flatten)]
    pub project: ProjectSummary,
}

/// `ign project set` output model: the read-back record (flat, the
/// stable agent shape) plus which fields this set touched —
/// display-only, serde-skipped so it NEVER appears in JSON.
#[derive(Debug, Serialize)]
pub struct ProjectSetResult {
    /// The fields this set touched (human rendering only).
    #[serde(skip)]
    pub fields: Vec<String>,
    /// The post-set read-back record.
    #[serde(flatten)]
    pub project: ProjectSummary,
}

/// `ign project delete` output model.
#[derive(Debug, Serialize)]
pub struct ProjectDeleteResult {
    /// The deleted project's name.
    pub deleted: String,
}

/// `ign project export` output model: `{project, file, bytes, scope}`
/// — the FILE is the artifact; stdout stays data-only.
#[derive(Debug, Serialize)]
pub struct ExportResult {
    /// The exported project's name.
    pub project: String,
    /// Path of the file written (the `-o` value, or the resolved
    /// default name).
    pub file: String,
    /// Bytes streamed to disk (chunk-counted).
    pub bytes: u64,
    /// What the ZIP does and does not contain (roadmap criterion 4).
    pub scope: ExportScope,
}

/// `ign project import` output model: `{name, collision_policy,
/// bytes, scope, outcome}` — `outcome` is the opaque server answer
/// (an object when JSON, else the success fallback).
#[derive(Debug, Serialize)]
pub struct ImportResult {
    /// The name imported under.
    pub name: String,
    /// The policy that ran (`abort` | `overwrite`).
    pub collision_policy: String,
    /// Bytes uploaded.
    pub bytes: usize,
    /// What the ZIP does and does not contain — the SAME consts as
    /// export's, so the pair never drifts.
    pub scope: ExportScope,
    /// The server's opaque answer.
    pub outcome: serde_json::Value,
}

// ---- Cross-gateway diff & sync (07-01, SYNC-01/02) -----------------------
//
// The promotion pair: see exactly what differs between two gateways'
// copy of a project, then push selected resources across. Both
// orchestrate over TWO `GatewayApi` handles (source A, target B) and
// ride the pure diff engine in [`crate::client::resources`]
// (normalized member compare — the volatility guard) plus the 05-02
// surgery helpers (replace_member's descriptor-merge landing rules
// ride free).

/// One `project.json` semantic-field difference — `(field, a, b)`
/// surfaced as named keys (the flat agent shape).
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ProjectMetaDelta {
    /// The compared field (`title` | `enabled` | `parent`).
    pub field: String,
    /// Profile A's value (stringified; `null` when absent).
    pub a: String,
    /// Profile B's value (stringified; `null` when absent).
    pub b: String,
}

/// `ign project diff` output model — the flat agent shape, ALL keys
/// always. `scope` is the literal `"project"` (the scope-honesty
/// mandate: tag providers live on a different seam, README documents
/// the promotion pipe); `profile_a`/`profile_b` ride the DATA while
/// the envelope keeps its single active-profile field (the frozen
/// one-field envelope).
#[derive(Debug, Serialize)]
pub struct ProjectDiffResult {
    /// Always `"project"` — the diff's scope contract.
    pub scope: &'static str,
    /// The baseline profile (A).
    pub profile_a: String,
    /// The compared profile (B — statuses are B-relative-to-A).
    pub profile_b: String,
    /// The project compared.
    pub project: String,
    /// Root `project.json` semantic-field differences (title/enabled/
    /// parent) — empty when none.
    pub project_meta: Vec<ProjectMetaDelta>,
    /// The four member counts.
    pub summary: crate::client::resources::DiffSummary,
    /// One row per resource member, path-sorted.
    pub entries: Vec<crate::client::resources::MemberDiffEntry>,
}

/// `ign project diff A B --project NAME` — export both sides (A
/// first), run the normalized member compare plus the project.json
/// meta delta. A missing project on either side surfaces through
/// export's existing not-found path; the same profile twice is a
/// usage-class refusal (exit 2) before any network I/O.
pub async fn project_diff(
    api_a: &dyn GatewayApi,
    api_b: &dyn GatewayApi,
    project: &str,
    profile_a: &str,
    profile_b: &str,
) -> Result<ProjectDiffResult, CoreError> {
    if profile_a == profile_b {
        return Err(CoreError::InvalidInput {
            reason: "diffing a profile against itself is a no-op — name two \
                     different profiles"
                .to_string(),
        });
    }
    let zip_a = crate::actions::resources::export_zip_bytes(api_a, project).await?;
    let zip_b = crate::actions::resources::export_zip_bytes(api_b, project).await?;
    let diff = crate::client::resources::diff_members(&zip_a, &zip_b)?;
    let project_meta = crate::client::resources::project_meta_delta(&zip_a, &zip_b)?
        .into_iter()
        .map(|(field, a, b)| ProjectMetaDelta { field, a, b })
        .collect();
    Ok(ProjectDiffResult {
        scope: "project",
        profile_a: profile_a.to_string(),
        profile_b: profile_b.to_string(),
        project: project.to_string(),
        project_meta,
        summary: diff.summary,
        entries: diff.entries,
    })
}

/// What `project sync` promotes from A into B (07-01, SYNC-02) — at
/// least one half is required (the CLI validates pre-resolution; the
/// action re-validates for its other callers).
#[derive(Debug, Default, Clone)]
pub struct SyncSelection {
    /// Explicit `--resource` user paths (repeatable; combines with
    /// `all_changed`).
    pub resources: Vec<String>,
    /// `--all-changed`: take the diff's `added`+`changed` paths —
    /// never `removed` (deletion is the separate `--delete`
    /// opt-in's job).
    pub all_changed: bool,
}

/// `ign project sync` output model — the flat agent shape, ALL keys
/// always (empty vecs when none). Direction is ALWAYS explicit A→B
/// (source A, target B).
#[derive(Debug, Serialize)]
pub struct ProjectSyncResult {
    /// Always `"project"` — the sync's scope contract.
    pub scope: &'static str,
    /// The source profile (A).
    pub profile_a: String,
    /// The target profile (B).
    pub profile_b: String,
    /// The project promoted.
    pub project: String,
    /// The user paths promoted A→B (upserted).
    pub synced: Vec<String>,
    /// The user paths removed from B (`--delete` only).
    pub removed: Vec<String>,
}

/// `ign project sync A B --project NAME` — the guarded promotion.
/// Order is the contract: export A then B → resolve the selection
/// (explicit `--resource` paths must exist in A unless `--delete`
/// wants them removed from B; `--all_changed` rides the diff) →
/// splice A's member bytes into B's zip via the surgery helpers
/// (`replace_member`'s descriptor-merge landing rules ride free —
/// 05-07's put-new hazard is handled) → optional `remove_member`
/// passes for deletions → `validate_import` + ONE overwrite-import
/// into B. B's root `project.json` is never touched (only resource
/// members splice). An EMPTY effective selection performs NO import
/// (zero writes) and reports empty lists.
pub async fn project_sync(
    api_a: &dyn GatewayApi,
    api_b: &dyn GatewayApi,
    project: &str,
    selection: &SyncSelection,
    delete: bool,
    profile_a: &str,
    profile_b: &str,
) -> Result<ProjectSyncResult, CoreError> {
    if selection.resources.is_empty() && !selection.all_changed {
        return Err(CoreError::InvalidInput {
            reason: "sync needs a selection — pass --resource PATH (repeatable) \
                     and/or --all-changed"
                .to_string(),
        });
    }
    let zip_a = crate::actions::resources::export_zip_bytes(api_a, project).await?;
    let zip_b = crate::actions::resources::export_zip_bytes(api_b, project).await?;

    // Resolve the selection: upserts (A's bytes land in B) and — only
    // under --delete — removals (B loses what A no longer has).
    let mut upserts: Vec<String> = Vec::new();
    let mut removals: Vec<String> = Vec::new();
    for path in &selection.resources {
        match crate::client::resources::read_member(&zip_a, path) {
            Ok(_) => upserts.push(path.clone()),
            // An explicit path absent in A is a DELETION request under
            // --delete (removed from B below); without --delete it is
            // the missing-member shape.
            Err(CoreError::NotFound { .. }) if delete => removals.push(path.clone()),
            Err(other) => return Err(other),
        }
    }
    if selection.all_changed {
        // LABEL RECONCILIATION (must_haves over the plan sketch): the
        // diff speaks B-relative-to-A (`added` = in B only, `removed`
        // = in A only) while sync speaks A→B promotion. For A's
        // resources to LAND in B, the upsert set is everything A has
        // that B lacks or differs on — the diff's `removed` (A-only)
        // and `changed` (differing) — and the `--delete` removal set
        // is B's extras, the diff's `added` (B-only). Pushing the
        // diff's `added` set would read members A does not have.
        for entry in crate::client::resources::diff_members(&zip_a, &zip_b)?.entries {
            match entry.status {
                crate::client::resources::MemberStatus::Removed
                | crate::client::resources::MemberStatus::Changed => {
                    upserts.push(entry.path);
                }
                crate::client::resources::MemberStatus::Added if delete => {
                    removals.push(entry.path);
                }
                _ => {}
            }
        }
    }
    upserts.sort();
    upserts.dedup();
    removals.sort();
    removals.dedup();

    // The surgery: splice A's members into B's zip, then drop the
    // removals. replace_member's put-new descriptor rules ride free.
    let mut surgical = zip_b;
    for path in &upserts {
        let bytes = crate::client::resources::read_member(&zip_a, path)?;
        surgical = crate::client::resources::replace_member(&surgical, path, &bytes)?;
    }
    for path in &removals {
        surgical = crate::client::resources::remove_member(&surgical, path)?;
    }

    // Zero-write honesty: an empty selection (nothing to upsert,
    // nothing to remove) performs NO import — a whole-project
    // overwrite-import of an unchanged zip is not a no-op on the
    // gateway, so it must never fire without work to do.
    if !upserts.is_empty() || !removals.is_empty() {
        validate_import(&surgical)?;
        api_b.project_import(project, surgical, true).await?;
    }
    Ok(ProjectSyncResult {
        scope: "project",
        profile_a: profile_a.to_string(),
        profile_b: profile_b.to_string(),
        project: project.to_string(),
        synced: upserts,
        removed: removals,
    })
}

/// `ign project list` — every runnable project with inheritance info
/// (the standard `limit=-1` UI convention).
pub async fn projects(api: &dyn GatewayApi) -> Result<ProjectsResult, CoreError> {
    let page = api.projects(&ListQuery::default()).await?;
    Ok(ProjectsResult {
        projects: page.items.iter().map(ProjectSummary::from_record).collect(),
    })
}

/// `ign project new` — create, then `find` read-back (validates the
/// create and fills the result; the create response body itself is
/// unverified LOW).
pub async fn project_new(
    api: &dyn GatewayApi,
    name: &str,
    opts: &NewOptions,
) -> Result<ProjectSummary, CoreError> {
    let body = ProjectCreate {
        name: name.to_string(),
        enabled: opts.enabled,
        title: opts.title.clone(),
        description: opts.description.clone(),
        parent: opts.parent.clone(),
        inheritable: opts.inheritable,
        default_db: None,
        tag_provider: None,
        user_source: None,
    };
    api.project_create(&body).await?;
    let record = api.project_find(name).await?;
    Ok(ProjectSummary::from_record(&record))
}

/// `ign project copy` — copy all resources, then `find(to)` read-back.
pub async fn project_copy(
    api: &dyn GatewayApi,
    from: &str,
    to: &str,
) -> Result<ProjectCopyResult, CoreError> {
    api.project_copy(from, to).await?;
    let record = api.project_find(to).await?;
    Ok(ProjectCopyResult {
        from: from.to_string(),
        project: ProjectSummary::from_record(&record),
    })
}

/// `ign project rename` — native rename, then `find(new)` read-back.
pub async fn project_rename(
    api: &dyn GatewayApi,
    old: &str,
    new: &str,
) -> Result<ProjectRenameResult, CoreError> {
    api.project_rename(old, new).await?;
    let record = api.project_find(new).await?;
    Ok(ProjectRenameResult {
        previous_name: old.to_string(),
        project: ProjectSummary::from_record(&record),
    })
}

/// `ign project set` — build the modify body from `Some`-fields ONLY
/// (absent flag = don't touch), PUT, then read-back. `--parent` IS the
/// inheritance move.
pub async fn project_set(
    api: &dyn GatewayApi,
    name: &str,
    opts: &SetOptions,
) -> Result<ProjectSetResult, CoreError> {
    let body = ProjectModify {
        enabled: opts.enabled,
        title: opts.title.clone(),
        description: opts.description.clone(),
        parent: opts.parent.clone(),
        inheritable: opts.inheritable,
        default_db: None,
        tag_provider: None,
        user_source: None,
    };
    api.project_modify(name, &body).await?;
    let record = api.project_find(name).await?;
    Ok(ProjectSetResult {
        fields: opts.fields_set(),
        project: ProjectSummary::from_record(&record),
    })
}

/// `ign project delete` — the obedient arm; the `--yes` guard belongs
/// to the CLI CALLER (it refuses pre-resolution, the LOCKED 02-03
/// shape). The wire request always carries `confirm=true`.
pub async fn project_delete(
    api: &dyn GatewayApi,
    name: &str,
) -> Result<ProjectDeleteResult, CoreError> {
    api.project_delete(name).await?;
    Ok(ProjectDeleteResult {
        deleted: name.to_string(),
    })
}

/// `ign project export` — stream the project ZIP to disk. With `-o`
/// the bytes land at exactly that path; without one, the stream goes
/// to `<name>.zip.part` in the working directory and atomically
/// renames to the SANITIZED `Content-Disposition` basename (path
/// components stripped) or the `<name>.zip` fallback — the `.part`
/// is removed best-effort on error, so a failed export leaves no
/// half-written impostor.
pub async fn project_export(
    api: &dyn GatewayApi,
    name: &str,
    output: Option<&Path>,
) -> Result<ExportResult, CoreError> {
    let scope = ExportScope::new();
    if let Some(out) = output {
        let meta = api.project_export_to_file(name, out).await?;
        return Ok(ExportResult {
            project: name.to_string(),
            file: out.display().to_string(),
            bytes: meta.bytes,
            scope,
        });
    }

    // Default naming: stream to <fallback>.part, then rename to the
    // disposition basename (or the fallback) once the meta arrives.
    let fallback = format!("{}.zip", safe_fallback_stem(name));
    let part = PathBuf::from(format!("{fallback}.part"));
    let meta = match api.project_export_to_file(name, &part).await {
        Ok(meta) => meta,
        Err(err) => {
            let _ = std::fs::remove_file(&part); // best-effort
            return Err(err);
        }
    };
    let final_name = meta
        .filename
        .as_deref()
        .and_then(sanitize_basename)
        .unwrap_or(fallback);
    if let Err(err) = std::fs::rename(&part, &final_name) {
        let _ = std::fs::remove_file(&part); // best-effort
        return Err(CoreError::Internal(format!(
            "cannot finalize export {final_name}: {err}"
        )));
    }
    Ok(ExportResult {
        project: name.to_string(),
        file: final_name,
        bytes: meta.bytes,
        scope,
    })
}

/// `ign project import` — order is the contract: magic/size guards
/// (exit 2, zero network) → abort-policy find pre-check (`Ok` →
/// [`CoreError::ProjectExists`] BEFORE any upload) → the raw-body
/// upload with the policy as the wire's `overwrite` query param.
/// Overwrite runs NO pre-check — the server is the authority — and
/// the CLI guards it as destructive upstream of this action.
pub async fn project_import(
    api: &dyn GatewayApi,
    name: &str,
    zip: Vec<u8>,
    policy: CollisionPolicy,
) -> Result<ImportResult, CoreError> {
    let bytes = zip.len();
    let scope = ExportScope::new();
    validate_import(&zip)?;
    if matches!(policy, CollisionPolicy::Abort) && api.project_find(name).await.is_ok() {
        return Err(CoreError::ProjectExists {
            name: name.to_string(),
            endpoint: None,
        });
    }
    let overwrite = matches!(policy, CollisionPolicy::Overwrite);
    let outcome = api.project_import(name, zip, overwrite).await?;
    Ok(ImportResult {
        name: name.to_string(),
        collision_policy: policy.label().to_string(),
        bytes,
        scope,
        outcome: outcome.response,
    })
}

/// `ign project export --decode-scripts` output model (07-04,
/// INTR-01): the DIRECTORY is the artifact — the export's members
/// plus `<member>.<n>.py` sidecars plus the pointer manifest, ready
/// for nvim/ignition-lint editing.
#[derive(Debug, Serialize)]
pub struct ExportDecodedResult {
    /// The exported project's name.
    pub project: String,
    /// The directory written (the `-o` value, or `<name>-export/`).
    pub dir: String,
    /// File members in the export zip.
    pub members: usize,
    /// Scripts decoded to sidecars.
    pub scripts_decoded: usize,
    /// Bytes of the source export zip.
    pub bytes: u64,
    /// What the ZIP does and does not contain (the shared consts).
    pub scope: ExportScope,
}

/// `ign project export NAME --decode-scripts` — buffer the export
/// (the diff/sync seam), then decode the tree via the PURE codec:
/// members + counter-named sidecars + `scripts-manifest.json` at the
/// directory root. The re-encode half (`import --encode-scripts`)
/// lives at the CLI dispatch seam — it re-zips the directory BEFORE
/// this action's import path, which then rides verbatim
/// (`validate_import` walks the re-zipped archive — the 05-07 guard
/// applies free).
pub async fn project_export_decoded(
    api: &dyn GatewayApi,
    name: &str,
    out_dir: Option<&Path>,
) -> Result<ExportDecodedResult, CoreError> {
    let zip = crate::actions::resources::export_zip_bytes(api, name).await?;
    let dir = match out_dir {
        Some(dir) => dir.to_path_buf(),
        None => PathBuf::from(format!("{}-export", safe_fallback_stem(name))),
    };
    let members = crate::client::scripts_codec::count_file_members(&zip)?;
    let scripts_decoded = crate::client::scripts_codec::decode_export_tree(&zip, &dir)?;
    Ok(ExportDecodedResult {
        project: name.to_string(),
        dir: dir.display().to_string(),
        members,
        scripts_decoded,
        bytes: zip.len() as u64,
        scope: ExportScope::new(),
    })
}

#[cfg(test)]
mod tests {
    use super::{NewOptions, ProjectSummary, SetOptions, project_new, projects};
    use crate::client::GatewayApi;
    use crate::client::projects::{ProjectCreate, ProjectModify, ProjectRecord};
    use crate::client::query::{ListEnvelope, ListMetadata};
    use crate::error::CoreError;

    use std::sync::Mutex;

    /// A recording double: serves one record per find (create/copy/
    /// rename/set read-backs), remembers every create/modify body and
    /// every deleted name. 03-02 grows it into the export/import
    /// double: find honors an `absent` switch (the collision
    /// pre-check's both answers), export writes a fixture ZIP, import
    /// records (name, bytes, overwrite) — the Task-2 action proofs key
    /// off those recordings.
    #[derive(Default)]
    struct ProjectsRig {
        creates: Mutex<Vec<ProjectCreate>>,
        modifies: Mutex<Vec<(String, ProjectModify)>>,
        deletes: Mutex<Vec<String>>,
        finds: Mutex<Vec<String>>,
        exports: Mutex<Vec<String>>,
        imports: Mutex<Vec<(String, usize, bool)>>,
        /// Whether `find` answers 404-NotFound instead of Ok — the
        /// collision pre-check's two outcomes (default: the project
        /// exists, preserving the create/copy/rename/set read-backs).
        absent: bool,
        /// An export-body override (07-04: the decode tests serve a
        /// script-bearing zip; default None = the bare fixture).
        export_body: Option<Vec<u8>>,
    }

    impl ProjectsRig {
        /// A minimal VALID ZIP fixture (real archive — the action's
        /// import guard walks every member since 05-07; the old
        /// magic-bytes-plus-junk shape now refuses, correctly).
        fn zip_fixture() -> Vec<u8> {
            use std::io::Write as _;
            let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
            let options = zip::write::SimpleFileOptions::default();
            writer
                .start_file("project.json", options)
                .expect("fixture member starts");
            writer
                .write_all(br#"{"title":"fixture"}"#)
                .expect("fixture member writes");
            writer.finish().expect("fixture finalizes").into_inner()
        }
    }

    fn record(name: &str) -> ProjectRecord {
        ProjectRecord {
            name: name.into(),
            title: Some(format!("{name} title")),
            description: None,
            enabled: true,
            parent: Some("Base".into()),
            inheritable: Some(false),
            default_db: None,
            tag_provider: None,
            user_source: None,
            extra: Default::default(),
        }
    }

    fn page(items: Vec<ProjectRecord>) -> ListEnvelope<ProjectRecord> {
        let total = items.len() as i64;
        ListEnvelope {
            items,
            metadata: ListMetadata {
                total,
                matching: total,
                limit: -1,
                offset: 0,
            },
        }
    }

    #[async_trait::async_trait]
    impl GatewayApi for ProjectsRig {
        async fn bundle_generate(
            &self,
        ) -> Result<crate::client::diagnostics::BundleStatusWire, CoreError> {
            unreachable!("not part of this action")
        }
        async fn bundle_status(
            &self,
        ) -> Result<crate::client::diagnostics::BundleStatusWire, CoreError> {
            unreachable!("not part of this action")
        }
        async fn bundle_download(
            &self,
            _out: &std::path::Path,
        ) -> Result<crate::client::projects::ExportMeta, CoreError> {
            unreachable!("not part of this action")
        }
        async fn tag_provider_list(
            &self,
            _query: &crate::client::query::ListQuery,
        ) -> Result<
            crate::client::query::ListEnvelope<crate::client::tags::TagProviderRecord>,
            CoreError,
        > {
            unreachable!("not part of this action")
        }
        async fn tag_provider_find(
            &self,
            _name: &str,
        ) -> Result<crate::client::tags::TagProviderRecord, CoreError> {
            unreachable!("not part of this action")
        }
        async fn tag_provider_create(
            &self,
            _body: &[crate::client::tags::TagProviderCreate],
        ) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn tag_provider_delete(
            &self,
            _name: &str,
            _signature: &str,
        ) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn trial_status_wire(&self) -> Result<crate::client::trial::TrialWire, CoreError> {
            unreachable!("not part of this action")
        }
        async fn banners(&self) -> Result<crate::client::trial::BannerSet, CoreError> {
            unreachable!("not part of this action")
        }
        async fn trial_reset_wire(&self) -> Result<crate::client::trial::TrialWire, CoreError> {
            unreachable!("not part of this action")
        }
        async fn backup_download(
            &self,
            _out: &std::path::Path,
            _backup_type: crate::client::backup::BackupType,
        ) -> Result<crate::client::projects::ExportMeta, CoreError> {
            unreachable!("not part of this action")
        }
        async fn backup_restore(&self, _gwbk: &std::path::Path) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn eam_task_history(
            &self,
            _limit: Option<u32>,
            _search: Option<&str>,
        ) -> Result<crate::client::query::ListEnvelope<crate::client::eam::EamHistoryItem>, CoreError>
        {
            unreachable!("not part of this action")
        }
        async fn eam_task_definitions(
            &self,
        ) -> Result<crate::client::query::ListEnvelope<crate::client::eam::EamTaskRecord>, CoreError>
        {
            unreachable!("not part of this action")
        }
        async fn eam_task_find(
            &self,
            _name: &str,
        ) -> Result<crate::client::eam::EamTaskRecord, CoreError> {
            unreachable!("not part of this action")
        }
        async fn eam_task_create(&self, _definition: &serde_json::Value) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn eam_task_force(&self, _owner: &str, _name: &str) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn eam_task_suspend(&self, _name: &str) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn eam_task_resume(&self, _name: &str) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn eam_task_cancel(&self, _name: &str) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn eam_tasks_scheduled(
            &self,
            _running: bool,
        ) -> Result<Vec<crate::client::eam::EamScheduledTask>, CoreError> {
            unreachable!("not part of this action")
        }
        async fn eam_task_modify(
            &self,
            _definition: &serde_json::Value,
        ) -> Result<Option<crate::client::eam::ModifyOutcome>, CoreError> {
            unreachable!("not part of this action")
        }
        async fn eam_task_delete(
            &self,
            _name: &str,
            _signature: &str,
            _confirm: bool,
        ) -> Result<crate::client::eam::DeleteOutcome, CoreError> {
            unreachable!("not part of this action")
        }
        async fn api_call(
            &self,
            _call: &crate::client::apicall::ApiCallRequest,
        ) -> Result<crate::client::apicall::ApiCallData, CoreError> {
            unreachable!("not part of this action")
        }
        async fn license_status(
            &self,
        ) -> Result<crate::client::license::LicenseStatusWire, CoreError> {
            unreachable!("not part of this action")
        }
        async fn redundancy_status(
            &self,
        ) -> Result<crate::client::redundancy::RedundancyStatusWire, CoreError> {
            unreachable!("not part of this action")
        }
        async fn gan_status(&self) -> Result<crate::client::gan::GanStatusWire, CoreError> {
            unreachable!("not part of this action")
        }
        async fn gateway_info(&self) -> Result<crate::client::version::GatewayInfo, CoreError> {
            unreachable!("not part of this action")
        }
        async fn overview(&self) -> Result<crate::client::status::Overview, CoreError> {
            unreachable!("not part of this action")
        }
        async fn status_ping(&self) -> Result<crate::client::status::StatusPing, CoreError> {
            unreachable!("not part of this action")
        }
        async fn modules(
            &self,
            _quarantined: bool,
            _query: &crate::client::query::ListQuery,
        ) -> Result<ListEnvelope<crate::client::status::ModuleInfo>, CoreError> {
            unreachable!("not part of this action")
        }
        async fn metrics_current(
            &self,
        ) -> Result<crate::client::metrics::CurrentGauges, CoreError> {
            unreachable!("not part of this action")
        }
        async fn metrics_historic(
            &self,
        ) -> Result<crate::client::metrics::PerformanceCharts, CoreError> {
            unreachable!("not part of this action")
        }
        async fn metrics_threads(&self) -> Result<crate::client::metrics::ThreadCounts, CoreError> {
            unreachable!("not part of this action")
        }
        async fn designers(
            &self,
            _query: &crate::client::query::ListQuery,
        ) -> Result<ListEnvelope<crate::client::sessions::DesignerInfo>, CoreError> {
            unreachable!("not part of this action")
        }
        async fn perspective_sessions(
            &self,
            _query: &crate::client::query::ListQuery,
        ) -> Result<ListEnvelope<crate::client::sessions::PerspectiveSession>, CoreError> {
            unreachable!("not part of this action")
        }
        async fn vision_clients(
            &self,
            _query: &crate::client::query::ListQuery,
        ) -> Result<ListEnvelope<crate::client::sessions::VisionClient>, CoreError> {
            unreachable!("not part of this action")
        }
        async fn terminate_perspective_session(
            &self,
            _id: &str,
            _message: Option<&str>,
        ) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn terminate_vision_client(&self, _id: &str) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn prune_designer(&self, _id: &str) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn database_connections(
            &self,
        ) -> Result<ListEnvelope<crate::client::connections::GatewayConnection>, CoreError>
        {
            unreachable!("not part of this action")
        }
        async fn opc_connections(
            &self,
        ) -> Result<ListEnvelope<crate::client::connections::GatewayConnection>, CoreError>
        {
            unreachable!("not part of this action")
        }
        async fn logs(
            &self,
            _filter: &crate::client::logs::LogQuery,
        ) -> Result<ListEnvelope<crate::client::logs::LogEntry>, CoreError> {
            unreachable!("not part of this action")
        }
        async fn logs_download(&self) -> Result<crate::client::logs::LogDownload, CoreError> {
            unreachable!("not part of this action")
        }
        async fn loggers(
            &self,
            _query: &crate::client::query::ListQuery,
        ) -> Result<ListEnvelope<crate::client::logs::LoggerInfo>, CoreError> {
            unreachable!("not part of this action")
        }
        async fn set_logger_level(&self, _logger: &str, _level: &str) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn reset_logger_levels(&self) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn restart(&self) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn scan_projects(&self) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn security_properties(
            &self,
        ) -> Result<crate::client::restart::SecurityProperties, CoreError> {
            unreachable!("not part of this action")
        }
        async fn webdev_route_status(&self, _route: &str) -> Result<u16, CoreError> {
            unreachable!("not part of this action")
        }
        async fn webdev_route_call(
            &self,
            _project: &str,
            _route: &str,
            _body: &serde_json::Value,
            _extra_headers: &[(&str, &str)],
        ) -> Result<serde_json::Value, CoreError> {
            unreachable!("not part of this action")
        }
        async fn webdev_route_probe(
            &self,
            _project: &str,
            _route: &str,
            _extra_headers: &[(&str, &str)],
        ) -> Result<crate::client::webdev::RouteProbe, CoreError> {
            unreachable!("not part of this action")
        }
        async fn projects(
            &self,
            _query: &crate::client::query::ListQuery,
        ) -> Result<ListEnvelope<ProjectRecord>, CoreError> {
            Ok(page(vec![record("PlantFloor"), record("Base")]))
        }
        async fn project_find(&self, name: &str) -> Result<ProjectRecord, CoreError> {
            self.finds.lock().unwrap().push(name.into());
            if self.absent {
                Err(CoreError::NotFound { endpoint: None })
            } else {
                Ok(record("whatever-the-rig-is-asked-for"))
            }
        }
        async fn project_create(&self, body: &ProjectCreate) -> Result<(), CoreError> {
            self.creates.lock().unwrap().push(body.clone());
            Ok(())
        }
        async fn project_copy(&self, _from: &str, _to: &str) -> Result<(), CoreError> {
            Ok(())
        }
        async fn project_rename(&self, _name: &str, _new_name: &str) -> Result<(), CoreError> {
            Ok(())
        }
        async fn project_modify(&self, name: &str, body: &ProjectModify) -> Result<(), CoreError> {
            self.modifies
                .lock()
                .unwrap()
                .push((name.into(), body.clone()));
            Ok(())
        }
        async fn project_delete(&self, name: &str) -> Result<(), CoreError> {
            self.deletes.lock().unwrap().push(name.into());
            Ok(())
        }
        async fn project_export_to_file(
            &self,
            name: &str,
            out: &std::path::Path,
        ) -> Result<crate::client::projects::ExportMeta, CoreError> {
            self.exports.lock().unwrap().push(name.into());
            let fixture = self.export_body.clone().unwrap_or_else(Self::zip_fixture);
            std::fs::write(out, &fixture)
                .map_err(|err| CoreError::Internal(format!("rig export write: {err}")))?;
            Ok(crate::client::projects::ExportMeta {
                filename: Some("rig-export.zip".into()),
                bytes: fixture.len() as u64,
                content_type: Some("application/zip".into()),
            })
        }
        async fn project_import(
            &self,
            name: &str,
            zip: Vec<u8>,
            overwrite: bool,
        ) -> Result<crate::client::projects::ImportOutcome, CoreError> {
            self.imports
                .lock()
                .unwrap()
                .push((name.into(), zip.len(), overwrite));
            Ok(crate::client::projects::ImportOutcome {
                response: serde_json::json!({"status": "success"}),
            })
        }
    }

    /// THE modify-body pin: `SetOptions` with only `--title` rides the
    /// wire as EXACTLY `{"title":"T"}` — no other keys, no `enabled`
    /// clobber, no `name`.
    #[test]
    fn set_options_only_title_serializes_exactly_title() {
        let opts = SetOptions {
            title: Some("T".into()),
            ..Default::default()
        };
        let body = ProjectModify {
            enabled: opts.enabled,
            title: opts.title.clone(),
            description: opts.description.clone(),
            parent: opts.parent.clone(),
            inheritable: opts.inheritable,
            default_db: None,
            tag_provider: None,
            user_source: None,
        };
        assert_eq!(
            serde_json::to_value(&body).expect("serializes"),
            serde_json::json!({"title": "T"})
        );
    }

    /// The list action selects the six stable fields (passthrough keys
    /// like `defaultDb` stay at the client seam, not the agent shape).
    #[tokio::test]
    async fn projects_action_selects_the_six_stable_fields() {
        let rig = ProjectsRig::default();
        let result = projects(&rig).await.expect("list");
        assert_eq!(result.projects.len(), 2);
        assert_eq!(
            result.projects[0],
            ProjectSummary {
                name: "PlantFloor".into(),
                title: Some("PlantFloor title".into()),
                description: None,
                enabled: true,
                parent: Some("Base".into()),
                inheritable: Some(false),
            }
        );
        // The agent shape carries ALL six keys, always.
        let json = serde_json::to_value(&result).expect("serialize");
        let mut keys: Vec<&str> = json["projects"][0]
            .as_object()
            .unwrap()
            .keys()
            .map(String::as_str)
            .collect();
        keys.sort_unstable();
        assert_eq!(
            keys,
            [
                "description",
                "enabled",
                "inheritable",
                "name",
                "parent",
                "title"
            ]
        );
    }

    /// new = create + find read-back: the create body carries ONLY the
    /// provided fields, and the result is the read-back record.
    #[tokio::test]
    async fn project_new_creates_then_reads_back() {
        let rig = ProjectsRig::default();
        let opts = NewOptions {
            enabled: true,
            title: Some("T".into()),
            description: None,
            parent: Some("Base".into()),
            inheritable: Some(true),
        };
        let summary = project_new(&rig, "child", &opts).await.expect("new");
        assert_eq!(summary.name, "whatever-the-rig-is-asked-for");

        let creates = rig.creates.lock().unwrap();
        assert_eq!(creates.len(), 1);
        assert_eq!(
            serde_json::to_value(&creates[0]).unwrap(),
            serde_json::json!({
                "name": "child",
                "enabled": true,
                "title": "T",
                "parent": "Base",
                "inheritable": true
            })
        );
    }

    /// set = modify-with-Somes + read-back; the result records which
    /// fields were touched (display-only — never in JSON) and the flat
    /// JSON stays the six-key record shape.
    #[tokio::test]
    async fn project_set_modifies_with_somes_and_reads_back() {
        let rig = ProjectsRig::default();
        let opts = SetOptions {
            title: Some("T".into()),
            parent: Some("Base".into()),
            ..Default::default()
        };
        let result = super::project_set(&rig, "x", &opts).await.expect("set");
        assert_eq!(result.fields, vec!["title", "parent"]);

        let modifies = rig.modifies.lock().unwrap();
        assert_eq!(modifies.len(), 1);
        assert_eq!(modifies[0].0, "x");
        assert_eq!(
            serde_json::to_value(&modifies[0].1).unwrap(),
            serde_json::json!({"title": "T", "parent": "Base"})
        );

        // JSON: flat record keys only — `fields` is serde-skipped.
        let json = serde_json::to_value(&result).expect("serialize");
        let keys: Vec<&str> = json
            .as_object()
            .unwrap()
            .keys()
            .map(String::as_str)
            .collect();
        assert_eq!(
            keys,
            [
                "description",
                "enabled",
                "inheritable",
                "name",
                "parent",
                "title"
            ],
            "no `fields` key in the agent shape"
        );
    }

    /// delete = the obedient arm; the guard belongs to the CLI caller.
    #[tokio::test]
    async fn project_delete_records_the_name() {
        let rig = ProjectsRig::default();
        let result = super::project_delete(&rig, "gone").await.expect("delete");
        assert_eq!(result.deleted, "gone");
        assert_eq!(*rig.deletes.lock().unwrap(), vec!["gone".to_string()]);
    }

    /// THE magic-guard pin: a non-ZIP input refuses with exit 2
    /// `invalid_import_file` BEFORE any network I/O — neither the find
    /// pre-check nor the upload ever fires.
    #[tokio::test]
    async fn import_refuses_non_zip_before_any_network() {
        let rig = ProjectsRig::default();
        let err = super::project_import(
            &rig,
            "x",
            b"definitely not a zip".to_vec(),
            super::CollisionPolicy::Abort,
        )
        .await
        .expect_err("the magic guard refuses");
        assert_eq!(
            err.exit_code(),
            2,
            "usage class — the caller must fix the file"
        );
        assert_eq!(err.code(), "invalid_import_file");
        assert!(
            rig.finds.lock().unwrap().is_empty(),
            "zero pre-check calls — the guard runs first"
        );
        assert!(rig.imports.lock().unwrap().is_empty(), "zero uploads");
    }

    /// THE truncated-zip pin (05-07, Rule 2): a zip with VALID magic
    /// but a broken tail — the live-witnessed wipe shape (8.3.3
    /// answers success:true changes:[] and replaces the project with
    /// the partial contents) — refuses `invalid_import_file` exit 2
    /// BEFORE any network I/O.
    #[tokio::test]
    async fn import_refuses_truncated_zip_before_any_network() {
        let rig = ProjectsRig::default();
        let truncated = {
            let full = ProjectsRig::zip_fixture();
            // Keep the magic + most of the body, cut the central
            // directory — exactly the partially-written-writer shape
            // the spike produced.
            let cut = full.len() - 10;
            full[..cut].to_vec()
        };
        let err = super::project_import(&rig, "x", truncated, super::CollisionPolicy::Overwrite)
            .await
            .expect_err("the structure guard refuses");
        assert_eq!(err.exit_code(), 2);
        assert_eq!(err.code(), "invalid_import_file");
        assert!(
            rig.finds.lock().unwrap().is_empty() && rig.imports.lock().unwrap().is_empty(),
            "zero network of any kind — the structure guard runs before everything"
        );
    }

    /// The 512 MB sanity guard refuses with the same slug — checked
    /// through the pure size helper (no half-gigabyte allocation in a
    /// unit test); exactly-at-limit stays allowed.
    #[test]
    fn import_size_guard_refuses_over_512mb() {
        let err = super::import_size_error(super::IMPORT_MAX_BYTES + 1)
            .expect("one byte over the limit refuses");
        assert_eq!(err.exit_code(), 2);
        assert_eq!(err.code(), "invalid_import_file");
        let message = err.to_string();
        assert!(
            message.contains("512 MB"),
            "the reason names the limit: {message}"
        );
        assert!(
            super::import_size_error(super::IMPORT_MAX_BYTES).is_none(),
            "exactly at the limit is fine"
        );
    }

    /// THE collision pin: abort over an existing project (find → Ok)
    /// refuses with `project_exists` (exit 6) BEFORE the upload, and
    /// the hint names BOTH the overwrite flag and its replace-semantics
    /// warning (Pitfall 4).
    #[tokio::test]
    async fn import_abort_over_existing_refuses_project_exists() {
        let rig = ProjectsRig::default(); // find → Ok: the name exists
        let err = super::project_import(
            &rig,
            "PlantFloor",
            ProjectsRig::zip_fixture(),
            super::CollisionPolicy::Abort,
        )
        .await
        .expect_err("the collision pre-check refuses");
        assert!(
            matches!(&err, CoreError::ProjectExists { name, .. } if name == "PlantFloor"),
            "wrong class: {err}"
        );
        assert_eq!(err.exit_code(), 6);
        assert_eq!(err.code(), "project_exists");
        let hint = err.hint().expect("hint required");
        assert!(
            hint.contains("--collision-policy overwrite"),
            "hint names the flag: {hint}"
        );
        assert!(
            hint.contains("ENTIRE project") && hint.contains("Designer-only"),
            "hint warns replace-not-merge: {hint}"
        );
        assert!(
            rig.imports.lock().unwrap().is_empty(),
            "the refusal happened BEFORE any upload"
        );
        assert_eq!(*rig.finds.lock().unwrap(), vec!["PlantFloor".to_string()]);
    }

    /// Abort when the name is FREE: the pre-check passes (find → 404)
    /// and the upload fires with `overwrite=false`.
    #[tokio::test]
    async fn import_abort_when_free_uploads_without_overwrite() {
        let rig = ProjectsRig {
            absent: true,
            ..Default::default()
        };
        let result = super::project_import(
            &rig,
            "fresh",
            ProjectsRig::zip_fixture(),
            super::CollisionPolicy::Abort,
        )
        .await
        .expect("free name imports");
        assert_eq!(result.name, "fresh");
        assert_eq!(result.collision_policy, "abort");
        assert_eq!(result.bytes, ProjectsRig::zip_fixture().len());
        assert_eq!(
            result.scope,
            super::ExportScope::new(),
            "import carries the SAME scope consts as export"
        );
        assert_eq!(
            *rig.imports.lock().unwrap(),
            vec![("fresh".to_string(), ProjectsRig::zip_fixture().len(), false)]
        );
    }

    /// Overwrite: NO pre-check (the server is the authority) — zero
    /// find calls — and the upload fires with `overwrite=true`.
    #[tokio::test]
    async fn import_overwrite_skips_pre_check_and_uploads() {
        let rig = ProjectsRig::default(); // find would answer Ok; it must not be asked
        let result = super::project_import(
            &rig,
            "PlantFloor",
            ProjectsRig::zip_fixture(),
            super::CollisionPolicy::Overwrite,
        )
        .await
        .expect("overwrite imports without a pre-check");
        assert_eq!(result.collision_policy, "overwrite");
        assert!(
            rig.finds.lock().unwrap().is_empty(),
            "overwrite performs ZERO pre-check calls"
        );
        assert_eq!(
            *rig.imports.lock().unwrap(),
            vec![(
                "PlantFloor".to_string(),
                ProjectsRig::zip_fixture().len(),
                true
            )]
        );
    }

    /// Scope arrays are DATA (roadmap criterion 4): tag-providers sit
    /// under excludes, and the serialized shape is the two-key object
    /// agents key off.
    #[test]
    fn export_scope_arrays_are_data() {
        assert!(
            super::EXPORT_EXCLUDES.contains(&"tag-providers"),
            "the headline exclusion (tags are gateway config, not project export)"
        );
        assert!(super::EXPORT_EXCLUDES.contains(&"tags"));
        assert!(super::EXPORT_EXCLUDES.contains(&"udts"));
        assert!(super::EXPORT_INCLUDES.contains(&"views"));
        assert!(super::EXPORT_INCLUDES.contains(&"scripts"));
        assert!(super::EXPORT_INCLUDES.contains(&"named-queries"));
        let json = serde_json::to_value(super::ExportScope::new()).expect("scope serializes");
        assert_eq!(
            json["includes"]
                .as_array()
                .expect("includes is an array")
                .len(),
            super::EXPORT_INCLUDES.len()
        );
        assert_eq!(
            json["excludes"][0], "tag-providers",
            "declaration order is the agent-visible order"
        );
    }

    /// Export with `-o`: the bytes land at exactly the given path and
    /// the result carries file/bytes/scope.
    #[tokio::test]
    async fn export_to_explicit_path_streams_and_reports() {
        let rig = ProjectsRig::default();
        let dir = tempfile::tempdir().expect("tempdir");
        let out = dir.path().join("proj.zip");
        let result = super::project_export(&rig, "My Proj", Some(&out))
            .await
            .expect("export");
        assert_eq!(result.project, "My Proj");
        assert_eq!(result.file, out.display().to_string());
        assert_eq!(result.bytes as usize, ProjectsRig::zip_fixture().len());
        assert_eq!(
            std::fs::read(&out).expect("file written"),
            ProjectsRig::zip_fixture(),
            "the fixture landed byte-for-byte"
        );
        assert_eq!(result.scope, super::ExportScope::new());
        assert_eq!(*rig.exports.lock().unwrap(), vec!["My Proj".to_string()]);
    }

    /// Default-naming hygiene: a disposition basename is stripped to
    /// its final component (`.`/`..`/empty refuse → the caller falls
    /// back), and the `<name>.zip` fallback neutralizes separators.
    #[test]
    fn sanitize_basename_strips_path_components() {
        assert_eq!(
            super::sanitize_basename("MyProj-export.zip"),
            Some("MyProj-export.zip".to_string())
        );
        assert_eq!(
            super::sanitize_basename("../../etc/passwd"),
            Some("passwd".to_string()),
            "path components never survive"
        );
        assert_eq!(
            super::sanitize_basename(r"..\..\win\evil.zip"),
            Some("evil.zip".to_string())
        );
        assert_eq!(super::sanitize_basename(".."), None);
        assert_eq!(super::sanitize_basename("."), None);
        assert_eq!(super::sanitize_basename("   "), None);
        assert_eq!(super::safe_fallback_stem("a/b\\c"), "a_b_c");
    }

    /// THE same-profile refusal (07-01): diffing a profile against
    /// itself is usage-class (exit 2 `invalid_input`) BEFORE any
    /// export fires — zero network work on the refused call.
    #[tokio::test]
    async fn project_diff_same_profile_refuses_before_any_export() {
        let rig = ProjectsRig::default();
        let err = super::project_diff(&rig, &rig, "p", "dev", "dev")
            .await
            .expect_err("the same-profile refusal");
        assert_eq!(err.exit_code(), 2);
        assert_eq!(err.code(), "invalid_input");
        assert!(
            rig.exports.lock().unwrap().is_empty(),
            "zero exports — the refusal leads"
        );
    }

    /// THE selection-less sync refusal (07-01): no `--resource` and
    /// no `--all-changed` is usage-class exit 2 before any export.
    #[tokio::test]
    async fn project_sync_selection_less_refuses_before_any_export() {
        let rig = ProjectsRig::default();
        let err = super::project_sync(
            &rig,
            &rig,
            "p",
            &super::SyncSelection::default(),
            false,
            "a",
            "b",
        )
        .await
        .expect_err("the selection-less refusal");
        assert_eq!(err.exit_code(), 2);
        assert_eq!(err.code(), "invalid_input");
        assert!(rig.exports.lock().unwrap().is_empty());
    }

    // ---- export --decode-scripts (07-04, INTR-01) ----

    /// A script-bearing export zip (the codec's contract shape,
    /// gateway-image escapes): a view member with two embedded
    /// scripts + an expression value, its folder descriptor, a plain
    /// script-python member, and project.json.
    fn script_bearing_zip() -> Vec<u8> {
        use std::io::Write as _;
        let view = br#"{
  "scope": "G",
  "children": [
    {
      "type": "ia.display.label",
      "eventScripts": {
        "actionPerformed": {
          "config": {
            "script": "\tprint \u0027clicked\u0027\n\tprint \u0027done\u0027"
          }
        }
      }
    },
    {
      "type": "ia.chart",
      "transform": {
        "script": "\t\tfor i in range(3):\n\t\t\tprint i\n\t\tprint \u0027end\u0027"
      },
      "props": {
        "expression": "toStr({view.args.x} * 2)"
      }
    }
  ]
}"#;
        let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
        let options = zip::write::SimpleFileOptions::default();
        writer.start_file("project.json", options).expect("starts");
        writer.write_all(br#"{"title":"T"}"#).expect("writes");
        writer
            .start_file("c/resources/views/Dash/view.json", options)
            .expect("starts");
        writer.write_all(view).expect("writes");
        writer
            .start_file("c/resources/views/Dash/resource.json", options)
            .expect("starts");
        writer
            .write_all(br#"{"scope":"G","version":1,"files":["view.json"]}"#)
            .expect("writes");
        writer
            .start_file("ignition/resources/scratch", options)
            .expect("starts");
        writer.write_all(b"print('plain')").expect("writes");
        writer.finish().expect("finalize").into_inner()
    }

    /// The decode-export action: counts honest (members + sidecars),
    /// the directory carries the members + sidecars + manifest, and
    /// the JSON shape rides all keys in declaration order.
    #[tokio::test]
    async fn project_export_decoded_writes_the_tree() {
        let rig = ProjectsRig {
            export_body: Some(script_bearing_zip()),
            ..Default::default()
        };
        let dir = tempfile::tempdir().expect("tempdir");
        let result = super::project_export_decoded(&rig, "p", Some(dir.path()))
            .await
            .expect("decode export");
        assert_eq!(result.members, 4);
        assert_eq!(result.scripts_decoded, 2);
        assert_eq!(result.dir, dir.path().display().to_string());
        assert!(
            dir.path()
                .join("c/resources/views/Dash/view.json.1.py")
                .is_file()
        );
        assert!(
            dir.path()
                .join("c/resources/views/Dash/view.json.2.py")
                .is_file()
        );
        assert!(
            dir.path()
                .join(crate::client::scripts_codec::MANIFEST_NAME)
                .is_file()
        );
        // The plain script-python member rides verbatim (scope
        // honesty: already plain .py text — never decoded).
        assert_eq!(
            std::fs::read(dir.path().join("ignition/resources/scratch")).expect("scratch member"),
            b"print('plain')"
        );
        // Agent shape: all keys present (the declaration order is the
        // struct's — pinned by the CLI golden; a Value walk sorts).
        let json = serde_json::to_value(&result).expect("serialize");
        let mut keys: Vec<&str> = json
            .as_object()
            .unwrap()
            .keys()
            .map(String::as_str)
            .collect();
        keys.sort_unstable();
        assert_eq!(
            keys,
            [
                "bytes",
                "dir",
                "members",
                "project",
                "scope",
                "scripts_decoded"
            ]
        );
    }
}