graphforge-core 0.6.0-rc.1

GraphForge shared identities, values, options, and facade errors
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
//! Neutral portable package contracts and sanitized lifecycle errors.
#![allow(missing_docs)]

use serde::{Deserialize, Serialize};
use std::fmt;

/// Writer and reader admission limits for portable-v2 packages.
///
/// Limits that grow with the entry count admit every package a project can
/// produce (#900): the payload inventory streams, and the semantic manifest
/// is bounded per package by the entries it actually lists.
#[derive(Clone, Copy, Debug)]
pub struct PortableV2Limits {
    /// Components in the semantic manifest.
    pub max_components: u64,
    /// Regular entries in the package, tag files included.
    pub max_entries: u64,
    /// Bytes in one entry.
    pub max_entry_bytes: u64,
    /// Declared payload bytes across all entries.
    pub max_total_bytes: u64,
    /// Bytes in each retained JSON control whose size does not grow with the
    /// entry count: the runtime map, the ontology composition, and ontology
    /// and bridge documents in aggregate. It is also the semantic manifest's
    /// fixed allowance; see [`Self::semantic_manifest_bound`].
    pub max_manifest_bytes: u64,
    /// Ceiling on the semantic manifest, `data/graphforge-project.json`,
    /// whatever its entry count. It is parsed whole, so this bounds reader
    /// memory under untrusted input.
    pub max_semantic_manifest_bytes: u64,
    /// Bytes in each retained tag file: `bagit.txt`, `bag-info.txt` and
    /// `tagmanifest-sha256.txt`, which has three rows. The payload inventory,
    /// `manifest-sha256.txt`, has one row per `data/` entry; writer and reader
    /// stream it, and it is bounded by `max_entries` and `max_path_bytes`.
    pub max_tag_manifest_bytes: u64,
    /// UTF-8 bytes in one portable path.
    pub max_path_bytes: usize,
    /// Bytes in the streaming copy buffer.
    pub copy_buffer_bytes: usize,
}

/// Semantic manifest budget per entry. A file record is
/// `{"length":L,"media_type":"M","path":"P","sha256":"H"},`: 50 bytes of
/// syntax, at most 20 length digits, a media type of at most 52 bytes and 64
/// digest bytes, 186 bytes plus the path. The S26 Graph500 project's records
/// average about 320 bytes (21,531 files, 6.9 MB), so 512 bytes admits paths
/// that average up to 326 bytes, nearly twice S26's 169.
pub const PORTABLE_V2_MANIFEST_BYTES_PER_ENTRY: u64 = 512;
/// Most graph files one project holds: the storage graph-manifest default
/// (`GraphManifestLimits::max_entries`), the largest graph a package can carry.
const PRODUCER_MAX_GRAPH_FILES: u64 = 100_000;

impl PortableV2Limits {
    /// Largest semantic manifest admitted for a package of `entries` regular
    /// entries, checked before it is parsed: the fixed `max_manifest_bytes`
    /// allowance for components and selection, plus one file-record budget
    /// per entry, never above `max_semantic_manifest_bytes`. A small package
    /// therefore cannot present a large manifest.
    #[must_use]
    pub fn semantic_manifest_bound(&self, entries: u64) -> u64 {
        self.max_manifest_bytes
            .saturating_add(entries.saturating_mul(PORTABLE_V2_MANIFEST_BYTES_PER_ENTRY))
            .min(self.max_semantic_manifest_bytes)
    }
}

impl Default for PortableV2Limits {
    fn default() -> Self {
        Self {
            max_components: 10_000,
            max_entries: 1_000_000,
            max_entry_bytes: 16 * 1024_u64.pow(4),
            max_total_bytes: 1024 * 1024_u64.pow(4),
            max_manifest_bytes: 16 * 1024 * 1024,
            // 100,000 graph files x 512 bytes = 51,200,000, rounded up to
            // 64 MiB: a manifest for the largest graph a project holds fits.
            max_semantic_manifest_bytes: (PRODUCER_MAX_GRAPH_FILES
                * PORTABLE_V2_MANIFEST_BYTES_PER_ENTRY)
                .next_power_of_two(),
            max_tag_manifest_bytes: 4 * 1024 * 1024,
            max_path_bytes: 4096,
            copy_buffer_bytes: 1024 * 1024,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PortableV2Mode {
    StructureOnly,
    Full,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PortableV2Representation {
    Expanded,
    Bundle,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum PortableV2PackageClass {
    Complete,
    OntologyOnly,
    ComponentSelective,
    GraphDataSubset,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PortableV2Integrity {
    NotChecked,
    Verified,
    Failed,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PortableV2Compatibility {
    Supported,
    UnsupportedFuture,
    Failed,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PortableV2Authenticity {
    NotEvaluated,
    Unsigned,
    Verified,
    Failed,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct PortableV2Report {
    /// Whether full verification includes the registered research interchange component.
    pub research_interchange: bool,
    /// Manifest-authenticated research files for bounded native semantic verification.
    pub research_entries: Vec<PortableV2ResearchEntry>,
    pub contract: &'static str,
    pub representation: PortableV2Representation,
    pub package_digest: String,
    pub package_class: PortableV2PackageClass,
    pub component_count: u64,
    pub entry_count: u64,
    pub payload_bytes: u64,
    pub integrity: PortableV2Integrity,
    pub compatibility: PortableV2Compatibility,
    pub authenticity: PortableV2Authenticity,
    pub transport_digest: Option<String>,
    /// Exact authenticated multi-ontology compatibility control, when present.
    pub ontology_composition: Option<PortableV2OntologyComposition>,
    /// Authenticated bounded payload entries available to explicit lifecycle consumers.
    pub ontology_composition_entries: Vec<PortableV2CompositionEntry>,
}

/// An authenticated file in the versioned research component.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct PortableV2ResearchEntry {
    pub component_id: String,
    pub path: String,
    pub length: u64,
    pub sha256: String,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct PortableV2CompositionEntry {
    pub kind: String,
    pub identity: PortableV2ExactIdentity,
    pub path: String,
    pub media_type: String,
    pub length: u64,
    pub sha256: String,
    pub required_dependencies: Vec<String>,
}

#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PortableV2ExactIdentity {
    pub id: String,
    pub version: String,
    pub content_digest: String,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PortableV2ActivationOverride {
    pub scope: String,
    pub subject: PortableV2ExactIdentity,
    pub mode: String,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PortableV2ActivationProfile {
    pub profile_default: String,
    pub overrides: Vec<PortableV2ActivationOverride>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PortableV2OntologyModule {
    pub ontology_id: String,
    pub version: String,
    pub content_digest: String,
    pub dialect: String,
    pub profile: String,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PortableV2BridgeSet {
    pub bridge_id: String,
    pub version: String,
    pub content_digest: String,
    pub source_modules: Vec<PortableV2ExactIdentity>,
    pub target_modules: Vec<PortableV2ExactIdentity>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PortableV2OntologyComposition {
    pub contract: String,
    pub activation_profile: PortableV2ActivationProfile,
    pub modules: Vec<PortableV2OntologyModule>,
    pub bridge_sets: Vec<PortableV2BridgeSet>,
    pub required_features: Vec<String>,
    pub optional_features: Vec<String>,
    pub composition_digest: String,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PortableV2ErrorCode {
    Cancelled,
    LimitExceeded,
    Io,
    InvalidStructure,
    InvalidPath,
    DuplicateEntry,
    UnsupportedFuture,
    Incompatible,
    DigestMismatch,
    ConcurrentMutation,
}

#[derive(Debug)]
pub struct PortableV2Error {
    /// Authenticated committed import, even when acknowledgement or cleanup failed.
    pub committed_import: Option<Box<PortableV2CommittedImport>>,
    pub code: PortableV2ErrorCode,
    pub entry: Option<String>,
    detail: &'static str,
    /// The sanitized underlying cause of an I/O failure: the platform error
    /// text with every absolute host path reduced to its last two components.
    /// Diagnostic only; `detail` stays the stable public text.
    #[doc(hidden)]
    pub cause: Option<String>,
    /// Content-free native allocation evidence retained only for local
    /// lifecycle qualification of an interrupted operation.
    #[doc(hidden)]
    pub allocation_identity_allocated_bytes: std::collections::BTreeMap<String, u64>,
    /// Bytes actually read while reauthenticating an interrupted import.
    #[doc(hidden)]
    pub recovery_reauthentication_read_bytes: u64,
    /// Calls actually completed while reauthenticating an interrupted import.
    #[doc(hidden)]
    pub recovery_reauthentication_read_calls: u64,
}

impl PortableV2Error {
    /// Construct a sanitized package-level failure without a host path or payload value.
    #[must_use]
    pub fn new(code: PortableV2ErrorCode, detail: &'static str) -> Self {
        Self {
            committed_import: None,
            code,
            entry: None,
            detail,
            cause: None,
            allocation_identity_allocated_bytes: std::collections::BTreeMap::new(),
            recovery_reauthentication_read_bytes: 0,
            recovery_reauthentication_read_calls: 0,
        }
    }
    #[must_use]
    pub fn at(code: PortableV2ErrorCode, entry: &str, detail: &'static str) -> Self {
        Self {
            committed_import: None,
            code,
            entry: Some(entry.chars().take(4096).collect()),
            detail,
            cause: None,
            allocation_identity_allocated_bytes: std::collections::BTreeMap::new(),
            recovery_reauthentication_read_bytes: 0,
            recovery_reauthentication_read_calls: 0,
        }
    }

    /// Record the sanitized underlying cause of an I/O failure.
    #[must_use]
    pub fn with_cause(mut self, cause: impl Into<String>) -> Self {
        self.cause = Some(cause.into());
        self
    }

    #[must_use]
    pub fn with_allocation_identities(
        mut self,
        identities: std::collections::BTreeMap<String, u64>,
    ) -> Self {
        self.allocation_identity_allocated_bytes = identities;
        self
    }

    #[must_use]
    pub fn with_recovery_reauthentication(mut self, read_bytes: u64, read_calls: u64) -> Self {
        self.recovery_reauthentication_read_bytes = read_bytes;
        self.recovery_reauthentication_read_calls = read_calls;
        self
    }

    /// Attach exact publication evidence without claiming successful staging cleanup.
    #[must_use]
    pub fn with_committed_import(mut self, receipt: PortableV2CommittedImport) -> Self {
        self.committed_import = Some(Box::new(receipt));
        self
    }
}

/// Payload-free receipt evidence for an import whose CURRENT replacement committed.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct PortableV2CommittedImport {
    pub operation_uuid: uuid::Uuid,
    pub generation_uuid: uuid::Uuid,
    pub generation_manifest_sha256: [u8; 32],
    pub package_digest: String,
}
impl fmt::Display for PortableV2Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "portable-v2 {:?}: {}", self.code, self.detail)?;
        if let Some(receipt) = &self.committed_import {
            write!(
                f,
                " committed=true operation_uuid={} generation_uuid={}",
                receipt.operation_uuid, receipt.generation_uuid
            )?;
        }
        Ok(())
    }
}
impl std::error::Error for PortableV2Error {}
impl From<crate::GfError> for PortableV2Error {
    fn from(_: crate::GfError) -> Self {
        Self::new(
            PortableV2ErrorCode::Incompatible,
            "pinned project generation is not exportable",
        )
    }
}

use std::path::PathBuf;
/// Digest-pinned OCI reference returned after a successful publish.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct PortableV2OciReference {
    /// Registry host (no credentials).
    pub registry: String,
    /// Repository path inside the registry.
    pub repository: String,
    /// OCI manifest digest (`sha256:…`).
    pub oci_manifest_digest: String,
    /// Authoritative GraphForge package digest (`sha256:…`).
    pub package_digest: String,
    /// Package class carried in the config blob.
    pub package_class: PortableV2PackageClass,
    /// Optional mutable tag that was also written; never used as identity.
    pub tag: Option<String>,
    /// Bytes uploaded across config + layer + manifest.
    pub bytes_transferred: u64,
    /// Blob count excluding the manifest itself.
    pub blob_count: u64,
}

/// Sanitized receipt after a successful pull + local verification.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct PortableV2OciPullReceipt {
    /// Digest-pinned reference that was resolved.
    pub reference: PortableV2OciReference,
    /// Destination path written after verification.
    pub destination: PathBuf,
    /// Local verifier report for the pulled package.
    pub report: PortableV2Report,
    /// Signature evaluation outcome (distinct from integrity).
    pub signature_state: PortableV2OciSignatureState,
}

/// Optional authenticity policy for referrer/signature attachments.
#[derive(Clone, Default, Eq, PartialEq)]
pub struct PortableV2OciAuthenticityPolicy {
    /// When set, unsigned content is integrity-valid but authenticity-absent.
    pub require_named_signer: Option<String>,
    /// Caller-owned verification key material. Never logged or persisted.
    pub verification_key: Option<Vec<u8>>,
}

/// Explicit signature states. Never reused as integrity outcomes.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PortableV2OciSignatureState {
    /// Signature present, signer matches policy, MAC verifies.
    Valid,
    /// Signature present but MAC verification failed.
    Invalid,
    /// No signature attachment was observed.
    Absent,
    /// Signature present for a different signer than the policy requires.
    PolicyMismatched,
}

/// Progress phases for sanitized observability (no credentials or bodies).
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PortableV2OciPhase {
    VerifyLocal,
    UploadBlob,
    UploadManifest,
    AttachSignature,
    Observe,
    DownloadManifest,
    DownloadBlob,
    VerifyPulled,
    EvaluateAuthenticity,
}

/// Sanitized progress event.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct PortableV2OciProgress {
    /// Current phase.
    pub phase: PortableV2OciPhase,
    /// Cumulative bytes moved in this operation.
    pub bytes_transferred: u64,
    /// Optional blob/manifest digest under consideration.
    pub digest: Option<String>,
}

/// Caller-owned material used to attach an OCI signature referrer on publish.
#[derive(Clone, Eq, PartialEq)]
pub struct PortableV2OciSignatureMaterial {
    /// Signer identity recorded in the attachment.
    pub signer: String,
    /// Key identifier (not secret material).
    pub key_id: String,
    /// Secret key bytes used to compute the MAC. Never logged.
    pub secret: Vec<u8>,
}

impl std::fmt::Debug for PortableV2OciAuthenticityPolicy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PortableV2OciAuthenticityPolicy")
            .field("require_named_signer", &self.require_named_signer)
            .field("verification_key", &"[REDACTED]")
            .finish()
    }
}

impl std::fmt::Debug for PortableV2OciSignatureMaterial {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PortableV2OciSignatureMaterial")
            .field("signer", &self.signer)
            .field("key_id", &self.key_id)
            .field("secret", &"[REDACTED]")
            .finish()
    }
}

/// Stable semantic participant identity. Runtime catalog IDs and host paths are never selectors.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub struct PortableV2ParticipantId {
    /// Owning portable capability contract.
    pub capability_id: String,
    /// Stable record-family contract.
    pub record_family_id: String,
}

/// Built-in deterministic selection profiles.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum PortableV2SelectionProfile {
    /// Every committed participant and graph-tree payload.
    Complete,
    /// Authored/adopted ontology plus required schema participants.
    OntologyOnly,
    /// Whole graph/data components. Row or subgraph selection belongs to #786.
    DataComponents,
    /// Derived and repository artifact participants.
    Artifacts,
    /// Closed-schema portable settings only.
    Settings,
    /// Explicit stable identities.
    Custom(Vec<PortableV2ParticipantId>),
    /// Exact projected ontology module or bridge identities. The immutable
    /// preview exposes the complete emitted composition closure.
    OntologyComposition(Vec<PortableV2ExactIdentity>),
}

/// Selection planning request.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PortableV2SelectionRequest {
    /// Requested built-in or custom profile.
    pub profile: PortableV2SelectionProfile,
    /// Refuse any automatically required dependency instead of widening visibly.
    pub strict: bool,
}

/// Stable reason for inclusion/exclusion.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum PortableV2SelectionReason {
    /// Directly requested by profile or exact identity.
    Requested,
    /// Required ontology/schema closure.
    RequiredSchemaAuthority,
    /// Required exact multi-ontology composition closure.
    RequiredOntologyComposition,
    /// Not part of the requested profile.
    ProfileExcluded,
}

/// Content-free preview row.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct PortableV2SelectionEntry {
    /// Stable semantic identity.
    pub identity: PortableV2ParticipantId,
    /// Canonical component kind.
    pub kind: String,
    /// Stable selection reason.
    pub reason: PortableV2SelectionReason,
    /// Exact committed payload bytes.
    pub estimated_bytes: u64,
    /// Manifest row count.
    pub row_count: u64,
}

/// Exact ontology module or bridge emitted by composition projection.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct PortableV2ProjectedSelectionEntry {
    /// Projected component kind (`ontology` or `schema`).
    pub kind: String,
    /// Exact semantic identity addressable by callers.
    pub identity: PortableV2ExactIdentity,
    /// Stable component identity used by the portable manifest.
    pub participant_id: String,
    /// Whether this exact identity was directly requested or closure-added.
    pub reason: PortableV2SelectionReason,
    /// Exact canonical projected payload bytes.
    pub estimated_bytes: u64,
}

/// Immutable deterministic preview consumed by both export representations.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct PortableV2SelectionPlan {
    /// Pinned source generation identity.
    pub source_generation_uuid: String,
    /// Pinned source generation manifest identity.
    pub source_manifest_sha256: String,
    /// Portable package class token.
    pub package_class: String,
    /// Included participants in canonical identity order.
    pub included: Vec<PortableV2SelectionEntry>,
    /// Excluded participants in canonical identity order.
    pub excluded: Vec<PortableV2SelectionEntry>,
    /// Exact projected ontology closure in canonical identity order.
    pub projected: Vec<PortableV2ProjectedSelectionEntry>,
    /// Explicit redaction reason codes; values are never retained.
    pub redactions: Vec<String>,
    /// Required portable capability contracts.
    pub required_capabilities: Vec<String>,
    /// Exact known participant bytes, excluding bounded control metadata.
    pub estimated_payload_bytes: u64,
    /// Stable digest over canonical content-free plan metadata.
    pub selection_fingerprint: String,
    include_graph_tree: bool,
}

impl PortableV2SelectionPlan {
    /// Construct a passive preview; this does not authorize storage execution.
    #[must_use]
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        source_generation_uuid: String,
        source_manifest_sha256: String,
        package_class: String,
        included: Vec<PortableV2SelectionEntry>,
        excluded: Vec<PortableV2SelectionEntry>,
        projected: Vec<PortableV2ProjectedSelectionEntry>,
        redactions: Vec<String>,
        required_capabilities: Vec<String>,
        estimated_payload_bytes: u64,
        selection_fingerprint: String,
        include_graph_tree: bool,
    ) -> Self {
        Self {
            source_generation_uuid,
            source_manifest_sha256,
            package_class,
            included,
            excluded,
            projected,
            redactions,
            required_capabilities,
            estimated_payload_bytes,
            selection_fingerprint,
            include_graph_tree,
        }
    }
    /// Whether the semantic selection includes the graph tree.
    #[must_use]
    pub fn includes_graph_tree(&self) -> bool {
        self.include_graph_tree
    }
    /// Set the semantic graph-tree selection for a projected preview.
    pub fn set_include_graph_tree(&mut self, include: bool) {
        self.include_graph_tree = include;
    }
    /// Whether a semantic participant is included.
    #[must_use]
    pub fn includes(&self, capability: &str, family: &str) -> bool {
        self.included.iter().any(|entry| {
            entry.identity.capability_id == capability && entry.identity.record_family_id == family
        })
    }
}

/// Stable UUID selector for one pinned generation.
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)]
pub struct PortableV2GraphSelector {
    /// Ordered node UUIDs (hyphenated).
    pub node_uuids: Vec<String>,
    /// Ordered edge UUIDs (hyphenated).
    pub edge_uuids: Vec<String>,
}

/// Portable-v2 on-wire closure tokens.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum PortableV2SubsetClosure {
    /// Selected nodes plus edges whose endpoints are both selected.
    InducedEdges,
    /// Selected edges plus both endpoint nodes.
    Referential,
}

/// Property projection/redaction for subset packages.
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)]
pub struct PortableV2PropertyProjection {
    /// Property field names excluded from payloads.
    pub exclude: Vec<String>,
}

/// Subset planning request.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PortableV2SubsetRequest {
    /// Stable UUID selector.
    pub selector: PortableV2GraphSelector,
    /// Closure mode.
    pub closure: PortableV2SubsetClosure,
    /// Property projection.
    pub projection: PortableV2PropertyProjection,
}

/// Content-free graph-subset receipt retained in the semantic manifest.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct PortableV2GraphSubsetMeta {
    /// Canonical content-free selector digest token.
    pub selector: String,
    /// On-wire closure token.
    pub closure: String,
}

/// Immutable subset preview consumed by planning and export.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct PortableV2SubsetPreview {
    /// Component selection consumed by the exporter.
    pub selection: PortableV2SelectionPlan,
    /// Graph-subset metadata emitted into the semantic manifest.
    pub graph_subset: PortableV2GraphSubsetMeta,
    /// Resolved node count after closure.
    pub selected_node_count: u64,
    /// Resolved edge count after closure.
    pub selected_edge_count: u64,
    /// Endpoint nodes added beyond the caller's explicit node set.
    pub endpoint_node_count: u64,
    /// Domain-separated projected graph fingerprint.
    pub result_fingerprint: String,
    /// Stable digest over the full subset preview.
    pub subset_fingerprint: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Portable-v2 transport representation.
pub enum PortableV2Output {
    /// Closed BagIt-compatible directory.
    Expanded,
    /// Canonical uncompressed PAX/ustar stream.
    Bundle,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Aggregate content-free progress observation.
pub struct PortableV2ExportProgress {
    /// Fully emitted entries.
    pub entries_completed: usize,
    /// Emitted source payload bytes.
    pub bytes_completed: u64,
    /// Planned entry count.
    pub entries_total: usize,
    /// Planned source payload bytes.
    pub bytes_total: u64,
}

#[cfg(test)]
mod preview_wire_tests {
    use super::*;

    #[test]
    fn moved_preview_contract_keeps_private_serialized_graph_decision() {
        let plan = PortableV2SelectionPlan::new(
            "generation".into(),
            "manifest".into(),
            "graph-data-subset".into(),
            vec![PortableV2SelectionEntry {
                identity: PortableV2ParticipantId {
                    capability_id: "graph@1".into(),
                    record_family_id: "files@1".into(),
                },
                kind: "graph-data".into(),
                reason: PortableV2SelectionReason::Requested,
                estimated_bytes: 7,
                row_count: 2,
            }],
            Vec::new(),
            Vec::new(),
            vec!["redacted".into()],
            vec!["graph@1".into()],
            7,
            "selection".into(),
            false,
        );
        let expected = serde_json::json!({
            "source_generation_uuid":"generation", "source_manifest_sha256":"manifest",
            "package_class":"graph-data-subset", "included":[{"identity":{"capability_id":"graph@1","record_family_id":"files@1"},
                "kind":"graph-data","reason":"requested","estimated_bytes":7,"row_count":2}],
            "excluded":[],"projected":[],"redactions":["redacted"],"required_capabilities":["graph@1"],
            "estimated_payload_bytes":7,"selection_fingerprint":"selection","include_graph_tree":false
        });
        assert_eq!(serde_json::to_value(&plan).unwrap(), expected);
        let subset = PortableV2SubsetPreview {
            selection: plan,
            graph_subset: PortableV2GraphSubsetMeta {
                selector: "selector".into(),
                closure: "referential".into(),
            },
            selected_node_count: 2,
            selected_edge_count: 1,
            endpoint_node_count: 1,
            result_fingerprint: "result".into(),
            subset_fingerprint: "subset".into(),
        };
        assert_eq!(
            serde_json::to_value(subset).unwrap(),
            serde_json::json!({
                "selection":expected,"graph_subset":{"selector":"selector","closure":"referential"},
                "selected_node_count":2,"selected_edge_count":1,"endpoint_node_count":1,
                "result_fingerprint":"result","subset_fingerprint":"subset"
            })
        );
    }
}

#[cfg(test)]
mod limit_tests {
    use super::*;

    /// The longest file record the writer emits, with an empty path.
    fn longest_record_without_path() -> u64 {
        let record = serde_json::json!({
            "length": u64::MAX,
            "media_type": "application/vnd.graphforge.ontology-composition+json",
            "path": "",
            "sha256": "0".repeat(64),
        });
        (serde_json::to_vec(&record).unwrap().len() + ",".len()) as u64
    }

    #[test]
    fn default_limits_admit_every_package_a_project_can_produce() {
        let limits = PortableV2Limits::default();
        // The per-entry semantic manifest budget is one record plus its path.
        assert_eq!(longest_record_without_path(), 186);
        let path_budget = PORTABLE_V2_MANIFEST_BYTES_PER_ENTRY - longest_record_without_path();
        assert_eq!(path_budget, 326);
        // Controls that do not grow with the entry count keep 16 MiB; the
        // semantic manifest ceiling holds the largest graph a project holds.
        assert_eq!(limits.max_manifest_bytes, 16 * 1024 * 1024);
        assert_eq!(limits.max_semantic_manifest_bytes, 64 * 1024 * 1024);
        assert!(
            PRODUCER_MAX_GRAPH_FILES * PORTABLE_V2_MANIFEST_BYTES_PER_ENTRY
                <= limits.max_semantic_manifest_bytes
        );
        // S26 Graph500: 21,535 entries and a 6,874,538-byte manifest whose
        // paths average 169 bytes. S28 has about four times as many entries.
        assert!(6_874_538 <= limits.semantic_manifest_bound(21_535));
        let s28_entries = 4 * 21_535;
        let s28_manifest = s28_entries * (longest_record_without_path() + 169);
        assert!(s28_manifest <= limits.semantic_manifest_bound(s28_entries));
        assert!(169 < path_budget);
        // The bound grows with the package and stops at the ceiling.
        assert_eq!(limits.semantic_manifest_bound(0), limits.max_manifest_bytes);
        assert_eq!(
            limits.semantic_manifest_bound(1),
            limits.max_manifest_bytes + PORTABLE_V2_MANIFEST_BYTES_PER_ENTRY
        );
        assert_eq!(
            limits.semantic_manifest_bound(limits.max_entries),
            limits.max_semantic_manifest_bytes
        );
        assert_eq!(
            limits.semantic_manifest_bound(u64::MAX),
            limits.max_semantic_manifest_bytes
        );
        // The tag files the tag limit bounds have a fixed size: the tag
        // manifest has three rows whatever the entry count.
        let tag_manifest = ["bag-info.txt", "bagit.txt", "manifest-sha256.txt"]
            .iter()
            .map(|path| 64 + 2 + path.len() as u64 + 1)
            .sum::<u64>();
        assert!(tag_manifest <= limits.max_tag_manifest_bytes);
    }
}