ommx 3.0.0-beta.1

Open Mathematical prograMming eXchange (OMMX)
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
use super::{
    digest::sha256_digest,
    ghcr,
    local_registry::{
        LocalRegistry, RefUpdate, StoredDescriptor, TempLocalRegistry, UnsealedArtifact,
    },
    media_types::{self, OCI_EMPTY_CONFIG_BYTES},
    ImageRef,
};
use anyhow::{bail, ensure, Context, Result};
use oci_spec::image::{Descriptor, DescriptorBuilder, Digest, ImageManifest, MediaType};
use serde::Serialize;
use std::{
    collections::HashMap,
    path::Path,
    str::FromStr,
    sync::{Arc, OnceLock},
};
use url::Url;

/// OMMX Artifact stored in the SQLite-backed Local Registry.
///
/// Holds a reference to the [`LocalRegistry`] that stores the manifest
/// and layer blobs. `LocalArtifact` is a lazy view: it owns the image
/// name and manifest digest, but reads payload bytes through the
/// registry reference on demand.
///
/// The parsed manifest is memoised in an `Arc<OnceLock<LocalManifest>>`
/// so repeated calls to [`Self::layers`] / [`Self::annotations`] /
/// [`Self::subject`] do not re-read the manifest blob, requery the
/// registry index, and re-parse the JSON each time. Clones of the artifact
/// share the same cell, so any clone that reads the manifest first warms it
/// for the rest.
#[derive(Debug, Clone)]
pub struct LocalArtifact<'reg> {
    registry: &'reg LocalRegistry,
    image_name: ImageRef,
    manifest_digest: Digest,
    manifest_cache: Arc<OnceLock<LocalManifest>>,
}

/// Runtime-owned Local Registry handle.
///
/// This is the dynamic-lifetime counterpart of `&LocalRegistry`.
/// It exists for bindings and other dynamic runtimes that cannot
/// express Rust lifetimes in their object model. Values that borrow a
/// registry with an erased `'static` lifetime must carry the same
/// handle so the registry owner outlives those values.
#[derive(Debug, Clone)]
pub struct LocalRegistryHandle {
    inner: Arc<LocalRegistryHandleInner>,
}

#[derive(Debug)]
enum LocalRegistryHandleInner {
    Default(&'static LocalRegistry),
    Temp(TempLocalRegistry),
}

impl LocalRegistryHandle {
    pub fn shared_default() -> Result<Self> {
        Ok(Self {
            inner: Arc::new(LocalRegistryHandleInner::Default(
                LocalRegistry::shared_default()?,
            )),
        })
    }

    pub fn temp() -> Result<Self> {
        Ok(Self {
            inner: Arc::new(LocalRegistryHandleInner::Temp(TempLocalRegistry::new()?)),
        })
    }

    pub fn registry(&self) -> &LocalRegistry {
        match self.inner.as_ref() {
            LocalRegistryHandleInner::Default(registry) => registry,
            LocalRegistryHandleInner::Temp(temp) => temp.registry(),
        }
    }

    /// Read a blob referenced by an owned OCI descriptor from this registry.
    ///
    /// Dynamic-lifetime handles store raw [`Descriptor`] values internally
    /// because they cannot carry `StoredDescriptor<'reg>` lifetimes. This
    /// method revalidates the descriptor against the backing Local Registry
    /// before reading the blob bytes.
    pub fn get_blob_dyn(&self, descriptor: &Descriptor) -> Result<Vec<u8>> {
        let descriptor = self.registry().stored_descriptor(descriptor.clone())?;
        self.registry().get_blob(&descriptor)
    }
}

/// Runtime-owned artifact handle for dynamic runtimes.
///
/// This stores only owned artifact identity plus the registry owner.
/// When an operation needs the lifetime-based [`LocalArtifact`] API, it
/// reconstructs a short-lived `LocalArtifact<'_>` from the handle's
/// current registry reference.
#[derive(Debug, Clone)]
pub struct LocalArtifactDyn {
    registry_handle: LocalRegistryHandle,
    image_name: ImageRef,
    manifest_digest: Digest,
    manifest_cache: Arc<OnceLock<LocalManifest>>,
}

impl LocalArtifactDyn {
    pub fn open(image_name: ImageRef) -> Result<Self> {
        let registry_handle = LocalRegistryHandle::shared_default()?;
        Self::open_in_registry_handle(registry_handle, image_name)
    }

    /// Import an OCI archive file or OCI Image Layout directory into the
    /// default Local Registry and return the imported artifact.
    pub fn import_archive(path: &Path) -> Result<Self> {
        let registry_handle = LocalRegistryHandle::shared_default()?;
        let registry = registry_handle.registry();

        let image_name = if path.is_file() {
            registry.import_oci_archive(path)?.image_name
        } else if path.is_dir() {
            registry.import_oci_dir(path)?.image_name
        } else {
            bail!("Path must be a file or a directory")
        };

        Self::open_in_registry_handle(registry_handle, image_name)
    }

    /// Load an artifact by image reference from the default Local Registry.
    ///
    /// With `remote-artifact` enabled, this mirrors Python
    /// `Artifact.load`: if the default Local Registry does not already
    /// contain a complete copy, pull the image from the remote registry
    /// into the Local Registry before opening it.
    #[cfg(feature = "remote-artifact")]
    pub fn load(image_name: ImageRef) -> Result<Self> {
        let registry_handle = LocalRegistryHandle::shared_default()?;
        registry_handle.registry().pull_image(&image_name)?;
        Self::open_in_registry_handle(registry_handle, image_name)
    }

    /// Load an artifact by image reference from the default Local Registry.
    ///
    /// Without `remote-artifact`, loading is local-only.
    #[cfg(not(feature = "remote-artifact"))]
    pub fn load(image_name: ImageRef) -> Result<Self> {
        Self::open(image_name)
    }

    pub fn open_in_registry_handle(
        registry_handle: LocalRegistryHandle,
        image_name: ImageRef,
    ) -> Result<Self> {
        let manifest_digest = registry_handle
            .registry()
            .resolve_image_name(&image_name)?
            .with_context(|| {
                format!(
                    "Artifact not found in the SQLite-backed local registry: {image_name}. \
                         If this artifact exists in the legacy OCI directory local registry, \
                         run `ommx import-legacy` once, then retry."
                )
            })?;
        Ok(Self {
            registry_handle,
            image_name,
            manifest_digest,
            manifest_cache: Arc::new(OnceLock::new()),
        })
    }

    pub(crate) fn as_local_artifact(&self) -> LocalArtifact<'_> {
        LocalArtifact {
            registry: self.registry_handle.registry(),
            image_name: self.image_name.clone(),
            manifest_digest: self.manifest_digest.clone(),
            manifest_cache: Arc::clone(&self.manifest_cache),
        }
    }

    pub fn registry_handle(&self) -> LocalRegistryHandle {
        self.registry_handle.clone()
    }

    pub fn image_name(&self) -> &ImageRef {
        &self.image_name
    }

    pub fn manifest_digest(&self) -> &Digest {
        &self.manifest_digest
    }

    pub fn annotations(&self) -> Result<HashMap<String, String>> {
        self.as_local_artifact().annotations()
    }

    pub fn layers(&self) -> Result<Vec<StoredDescriptor<'_>>> {
        self.as_local_artifact().layers()
    }

    pub fn get_blob(&self, descriptor: &Descriptor) -> Result<Vec<u8>> {
        self.registry_handle.get_blob_dyn(descriptor)
    }

    pub fn get_instance_layer(&self, descriptor: &Descriptor) -> Result<crate::Instance> {
        let descriptor = self
            .registry_handle
            .registry()
            .stored_descriptor(descriptor.clone())?;
        self.registry_handle
            .registry()
            .get_instance_layer(&descriptor)
    }

    pub fn get_parametric_instance_layer(
        &self,
        descriptor: &Descriptor,
    ) -> Result<crate::ParametricInstance> {
        let descriptor = self
            .registry_handle
            .registry()
            .stored_descriptor(descriptor.clone())?;
        self.registry_handle
            .registry()
            .get_parametric_instance_layer(&descriptor)
    }

    pub fn get_solution_layer(&self, descriptor: &Descriptor) -> Result<crate::Solution> {
        let descriptor = self
            .registry_handle
            .registry()
            .stored_descriptor(descriptor.clone())?;
        self.registry_handle
            .registry()
            .get_solution_layer(&descriptor)
    }

    pub fn get_sample_set_layer(&self, descriptor: &Descriptor) -> Result<crate::SampleSet> {
        let descriptor = self
            .registry_handle
            .registry()
            .stored_descriptor(descriptor.clone())?;
        self.registry_handle
            .registry()
            .get_sample_set_layer(&descriptor)
    }

    pub fn save(&self, output: &Path) -> crate::Result<()> {
        AsArtifact::save(self, output)
    }

    #[cfg(feature = "remote-artifact")]
    pub fn push(&self) -> crate::Result<()> {
        AsArtifact::push(self)
    }

    pub fn tag_as(&self, image_name: ImageRef) -> Result<Self> {
        let artifact = self.as_local_artifact().tag_as(image_name)?;
        Ok(Self {
            registry_handle: self.registry_handle.clone(),
            image_name: artifact.image_name().clone(),
            manifest_digest: artifact.manifest_digest().clone(),
            manifest_cache: Arc::new(OnceLock::new()),
        })
    }
}

/// Values that can be viewed as a committed OMMX Artifact.
///
/// Implementors may be domain objects such as Experiment handles, or the
/// artifact handle itself. The returned [`LocalArtifact`] is a borrowed view
/// tied to `self`, so implementors that own a [`LocalRegistryHandle`] can keep
/// the underlying registry alive while exposing the lifetime-based artifact API.
pub trait AsArtifact<'reg> {
    /// Return the committed artifact view backing this value.
    fn as_artifact(&'reg self) -> crate::Result<LocalArtifact<'reg>>;

    /// Save the committed artifact as a `.ommx` OCI archive file.
    fn save(&'reg self, output: &Path) -> crate::Result<()> {
        self.as_artifact()?.save(output)
    }

    /// Push the committed artifact to its remote registry.
    #[cfg(feature = "remote-artifact")]
    fn push(&'reg self) -> crate::Result<()> {
        self.as_artifact()?.push()
    }
}

impl<'reg> AsArtifact<'reg> for LocalArtifactDyn {
    fn as_artifact(&'reg self) -> crate::Result<LocalArtifact<'reg>> {
        Ok(self.as_local_artifact())
    }
}

impl LocalArtifact<'static> {
    pub fn open(image_name: ImageRef) -> Result<Self> {
        let registry = LocalRegistry::shared_default()?;
        Self::open_in_registry(registry, image_name)
    }

    pub fn try_open(image_name: ImageRef) -> Result<Option<Self>> {
        let registry = LocalRegistry::shared_default()?;
        Self::try_open_in_registry(registry, image_name)
    }
}

impl<'reg> LocalArtifact<'reg> {
    pub(crate) fn from_parts(
        registry: &'reg LocalRegistry,
        image_name: ImageRef,
        manifest_digest: Digest,
    ) -> Self {
        Self {
            registry,
            image_name,
            manifest_digest,
            manifest_cache: Arc::new(OnceLock::new()),
        }
    }

    pub fn open_in_registry(registry: &'reg LocalRegistry, image_name: ImageRef) -> Result<Self> {
        Self::try_open_in_registry(registry, image_name.clone())?.with_context(|| {
            format!(
                "Artifact not found in the SQLite-backed local registry: {image_name}. \
                 If this artifact exists in the legacy OCI directory local registry, \
                 run `ommx import-legacy` once, then retry."
            )
        })
    }

    pub fn try_open_in_registry(
        registry: &'reg LocalRegistry,
        image_name: ImageRef,
    ) -> Result<Option<Self>> {
        let Some(manifest_digest) = registry.resolve_image_name(&image_name)? else {
            return Ok(None);
        };
        Ok(Some(Self::from_parts(
            registry,
            image_name,
            manifest_digest,
        )))
    }

    pub fn image_name(&self) -> &ImageRef {
        &self.image_name
    }

    pub fn manifest_digest(&self) -> &Digest {
        &self.manifest_digest
    }

    pub(crate) fn registry(&self) -> &'reg LocalRegistry {
        self.registry
    }

    /// Read and cache the manifest associated with this artifact.
    ///
    /// The first successful call populates a shared `OnceLock`; later
    /// calls (and clones of `self`) reuse the cached value without
    /// touching the Local Registry again. Failed reads are not cached,
    /// so transient errors retry on the next call.
    pub fn get_manifest(&self) -> Result<&LocalManifest> {
        if let Some(cached) = self.manifest_cache.get() {
            return Ok(cached);
        }
        let manifest = self.read_manifest_uncached()?;
        Ok(self.manifest_cache.get_or_init(|| manifest))
    }

    fn read_manifest_uncached(&self) -> Result<LocalManifest> {
        let bytes = self.registry.read_blob(&self.manifest_digest)?;
        LocalManifest::parse(&bytes)
    }

    pub fn annotations(&self) -> Result<HashMap<String, String>> {
        Ok(self.get_manifest()?.annotations())
    }

    pub fn stored_config(&self) -> Result<StoredDescriptor<'reg>> {
        self.registry
            .stored_descriptor(self.get_manifest()?.config())
    }

    pub fn layers(&self) -> Result<Vec<StoredDescriptor<'reg>>> {
        self.get_manifest()?
            .layers()
            .into_iter()
            .map(|descriptor| self.registry.stored_descriptor(descriptor))
            .collect()
    }

    pub fn subject(&self) -> Result<Option<Descriptor>> {
        Ok(self.get_manifest()?.subject())
    }

    pub fn get_blob(&self, descriptor: &StoredDescriptor<'_>) -> Result<Vec<u8>> {
        ensure!(
            descriptor.is_stored_in(self.registry),
            "Descriptor {} is not stored in this LocalArtifact's Local Registry",
            descriptor.digest()
        );
        self.registry.get_blob(descriptor)
    }

    pub(crate) fn get_blob_by_descriptor(&self, descriptor: &Descriptor) -> Result<Vec<u8>> {
        let descriptor = self.registry.stored_descriptor(descriptor.clone())?;
        self.get_blob(&descriptor)
    }

    pub(crate) fn read_blob_by_digest(&self, digest: &Digest) -> Result<Vec<u8>> {
        self.registry.read_blob(digest)
    }

    pub(crate) fn stored_manifest_descriptor(&self) -> Result<StoredDescriptor<'reg>> {
        self.registry
            .stored_manifest_descriptor(&self.manifest_digest)
    }

    /// Publish this artifact under another local image reference.
    ///
    /// This does not rewrite the manifest or payload blobs. It only adds a
    /// new Local Registry ref to the same root manifest digest and returns a
    /// handle whose `image_name` is the new reference.
    pub fn tag_as(&self, image_name: ImageRef) -> Result<Self> {
        let ref_update = self
            .registry
            .publish_existing_manifest_ref(&image_name, &self.manifest_digest)?;
        reject_conflicting_ref(&image_name, ref_update)?;
        Ok(Self::from_parts(
            self.registry,
            image_name,
            self.manifest_digest.clone(),
        ))
    }
}

/// A manifest read from the SQLite Local Registry. v3 stores OCI Image
/// Manifest as the only native format; OMMX artifacts are identified
/// at parse time by the `artifactType` field (validated against the
/// OMMX-owned artifact type set). The native build path also
/// writes an `application/vnd.oci.empty.v1+json` empty config descriptor
/// — matching the SDK v2 archive build — but `parse` does not assert
/// on the config blob, so legacy v2 imports that carry an OMMX-specific
/// config remain readable. The deprecated OCI Artifact Manifest media
/// type (`application/vnd.oci.artifact.manifest.v1+json`) is rejected
/// at parse time rather than supported via a second enum variant.
///
/// Boxed because `oci_spec`'s `ImageManifest` is large (~800 bytes) and
/// callers move `LocalManifest` around inside `Arc<OnceLock<...>>`.
#[derive(Debug, Clone)]
pub struct LocalManifest(Box<ImageManifest>);

impl LocalManifest {
    fn parse(bytes: &[u8]) -> Result<Self> {
        let manifest: ImageManifest =
            serde_json::from_slice(bytes).context("Failed to parse OCI image manifest")?;
        ensure_ommx_image_manifest(&manifest)?;
        Ok(Self(Box::new(manifest)))
    }

    pub fn media_type(&self) -> &'static str {
        media_types::OCI_IMAGE_MANIFEST_MEDIA_TYPE
    }

    /// Always returns the OMMX `artifactType` discriminator. `parse`
    /// rejects manifests without one (see `ensure_ommx_image_manifest`),
    /// so this method does not surface an `Option`.
    pub fn artifact_type(&self) -> &MediaType {
        self.0
            .artifact_type()
            .as_ref()
            .expect("ensure_ommx_image_manifest guarantees Image Manifest carries an artifactType")
    }

    pub fn config(&self) -> Descriptor {
        self.0.config().clone()
    }

    pub fn layers(&self) -> Vec<Descriptor> {
        self.0.layers().to_vec()
    }

    /// Consume this wrapper and return the inner OCI Image Manifest.
    /// Used by callers that need to round-trip the manifest as JSON
    /// (e.g. the CLI's `ommx inspect`), where the standard OCI
    /// `serde` form is what's expected. The accessors above cover
    /// programmatic use; `into_inner` is the escape hatch when the
    /// whole thing needs to leave the wrapper.
    pub fn into_inner(self) -> ImageManifest {
        *self.0
    }

    /// Borrow the validated OCI Image Manifest for crate-internal projection
    /// builders that need the parsed manifest and the original JSON bytes.
    pub(crate) fn as_image_manifest(&self) -> &ImageManifest {
        &self.0
    }

    pub fn annotations(&self) -> HashMap<String, String> {
        self.0.annotations().clone().unwrap_or_default()
    }

    pub fn subject(&self) -> Option<Descriptor> {
        self.0.subject().clone()
    }
}

/// Mutable draft for an OMMX Artifact stored in the SQLite-backed Local Registry.
///
/// Produces an OCI Image Manifest with `artifactType` set to the OMMX
/// artifact media type and the OCI 1.1 empty config descriptor as
/// `config`. The layer blobs land in the Image Manifest's `layers[]`
/// field.
#[derive(Debug, Clone)]
pub struct ArtifactDraft<'reg> {
    registry: &'reg LocalRegistry,
    image_name: ImageRef,
    artifact_type: MediaType,
    layers: Vec<StoredDescriptor<'reg>>,
    subject: Option<Descriptor>,
    annotations: HashMap<String, String>,
}

impl ArtifactDraft<'static> {
    pub fn new(image_name: ImageRef) -> Result<Self> {
        let registry = LocalRegistry::shared_default()?;
        Ok(Self::with_registry(registry, image_name))
    }

    pub fn new_anonymous() -> Result<Self> {
        let registry = LocalRegistry::shared_default()?;
        Self::new_anonymous_in_registry(registry)
    }

    /// Draft under a random `ttl.sh/<uuid>:1h` image name. Insecure;
    /// for tests only.
    pub fn temp() -> Result<Self> {
        let id = uuid::Uuid::new_v4();
        let image_name = ImageRef::parse(&format!("ttl.sh/{id}:1h"))?;
        Self::new(image_name)
    }

    /// Create a new artifact draft for a GitHub container registry image name.
    pub fn for_github(org: &str, repo: &str, name: &str, tag: &str) -> Result<Self> {
        let image_name = ghcr(org, repo, name, tag)?;
        let source = Url::parse(&format!("https://github.com/{org}/{repo}"))?;

        let mut draft = Self::new(image_name)?;
        draft.add_source(&source);
        Ok(draft)
    }
}

impl<'reg> ArtifactDraft<'reg> {
    /// Create a temporary Local Registry, create an artifact draft
    /// under `image_name`, and run a callback while the registry is
    /// alive.
    ///
    /// This is intended for Rust SDK tests that need to exercise the
    /// Local Registry-backed artifact path without writing to the
    /// user's persistent registry.
    pub fn with_temp_local_registry<T>(
        image_name: ImageRef,
        f: impl FnOnce(ArtifactDraft<'_>) -> Result<T>,
    ) -> Result<T> {
        let temp = TempLocalRegistry::new()?;
        let draft = ArtifactDraft::with_registry(temp.registry(), image_name);
        f(draft)
    }

    pub fn with_registry(registry: &'reg LocalRegistry, image_name: ImageRef) -> Self {
        Self {
            registry,
            image_name,
            artifact_type: MediaType::Other(media_types::V1_ARTIFACT_MEDIA_TYPE.to_string()),
            layers: Vec::new(),
            subject: None,
            annotations: HashMap::new(),
        }
    }

    /// Draft for an artifact whose name is auto-generated. UX
    /// shortcut for "I just want to share this artifact, I don't want
    /// to invent a real name". The synthesized image name has the form
    /// `<registry-id8>.ommx.local/anonymous:<local-timestamp>-<nonce>`;
    /// the registry-id prefix is generated once when each
    /// [`LocalRegistry`] is first created and persisted in its SQLite
    /// metadata, so anonymous artifacts from the same registry share
    /// a prefix and can be told apart from artifacts imported from
    /// another registry. Use `ommx prune-anonymous` to clean
    /// accumulated entries.
    ///
    /// Anonymous artifacts are designed to be transient and unique by
    /// timestamp + nonce. The 48-bit nonce in
    /// `anonymous_artifact_image_name` makes collisions astronomically
    /// rare in practice; if one still occurs, commit surfaces it as a
    /// normal ref conflict.
    pub fn new_anonymous_in_registry(registry: &'reg LocalRegistry) -> Result<Self> {
        let registry_id = registry.registry_id()?;
        let image_name = anonymous_artifact_image_name(&registry_id)?;
        Ok(Self::with_registry(registry, image_name))
    }

    pub fn add_layer_bytes(
        &mut self,
        media_type: MediaType,
        bytes: Vec<u8>,
        annotations: HashMap<String, String>,
    ) -> Result<StoredDescriptor<'reg>> {
        let descriptor = descriptor_from_bytes(media_type, &bytes, annotations)?;
        let stored_descriptor = self.registry.store_blob(descriptor, &bytes)?;
        self.layers.push(stored_descriptor.clone());
        Ok(stored_descriptor)
    }

    pub fn add_instance(&mut self, instance: crate::Instance) -> Result<StoredDescriptor<'reg>> {
        let stored_descriptor = self.registry.store_instance_layer(&instance)?;
        self.layers.push(stored_descriptor.clone());
        Ok(stored_descriptor)
    }

    pub fn add_solution(&mut self, solution: crate::Solution) -> Result<StoredDescriptor<'reg>> {
        let stored_descriptor = self.registry.store_solution_layer(&solution)?;
        self.layers.push(stored_descriptor.clone());
        Ok(stored_descriptor)
    }

    pub fn add_parametric_instance(
        &mut self,
        instance: crate::ParametricInstance,
    ) -> Result<StoredDescriptor<'reg>> {
        let stored_descriptor = self.registry.store_parametric_instance_layer(&instance)?;
        self.layers.push(stored_descriptor.clone());
        Ok(stored_descriptor)
    }

    pub fn add_sample_set(
        &mut self,
        sample_set: crate::SampleSet,
    ) -> Result<StoredDescriptor<'reg>> {
        let stored_descriptor = self.registry.store_sample_set_layer(&sample_set)?;
        self.layers.push(stored_descriptor.clone());
        Ok(stored_descriptor)
    }

    pub fn set_subject(&mut self, subject: Descriptor) -> &mut Self {
        self.subject = Some(subject);
        self
    }

    pub fn add_annotation(&mut self, key: impl Into<String>, value: impl Into<String>) {
        self.annotations.insert(key.into(), value.into());
    }

    pub fn add_source(&mut self, url: &Url) {
        self.add_annotation("org.opencontainers.image.source", url.to_string());
    }

    pub fn commit(self) -> Result<LocalArtifact<'reg>> {
        self.commit_inner(false)
    }

    pub fn commit_replace(self) -> Result<LocalArtifact<'reg>> {
        self.commit_inner(true)
    }

    fn commit_inner(self, replace_ref: bool) -> Result<LocalArtifact<'reg>> {
        let registry = self.registry;
        let image_name = self.image_name.clone();
        let artifact = self.into_unsealed_artifact()?;
        let sealed_artifact = registry.seal_artifact(artifact)?;
        let ref_update = if replace_ref {
            registry.replace_manifest_ref(&image_name, &sealed_artifact)?
        } else {
            registry.publish_manifest_ref(&image_name, &sealed_artifact)?
        };
        reject_conflicting_ref(&image_name, ref_update)?;
        Ok(LocalArtifact::from_parts(
            registry,
            image_name,
            sealed_artifact.digest().clone(),
        ))
    }

    /// Convert the in-memory draft state into unsealed manifest state.
    ///
    /// Matches the
    /// SDK v2 / `ArchiveArtifactBuilder` manifest shape (see
    /// `ocipkg::image::OciArtifactBuilder::new`): `schemaVersion: 2` +
    /// `artifactType` + empty config + layers, with the manifest's
    /// own `mediaType` field intentionally absent so `ArtifactDraft`
    /// and the archive build path produce structurally identical
    /// manifests.
    fn into_unsealed_artifact(self) -> Result<UnsealedArtifact<'reg>> {
        // V2 SDK's `ocipkg::OciArtifactBuilder::add_empty_json` emits the
        // empty config descriptor without an `annotations` field; build
        // it directly here (bypassing `descriptor_from_bytes`, which
        // always renders `annotations` even when empty for layer
        // descriptors) so the resulting manifest matches v2 byte-for-byte.
        let empty_config_bytes = OCI_EMPTY_CONFIG_BYTES.to_vec();
        let config_descriptor = DescriptorBuilder::default()
            .media_type(MediaType::EmptyJSON)
            .digest(
                Digest::from_str(&sha256_digest(&empty_config_bytes))
                    .context("Failed to parse empty config digest")?,
            )
            .size(empty_config_bytes.len() as u64)
            .build()
            .context("Failed to build empty config descriptor")?;
        let config_descriptor = self
            .registry
            .store_blob(config_descriptor, &empty_config_bytes)?;

        Ok(UnsealedArtifact::new(
            self.artifact_type,
            config_descriptor,
            self.layers,
            self.subject,
            self.annotations,
        ))
    }
}

pub(crate) fn descriptor_from_bytes(
    media_type: MediaType,
    bytes: &[u8],
    annotations: HashMap<String, String>,
) -> Result<Descriptor> {
    let digest = Digest::from_str(&sha256_digest(bytes)).context("Failed to parse blob digest")?;
    // `annotations` is always set, even when empty, matching SDK v2 /
    // `ocipkg::OciArtifactBuilder::add_layer` which renders the field as
    // `"annotations": {}` in the manifest JSON. Preserving this shape
    // keeps layer descriptor bytes (and therefore the manifest digest)
    // byte-for-byte compatible with v2 OMMX artifacts.
    let descriptor = DescriptorBuilder::default()
        .media_type(media_type)
        .digest(digest)
        .size(bytes.len() as u64)
        .annotations(annotations)
        .build()
        .context("Failed to build OCI descriptor")?;
    Ok(descriptor)
}

pub(crate) fn stable_json_bytes(value: &impl Serialize) -> Result<Vec<u8>> {
    let mut value = serde_json::to_value(value).context("Failed to encode JSON value")?;
    value.sort_all_objects();
    serde_json::to_vec(&value).context("Failed to encode stable JSON bytes")
}

fn reject_conflicting_ref(image_name: &ImageRef, ref_update: RefUpdate) -> Result<()> {
    if let RefUpdate::Conflicted {
        existing_manifest_digest,
        incoming_manifest_digest,
    } = ref_update
    {
        bail!(
            "Local registry ref {image_name} already points to {existing_manifest_digest}; \
             incoming manifest {incoming_manifest_digest} was not published"
        );
    }
    Ok(())
}

fn ensure_ommx_image_manifest(manifest: &ImageManifest) -> Result<()> {
    let artifact_type = manifest
        .artifact_type()
        .as_ref()
        .context("OCI image manifest is not an OMMX artifact: artifactType is missing")?;
    anyhow::ensure!(
        media_types::is_ommx_artifact_type(artifact_type),
        "OCI image manifest is not an OMMX artifact: {artifact_type}",
    );
    Ok(())
}

/// Suffix shared by every anonymous artifact repository name. The
/// full SQLite ref name is `<registry-id8>.ommx.local/anonymous`; the
/// registry-id prefix is randomised per registry, so filtering
/// anonymous artifacts uses
/// `name.ends_with(ANONYMOUS_ARTIFACT_REF_NAME_SUFFIX)`.
/// `ommx prune-anonymous` cleans entries from every prefix
/// in the registry, not just the host's own.
///
/// The hostname segment `.ommx.local` deliberately uses the `.local`
/// link-local TLD (RFC 6762, multicast DNS). A push attempt against
/// this name resolves through mDNS rather than DNS — so an accidental
/// `ommx push <anonymous>` cannot leak the artifact to a real remote
/// registry; absent an mDNS responder, the push just fails locally.
/// Internal-only suffix shared by every anonymous artifact ref name.
/// Use [`is_anonymous_artifact_ref_name`] for the structural match
/// predicate — that is the stable public API; this literal can change
/// over time without breaking external users.
pub(crate) const ANONYMOUS_ARTIFACT_REF_NAME_SUFFIX: &str = ".ommx.local/anonymous";
pub(crate) const ANONYMOUS_EXPERIMENT_REF_NAME_SUFFIX: &str = ".ommx.local/experiment";

/// Number of hex chars from the full registry-id used as the
/// hostname prefix. The metadata column stores the full 32-hex UUID;
/// only the hostname rendering truncates. Picked so the prefix is
/// short enough to read at a glance but wide enough (2^32) to avoid
/// realistic collisions across a single user's registries.
const ANONYMOUS_REGISTRY_ID_HOST_LEN: usize = 8;

/// Hex chars of the random nonce appended to the timestamp tag.
/// 12 hex = 48 bits = ~2.8 × 10^14 possible nonces; at N=10 000
/// concurrent anonymous builds the birthday-paradox collision
/// probability is ~1.8 × 10^-7. Combined with the seconds-level
/// timestamp prefix, this gives a practical zero collision rate even
/// on platforms whose `clock_gettime` resolution is only microseconds
/// (notably macOS — chrono's `%.9f` pads with zeros there, so the
/// timestamp alone would not differentiate builds within the same
/// microsecond). 32 bits (8 hex) would only give P ~ 1.2 × 10^-2 at
/// the same scale, so the extra 4 hex chars are worth the tag-length
/// cost.
const ANONYMOUS_TAG_NONCE_HEX_LEN: usize = 12;

/// Generate a synthetic [`ImageRef`] for an anonymous
/// artifact. Build the image name from the registry's persisted
/// `registry_id` (so the prefix matches the destination registry,
/// not the default registry), plus a local-time timestamp + random
/// nonce tag.
///
/// Format: `<registry-id8>.ommx.local/anonymous:<local-time>-<nonce>`
/// where
/// - `<registry-id8>` is the first
///   [`ANONYMOUS_REGISTRY_ID_HOST_LEN`] hex chars of the registry's
///   `registry_id` metadata (a random UUID generated once per
///   [`LocalRegistry`] on first init). The full UUID stays on disk
///   for future widening; only the rendering truncates.
/// - `<local-time>` is `YYYYMMDDTHHMMSS` in the caller's **local**
///   time zone (no `Z` / no offset — OCI tag syntax forbids `+`, and
///   a fixed UTC marker would defeat the "I can read the date at a
///   glance" intent). A registry shared across machines in different
///   timezones loses the time component's absolute meaning, which is
///   an explicit non-goal for anonymous artifacts.
/// - `<nonce>` is [`ANONYMOUS_TAG_NONCE_HEX_LEN`] hex chars of a fresh
///   UUID v4. Required for MINTO-style concurrent build patterns
///   (scripts emitting many anonymous artifacts per second): without
///   it, two builds in the same second would synthesize the same tag
///   and conflict on the same ref. A remaining astronomically rare
///   nonce collision is reported as a normal publish conflict.
pub(crate) fn anonymous_artifact_image_name(registry_id: &str) -> Result<ImageRef> {
    anonymous_local_image_name(registry_id, "anonymous")
        .with_context(|| "Failed to synthesise anonymous artifact image name")
}

pub(crate) fn anonymous_local_repository_key(
    registry_id: &str,
    repository: &str,
) -> Result<String> {
    anyhow::ensure!(
        !repository.is_empty()
            && repository
                .chars()
                .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_'),
        "Anonymous local repository name must be lowercase OCI-safe text; got {repository:?}",
    );
    let prefix: String = registry_id
        .chars()
        .take(ANONYMOUS_REGISTRY_ID_HOST_LEN)
        .collect();
    anyhow::ensure!(
        prefix.len() == ANONYMOUS_REGISTRY_ID_HOST_LEN
            && prefix
                .chars()
                .all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c)),
        "Anonymous artifact registry id must be at least {} lowercase hex chars; got {prefix:?}",
        ANONYMOUS_REGISTRY_ID_HOST_LEN,
    );
    Ok(format!("{prefix}.ommx.local/{repository}"))
}

pub(crate) fn anonymous_local_image_name(registry_id: &str, repository: &str) -> Result<ImageRef> {
    let repository_key = anonymous_local_repository_key(registry_id, repository)?;
    let stamp = chrono::Local::now().format("%Y%m%dT%H%M%S");
    let nonce: String = uuid::Uuid::new_v4()
        .simple()
        .to_string()
        .chars()
        .take(ANONYMOUS_TAG_NONCE_HEX_LEN)
        .collect();
    ImageRef::parse(&format!("{repository_key}:{stamp}-{nonce}")).with_context(|| {
        format!("Invalid anonymous local image name for registry {repository_key}")
    })
}

/// True iff `name` (the `host/path` portion of an OCI ref) matches the
/// shape an anonymous artifact's image name would take: an 8-hex
/// `<host>.ommx.local/anonymous` repository. Used by
/// `prune-anonymous` to filter SQLite refs without false-positives on
/// human-pushed refs that happen to share the suffix
/// (e.g. an artifact pushed to a real mDNS host named
/// `myhost.ommx.local`).
pub fn is_anonymous_artifact_ref_name(name: &str) -> bool {
    is_anonymous_local_ref_name(name, ANONYMOUS_ARTIFACT_REF_NAME_SUFFIX)
}

pub(crate) fn is_anonymous_experiment_ref_name(name: &str) -> bool {
    is_anonymous_local_ref_name(name, ANONYMOUS_EXPERIMENT_REF_NAME_SUFFIX)
}

fn is_anonymous_local_ref_name(name: &str, suffix: &str) -> bool {
    let Some(host_segment) = name.strip_suffix(suffix) else {
        return false;
    };
    host_segment.len() == ANONYMOUS_REGISTRY_ID_HOST_LEN
        && host_segment
            .chars()
            .all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c))
}

/// True iff `tag` matches the `YYYYMMDDTHHMMSS-<nonce>` shape that
/// `anonymous_artifact_image_name` generates: 15 timestamp chars
/// (digits with `T` at position 8), `-` separator, and
/// `ANONYMOUS_TAG_NONCE_HEX_LEN` lowercase hex chars. Combined with
/// [`is_anonymous_artifact_ref_name`] this gives `prune-anonymous` a
/// structural match instead of a substring match.
pub fn is_anonymous_artifact_tag(tag: &str) -> bool {
    let expected_len = 15 + 1 + ANONYMOUS_TAG_NONCE_HEX_LEN;
    if tag.len() != expected_len {
        return false;
    }
    let bytes = tag.as_bytes();
    // Timestamp portion: 8 digits, 'T', 6 digits.
    for (i, b) in bytes[..15].iter().enumerate() {
        let ok = if i == 8 {
            *b == b'T'
        } else {
            b.is_ascii_digit()
        };
        if !ok {
            return false;
        }
    }
    // Separator + nonce.
    if bytes[15] != b'-' {
        return false;
    }
    bytes[16..]
        .iter()
        .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(b))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{v1, Parse};
    fn test_image_name(tag: &str) -> Result<ImageRef> {
        ImageRef::parse(&format!("ghcr.io/jij-inc/ommx/demo:{tag}"))
    }

    fn instance_with_one_hot_constraint() -> crate::Instance {
        let variable_1 = crate::VariableID::from(1);
        let variable_2 = crate::VariableID::from(2);
        let one_hot_id = crate::OneHotConstraintID::from(10);

        crate::Instance::builder()
            .sense(crate::Sense::Minimize)
            .objective(crate::Function::Zero)
            .decision_variables(std::collections::BTreeMap::from([
                (variable_1, crate::DecisionVariable::binary()),
                (variable_2, crate::DecisionVariable::binary()),
            ]))
            .constraints(std::collections::BTreeMap::new())
            .one_hot_constraints(std::collections::BTreeMap::from([(
                one_hot_id,
                crate::OneHotConstraint::new(std::collections::BTreeSet::from([
                    variable_1, variable_2,
                ]))
                .unwrap(),
            )]))
            .build()
            .unwrap()
    }

    /// `<registry-id8>.ommx.local/anonymous:<YYYYMMDDTHHMMSS>-<nonce>`
    /// must parse as a valid OCI image reference. A regression that
    /// included `:` / `+` in the timestamp, or non-alphanumeric chars
    /// in the registry-id prefix or the nonce, would break
    /// `ImageName::parse`.
    #[test]
    fn anonymous_image_name_parses() {
        let fake_registry_id = "deadbeef0123456789abcdef01234567";
        let name = anonymous_artifact_image_name(fake_registry_id).expect("synthetic ref parses");
        let s = name.to_string();
        // Repository portion ends with `.ommx.local/anonymous`; the
        // tag follows the colon.
        // e.g. `deadbeef.ommx.local/anonymous:20260512T153045-a3f17b9c`.
        let (before_colon, tag) = s.rsplit_once(':').expect("ref must include `:tag`");
        assert!(
            before_colon.ends_with(ANONYMOUS_ARTIFACT_REF_NAME_SUFFIX),
            "ref `{before_colon}` must end with `{ANONYMOUS_ARTIFACT_REF_NAME_SUFFIX}`",
        );
        assert!(
            before_colon.starts_with("deadbeef."),
            "ref `{before_colon}` must start with the truncated registry-id prefix",
        );
        // Tag = 15 timestamp + `-` + nonce.
        let expected_tag_len = 15 + 1 + ANONYMOUS_TAG_NONCE_HEX_LEN;
        assert_eq!(
            tag.len(),
            expected_tag_len,
            "tag `{tag}` must be {expected_tag_len} chars",
        );
        assert!(
            tag.chars().nth(8) == Some('T'),
            "tag `{tag}` must have `T` at position 8",
        );
        assert!(
            tag.chars().nth(15) == Some('-'),
            "tag `{tag}` must have `-` separator before the nonce",
        );
    }

    /// Two anonymous image names generated back-to-back must differ in
    /// the nonce portion even when the timestamp portion is the same.
    /// MINTO-style concurrent build patterns rely on this for
    /// collision-free unique naming; second-resolution timestamps
    /// alone (especially on macOS where `clock_gettime` is microsecond
    /// resolution) would not suffice.
    #[test]
    fn anonymous_image_name_nonce_differentiates_same_second_builds() {
        let id = "0123456789abcdef0123456789abcdef";
        let n1 = anonymous_artifact_image_name(id).unwrap().to_string();
        let n2 = anonymous_artifact_image_name(id).unwrap().to_string();
        assert_ne!(n1, n2, "back-to-back anonymous names must differ: {n1}");
    }

    /// `is_anonymous_artifact_ref_name` + `is_anonymous_artifact_tag`
    /// must together accept only ref / tag pairs that
    /// [`anonymous_artifact_image_name`] would generate, and reject
    /// substring-match false positives a naive `ends_with` would let
    /// through (the failure mode `ommx prune-anonymous`
    /// would otherwise have on a human-pushed
    /// `myhost.ommx.local/anonymous:v1`).
    #[test]
    fn anonymous_ref_filter_rejects_false_positives() {
        // Positive: a synthesized name + tag pair.
        let synth = anonymous_artifact_image_name("0123456789abcdef0123456789abcdef")
            .unwrap()
            .to_string();
        let (name, tag) = synth.rsplit_once(':').unwrap();
        assert!(is_anonymous_artifact_ref_name(name));
        assert!(is_anonymous_artifact_tag(tag));

        // Negative: hostname has the suffix but a non-8-hex prefix.
        assert!(!is_anonymous_artifact_ref_name(
            "myhost.ommx.local/anonymous"
        ));
        assert!(!is_anonymous_artifact_ref_name(
            "ABCDEFGH.ommx.local/anonymous"
        ));

        // Negative: tag is not the synthesized YYYYMMDDTHHMMSS-<nonce>
        // shape.
        assert!(!is_anonymous_artifact_tag("v1"));
        // Right total length but wrong internal shape (no `T`, no `-`).
        assert!(!is_anonymous_artifact_tag("20260512-15304500a3f17b9c"));
        // Missing nonce.
        assert!(!is_anonymous_artifact_tag("20260512T153045"));
        // Nonce contains non-hex.
        assert!(!is_anonymous_artifact_tag("20260512T153045-XXXXXXXX"));
        // Wrong separator between timestamp and nonce.
        assert!(!is_anonymous_artifact_tag("20260512T153045_a3f17b9c"));
    }

    /// Hostname prefix is truncated to the configured length even when
    /// the persisted registry-id is the full 32-hex UUID, so the
    /// rendered image name stays compact while the metadata column
    /// keeps the full identifier for future use.
    #[test]
    fn anonymous_image_name_truncates_registry_id() {
        let full = "0123456789abcdef0123456789abcdef";
        let name = anonymous_artifact_image_name(full).unwrap().to_string();
        let host = name
            .split('/')
            .next()
            .expect("synthetic ref has a host segment");
        // `<8-hex>.ommx.local` → host segment is the 8-hex + `.ommx.local`.
        assert_eq!(host, format!("{}.ommx.local", &full[..8]));
    }

    /// Two anonymous commits with no sleep between them must still
    /// publish independently because their nonce portions differ.
    #[test]
    fn anonymous_build_in_same_second_does_not_fail() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let registry = LocalRegistry::open(dir.path())?;
        for tag in ["a", "b"] {
            let mut builder = ArtifactDraft::new_anonymous_in_registry(&registry)?;
            builder.add_layer_bytes(
                MediaType::Other(media_types::V1_INSTANCE_MEDIA_TYPE.to_string()),
                format!("anon-{tag}").into_bytes(),
                HashMap::new(),
            )?;
            builder.commit()?;
        }
        Ok(())
    }

    #[test]
    fn add_solution_stores_solution_blob() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let registry = LocalRegistry::open(dir.path())?;
        let mut builder = ArtifactDraft::with_registry(&registry, test_image_name("solution")?);
        #[allow(deprecated)]
        let solution_proto = v1::Solution {
            state: Some(v1::State {
                entries: HashMap::from([(1, 1.0)]),
            }),
            objective: 1.0,
            decision_variables: Vec::new(),
            evaluated_constraints: Vec::new(),
            evaluated_named_functions: Vec::new(),
            feasible: true,
            feasible_relaxed: Some(true),
            feasible_unrelaxed: true,
            optimality: v1::Optimality::Optimal as i32,
            relaxation: v1::Relaxation::Unspecified as i32,
            sense: v1::instance::Sense::Minimize as i32,
            format_version: crate::CURRENT_FORMAT_VERSION,
            metadata: None,
            annotations: HashMap::new(),
        };
        let solution = solution_proto.parse(&())?;

        let descriptor = builder.add_solution(solution.clone())?;
        assert_eq!(descriptor.media_type(), &media_types::v2_solution());

        let blob = registry.get_blob(&descriptor)?;
        let decoded = crate::Solution::from_v2_bytes(&blob)?;
        assert_eq!(decoded, solution);
        Ok(())
    }

    #[test]
    fn add_instance_projects_annotations_to_descriptor() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let registry = LocalRegistry::open(dir.path())?;
        let mut builder = ArtifactDraft::with_registry(&registry, test_image_name("instance")?);

        let mut instance = crate::Instance::default();
        instance.description = Some(crate::v1::instance::Description {
            name: Some("domain title".to_string()),
            ..Default::default()
        });
        instance.annotations.insert(
            "org.example.annotation".to_string(),
            "domain value".to_string(),
        );
        let descriptor = builder.add_instance(instance)?;

        let annotations = descriptor
            .annotations()
            .as_ref()
            .context("descriptor annotations should be present")?;
        assert_eq!(
            annotations.get(crate::annotation_keys::INSTANCE_TITLE),
            Some(&"domain title".to_string())
        );
        assert_eq!(
            annotations.get("org.example.annotation"),
            Some(&"domain value".to_string())
        );

        let bytes = registry.get_blob(&descriptor)?;
        let decoded = crate::Instance::from_v2_bytes(&bytes)?;
        assert_eq!(
            decoded.description.and_then(|description| description.name),
            Some("domain title".to_string())
        );
        assert_eq!(
            decoded.annotations.get("org.example.annotation"),
            Some(&"domain value".to_string())
        );

        Ok(())
    }

    #[test]
    fn add_instance_stores_v2_special_constraint_blob() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let registry = LocalRegistry::open(dir.path())?;
        let mut builder =
            ArtifactDraft::with_registry(&registry, test_image_name("special-instance")?);
        let instance = instance_with_one_hot_constraint();

        let descriptor = builder.add_instance(instance.clone())?;

        assert_eq!(descriptor.media_type(), &media_types::v2_instance());
        let restored = registry.get_instance_layer(&descriptor)?;
        assert_eq!(restored, instance);

        Ok(())
    }

    #[test]
    fn get_instance_layer_merges_descriptor_annotations_without_overwriting_proto() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let registry = LocalRegistry::open(dir.path())?;

        let mut instance = crate::Instance::default();
        instance.description = Some(crate::v1::instance::Description {
            name: Some("proto title".to_string()),
            ..Default::default()
        });
        instance
            .annotations
            .insert("org.example.owner".to_string(), "proto".to_string());

        let descriptor = registry.store_layer_blob(
            media_types::v1_instance(),
            &instance.to_v1_bytes()?,
            HashMap::from([
                (
                    crate::annotation_keys::INSTANCE_TITLE.to_string(),
                    "descriptor title".to_string(),
                ),
                (
                    crate::annotation_keys::INSTANCE_LICENSE.to_string(),
                    "MIT".to_string(),
                ),
                ("org.example.owner".to_string(), "descriptor".to_string()),
                ("org.example.source".to_string(), "descriptor".to_string()),
            ]),
        )?;

        let restored = registry.get_instance_layer(&descriptor)?;
        let description = restored
            .description
            .as_ref()
            .context("descriptor fallback should create description")?;
        assert_eq!(description.name.as_deref(), Some("proto title"));
        assert_eq!(description.license.as_deref(), Some("MIT"));
        assert_eq!(
            restored
                .annotations
                .get("org.example.owner")
                .map(String::as_str),
            Some("proto")
        );
        assert_eq!(
            restored
                .annotations
                .get("org.example.source")
                .map(String::as_str),
            Some("descriptor")
        );

        Ok(())
    }

    #[test]
    #[allow(deprecated)]
    fn get_solution_layer_merges_descriptor_annotations_without_overwriting_proto() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let registry = LocalRegistry::open(dir.path())?;

        let solution_proto = v1::Solution {
            state: Some(v1::State::default()),
            objective: 1.0,
            decision_variables: Vec::new(),
            evaluated_constraints: Vec::new(),
            evaluated_named_functions: Vec::new(),
            feasible: true,
            feasible_relaxed: Some(true),
            feasible_unrelaxed: true,
            optimality: v1::Optimality::Optimal as i32,
            relaxation: v1::Relaxation::Unspecified as i32,
            sense: v1::instance::Sense::Minimize as i32,
            format_version: crate::CURRENT_FORMAT_VERSION,
            metadata: Some(v1::ProcessMetadata {
                solver: Some(r#"{"name":"proto"}"#.to_string()),
                ..Default::default()
            }),
            annotations: HashMap::from([("org.example.owner".to_string(), "proto".to_string())]),
        };
        let solution = solution_proto.parse(&())?;

        let descriptor = registry.store_layer_blob(
            media_types::v1_solution(),
            &solution.to_v1_bytes(),
            HashMap::from([
                (
                    format!("{}.solver", crate::annotation_keys::SOLUTION_NAMESPACE),
                    r#"{"name":"descriptor"}"#.to_string(),
                ),
                (
                    format!("{}.instance", crate::annotation_keys::SOLUTION_NAMESPACE),
                    "sha256:descriptor".to_string(),
                ),
                ("org.example.owner".to_string(), "descriptor".to_string()),
                ("org.example.source".to_string(), "descriptor".to_string()),
            ]),
        )?;

        let restored = registry.get_solution_layer(&descriptor)?;
        let metadata = restored
            .metadata
            .as_ref()
            .context("descriptor fallback should create process metadata")?;
        assert_eq!(metadata.solver.as_deref(), Some(r#"{"name":"proto"}"#));
        assert_eq!(metadata.instance.as_deref(), Some("sha256:descriptor"));
        assert_eq!(
            restored
                .annotations
                .get("org.example.owner")
                .map(String::as_str),
            Some("proto")
        );
        assert_eq!(
            restored
                .annotations
                .get("org.example.source")
                .map(String::as_str),
            Some("descriptor")
        );

        Ok(())
    }

    #[test]
    fn builds_native_oci_image_manifest_with_artifact_type() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let registry = LocalRegistry::open(dir.path())?;
        let mut builder = ArtifactDraft::with_registry(&registry, test_image_name("v1")?);
        let layer = builder.add_layer_bytes(
            MediaType::Other(media_types::V1_INSTANCE_MEDIA_TYPE.to_string()),
            b"instance".to_vec(),
            HashMap::from([(
                crate::annotation_keys::INSTANCE_TITLE.to_string(),
                "demo".to_string(),
            )]),
        )?;
        builder.add_annotation("org.opencontainers.image.ref.name", "example.com/demo:v1");

        let manifest = builder
            .into_unsealed_artifact()?
            .into_oci_image_manifest()?;
        // Manifest's own `mediaType` field is intentionally not set, matching
        // the v2 / `ArchiveArtifactBuilder` shape; the OCI Distribution
        // Content-Type header is supplied separately at push time.
        assert_eq!(manifest.media_type().as_ref(), None);
        assert_eq!(
            manifest.artifact_type().as_ref(),
            Some(&MediaType::Other(
                media_types::V1_ARTIFACT_MEDIA_TYPE.to_string()
            ))
        );
        assert_eq!(manifest.layers(), &[Descriptor::from(layer)]);

        // OCI 1.1 empty config descriptor is set as the manifest's config and
        // stored alongside the layers before the root manifest is sealed.
        let config = manifest.config();
        assert_eq!(config.media_type(), &MediaType::EmptyJSON);
        assert_eq!(
            config.size(),
            media_types::OCI_EMPTY_CONFIG_BYTES.len() as u64
        );
        assert_eq!(
            config.digest().to_string(),
            media_types::OCI_EMPTY_CONFIG_DIGEST
        );

        let manifest_bytes = stable_json_bytes(&manifest)?;
        let manifest_descriptor =
            descriptor_from_bytes(MediaType::ImageManifest, &manifest_bytes, HashMap::new())?;
        assert_eq!(manifest_descriptor.media_type(), &MediaType::ImageManifest);
        assert_eq!(
            manifest_descriptor.digest().to_string(),
            sha256_digest(&manifest_bytes)
        );

        let parsed: ImageManifest = serde_json::from_slice(&manifest_bytes)?;
        assert_eq!(parsed, manifest);
        Ok(())
    }

    #[test]
    fn stable_manifest_json_is_independent_of_annotation_insertion_order() -> Result<()> {
        let first = unsealed_artifact_with_annotations("order-a", [("b", "2"), ("a", "1")])?;
        let second = unsealed_artifact_with_annotations("order-b", [("a", "1"), ("b", "2")])?;

        let first_bytes = stable_json_bytes(&first)?;
        let second_bytes = stable_json_bytes(&second)?;
        let first_descriptor =
            descriptor_from_bytes(MediaType::ImageManifest, &first_bytes, HashMap::new())?;
        let second_descriptor =
            descriptor_from_bytes(MediaType::ImageManifest, &second_bytes, HashMap::new())?;

        assert_eq!(first_bytes, second_bytes);
        assert_eq!(first_descriptor.digest(), second_descriptor.digest());
        Ok(())
    }

    #[test]
    fn builds_manifest_with_subject() -> Result<()> {
        let subject =
            descriptor_from_bytes(MediaType::ImageManifest, b"parent manifest", HashMap::new())?;
        let dir = tempfile::tempdir()?;
        let registry = LocalRegistry::open(dir.path())?;
        let mut builder = ArtifactDraft::with_registry(&registry, test_image_name("subject")?);
        builder.add_layer_bytes(
            MediaType::Other(media_types::V1_INSTANCE_MEDIA_TYPE.to_string()),
            b"instance".to_vec(),
            HashMap::new(),
        )?;
        builder.set_subject(subject.clone());

        let manifest = builder
            .into_unsealed_artifact()?
            .into_oci_image_manifest()?;
        assert_eq!(manifest.subject(), &Some(subject));
        Ok(())
    }

    #[test]
    fn rejects_invalid_descriptor_digest_through_oci_spec() {
        assert!(Digest::from_str("sha256:../bad").is_err());
    }

    fn unsealed_artifact_with_annotations(
        tag: &str,
        annotations: impl IntoIterator<Item = (&'static str, &'static str)>,
    ) -> Result<ImageManifest> {
        let dir = tempfile::tempdir()?;
        let registry = LocalRegistry::open(dir.path())?;
        let mut builder = ArtifactDraft::with_registry(&registry, test_image_name(tag)?);
        builder.add_layer_bytes(
            MediaType::Other(media_types::V1_INSTANCE_MEDIA_TYPE.to_string()),
            b"instance".to_vec(),
            HashMap::new(),
        )?;
        for (key, value) in annotations {
            builder.add_annotation(key, value);
        }
        builder.into_unsealed_artifact()?.into_oci_image_manifest()
    }
}