Skip to main content

qualia_core_db/q42/volume/
publication.rs

1//! Fail-closed publication class for unified `.q42` volumes.
2//!
3//! A Q42 file is a rights-bearing container. It may hold Selfhood (medical
4//! records, PEP files, sanctuary graphs) or Personhood artefacts for the
5//! Permissive Commons. Public magnets, HTTP web-seed, and IPFS pins are
6//! Commons *transport*, not a default. Unmarked files stay local.
7//!
8//! SocialWebNet (pairwise DID / WireGuard) remains the transport for
9//! Bilateral Micro-Commons. This module does not replace that mesh; it
10//! stops the volume/magnet path from treating every `.q42` as open data.
11
12use std::io;
13use std::path::Path;
14
15use serde::Serialize;
16
17#[cfg(not(target_arch = "wasm32"))]
18use super::super::{
19    Q42Volume, FLAG_PERMISSIVE_COMMONS, FLAG_SANCTUARY, QUIN_SIZE, SUPERBLOCK_HEADER,
20    SUPERBLOCK_SIZE,
21};
22use crate::{NQuin, PermissiveRoutingLane};
23#[cfg(not(target_arch = "wasm32"))]
24use crate::QUINS_PER_BLOCK;
25
26/// What the caller asserts about a file. Never overrides Quin-level rights.
27#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
28pub enum PublicationIntent {
29    /// Fail closed unless the file itself is affirmatively Commons.
30    Default,
31    /// Human principal marks a catalog/ontology artefact. Still denied if any
32    /// Quin is restricted, classified, medical, legal, fiduciary, or bilateral.
33    CommonsCatalog,
34}
35
36/// Mandatory ingest access / publication policy (QW-10).
37///
38/// Never inferred: writers must receive an explicit choice. Only
39/// [`IngestAccessPolicy::PublicRedistributable`] may set `FLAG_PERMISSIVE_COMMONS`.
40#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
41pub enum IngestAccessPolicy {
42    /// Local / Sanctuary; no public magnet, web-seed, or cache.
43    Restricted,
44    /// Shared inside a project; still not public redistribution.
45    ProjectInternal,
46    /// May be shown publicly but licence / redistribution still under review.
47    PublicNotForRedistribution,
48    /// Explicit reviewed decision: Permissive Commons transport allowed.
49    PublicRedistributable,
50}
51
52impl IngestAccessPolicy {
53    /// Parse a policy name (`restricted` | `project-internal` |
54    /// `public-not-for-redistribution` | `public-redistributable`,
55    /// plus review/licence-review aliases).
56    pub fn parse(raw: &str) -> Result<Self, String> {
57        match raw.trim().to_ascii_lowercase().as_str() {
58            "restricted" => Ok(Self::Restricted),
59            "project-internal" | "project_internal" | "internal" => Ok(Self::ProjectInternal),
60            "public-not-for-redistribution"
61            | "public_not_for_redistribution"
62            | "licence-review"
63            | "license-review"
64            | "review-required" => Ok(Self::PublicNotForRedistribution),
65            "public-redistributable" | "public_redistributable" | "permissive-commons" => {
66                Ok(Self::PublicRedistributable)
67            }
68            other => Err(format!(
69                "unknown access policy '{other}'; expected restricted | project-internal | public-not-for-redistribution | public-redistributable"
70            )),
71        }
72    }
73
74    /// Canonical lowercase policy token (as accepted by `parse`).
75    pub fn as_str(self) -> &'static str {
76        match self {
77            Self::Restricted => "restricted",
78            Self::ProjectInternal => "project-internal",
79            Self::PublicNotForRedistribution => "public-not-for-redistribution",
80            Self::PublicRedistributable => "public-redistributable",
81        }
82    }
83
84    /// Only an explicit redistributable decision may mint the Commons header flag.
85    pub fn may_declare_permissive_commons(self) -> bool {
86        matches!(self, Self::PublicRedistributable)
87    }
88}
89
90/// Integrity-bound companion written beside a newly ingested `.q42` (QW-10).
91#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
92pub struct IngestProvenanceRecord {
93    pub access_policy: String,
94    pub source_sha256: String,
95    pub mapping_version: String,
96    pub context_digest: String,
97    pub compiler_build_digest: String,
98    pub engine_version: String,
99}
100
101impl IngestProvenanceRecord {
102    /// New record; `engine_version` is stamped from
103    /// `CARGO_PKG_VERSION` automatically.
104    pub fn new(
105        policy: IngestAccessPolicy,
106        source_sha256: impl Into<String>,
107        mapping_version: impl Into<String>,
108        context_digest: impl Into<String>,
109        compiler_build_digest: impl Into<String>,
110    ) -> Self {
111        Self {
112            access_policy: policy.as_str().to_string(),
113            source_sha256: source_sha256.into(),
114            mapping_version: mapping_version.into(),
115            context_digest: context_digest.into(),
116            compiler_build_digest: compiler_build_digest.into(),
117            engine_version: env!("CARGO_PKG_VERSION").to_string(),
118        }
119    }
120
121    #[cfg(not(target_arch = "wasm32"))]
122    /// Write `<q42>.provenance.json` beside the volume; returns the
123    /// written path.
124    pub fn write_beside_volume(&self, q42_path: &Path) -> io::Result<std::path::PathBuf> {
125        let path = provenance_path_for(q42_path);
126        let json = serde_json::to_vec_pretty(self).map_err(|e| {
127            io::Error::new(io::ErrorKind::InvalidData, format!("provenance json: {e}"))
128        })?;
129        std::fs::write(&path, json)?;
130        Ok(path)
131    }
132}
133
134/// `<q42_path>.provenance.json` — the sidecar provenance location.
135pub fn provenance_path_for(q42_path: &Path) -> std::path::PathBuf {
136    std::path::PathBuf::from(format!("{}.provenance.json", q42_path.display()))
137}
138
139/// How this volume may move, if at all.
140#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
141pub enum Q42PublicationClass {
142    /// Affirmative Permissive Commons (header flag or catalog intent).
143    PermissiveCommons,
144    /// Commons lane present; still not Selfhood.
145    CommonsGated,
146    /// No restricted Quins, but no Commons declaration either.
147    UnmarkedLocal,
148    /// Selfhood / bilateral / medical / classified. Never a public hash.
149    Sanctuary,
150    /// Commons material mixed with Selfhood in one file. Deny until split.
151    MixedFailClosed,
152}
153
154/// Where a classified volume is allowed to travel.
155#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
156pub enum Q42Transport {
157    WebTorrentCommons,
158    SocialWebNetBilateral,
159    LocalSanctuaryOnly,
160}
161
162#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)]
163pub struct ClassificationCounts {
164    pub quins_scanned: u64,
165    pub public: u64,
166    pub restricted: u64,
167    pub classified: u64,
168    pub professional_tier: u64,
169    pub legal_tier: u64,
170    pub medical_tier: u64,
171    pub fiduciary_tier: u64,
172    pub passthrough: u64,
173    pub commons_lane: u64,
174    pub bilateral: u64,
175    pub spatial: u64,
176    pub decode_failures: u64,
177}
178
179#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
180pub struct Q42PublicationVerdict {
181    pub class: Q42PublicationClass,
182    pub may_emit_public_magnet: bool,
183    pub may_http_webseed: bool,
184    pub may_ipfs_pin: bool,
185    pub transport: Q42Transport,
186    pub reason: String,
187    pub counts: ClassificationCounts,
188    pub header_commons_flag: bool,
189    pub header_sanctuary_flag: bool,
190}
191
192impl Q42PublicationClass {
193    /// Lowercase class token (`permissive-commons`, `sanctuary`, …).
194    pub fn as_str(self) -> &'static str {
195        match self {
196            Self::PermissiveCommons => "permissive-commons",
197            Self::CommonsGated => "commons-gated",
198            Self::UnmarkedLocal => "unmarked-local",
199            Self::Sanctuary => "sanctuary",
200            Self::MixedFailClosed => "mixed-fail-closed",
201        }
202    }
203}
204
205impl Q42Transport {
206    /// Human-readable transport description (Commons magnet /
207    /// SocialWebNet bilateral / local sanctuary).
208    pub fn as_str(self) -> &'static str {
209        match self {
210            Self::WebTorrentCommons => {
211                "WebTorrent Permissive Commons (hash-addressed; not open-data)"
212            }
213            Self::SocialWebNetBilateral => {
214                "SocialWebNet (pairwise DID / WireGuard). No public magnet."
215            }
216            Self::LocalSanctuaryOnly => {
217                "local Sanctuary only. No public magnet, web-seed, or IPFS."
218            }
219        }
220    }
221}
222
223const MASK_60: u64 = 0x0FFF_FFFF_FFFF_FFFF;
224
225const fn token60(iri: &str) -> u64 {
226    crate::q_hash(iri) & MASK_60
227}
228
229const NATURAL_AGENT_SANCTUARY_TOKENS: &[u64] = &[
230    crate::q_hash("https://qualia.world/ontology/idf#NaturalAgent"),
231    token60("https://qualia.world/ontology/idf#NaturalAgent"),
232    crate::q_hash("q42:NaturalAgent"),
233    token60("q42:NaturalAgent"),
234    crate::q_hash("idf:NaturalAgent"),
235    token60("idf:NaturalAgent"),
236    crate::q_hash("https://qualia.world/ontology/idf#hasGuardian"),
237    token60("https://qualia.world/ontology/idf#hasGuardian"),
238    crate::q_hash("q42:hasGuardian"),
239    token60("q42:hasGuardian"),
240    crate::q_hash("https://qualia.world/ontology/clinical#hasDiagnosis"),
241    token60("https://qualia.world/ontology/clinical#hasDiagnosis"),
242    crate::q_hash("https://qualia.world/ontology/clinical#ClinicalClaim"),
243    token60("https://qualia.world/ontology/clinical#ClinicalClaim"),
244    crate::q_hash("https://qualia.world/ontology/sanctuary#PersonalClaim"),
245    token60("https://qualia.world/ontology/sanctuary#PersonalClaim"),
246    crate::q_hash("https://qualia.world/ontology/sanctuary#GuardianshipClaim"),
247    token60("https://qualia.world/ontology/sanctuary#GuardianshipClaim"),
248];
249
250#[inline]
251fn has_natural_agent_sanctuary_token(quin: &NQuin) -> bool {
252    let mut i = 0;
253    while i < NATURAL_AGENT_SANCTUARY_TOKENS.len() {
254        let tok = NATURAL_AGENT_SANCTUARY_TOKENS[i];
255        if quin.subject == tok || quin.predicate == tok || quin.object == tok {
256            return true;
257        }
258        i += 1;
259    }
260    false
261}
262
263/// True when this Quin is Selfhood, bilateral, a protected ODRL tier, or a `NaturalAgent`
264/// personal/clinical/guardianship claim.
265pub fn quin_requires_sanctuary(quin: &NQuin) -> bool {
266    match quin.get_sensitivity_byte() {
267        NQuin::SENSITIVITY_RESTRICTED | NQuin::SENSITIVITY_CLASSIFIED => return true,
268        _ => {}
269    }
270    match quin.get_sensitivity_tier() {
271        NQuin::SENSITIVITY_TIER_LEGAL
272        | NQuin::SENSITIVITY_TIER_MEDICAL
273        | NQuin::SENSITIVITY_TIER_FIDUCIARY => return true,
274        _ => {}
275    }
276    if quin.identify_routing_lane() == PermissiveRoutingLane::EnforceBilateralMicroCommons {
277        return true;
278    }
279    has_natural_agent_sanctuary_token(quin)
280}
281
282#[cfg(not(target_arch = "wasm32"))]
283#[cfg(not(target_arch = "wasm32"))]
284/// Open `path` and classify it for publication under `intent`.
285pub fn classify_q42_path(
286    path: &Path,
287    intent: PublicationIntent,
288) -> io::Result<Q42PublicationVerdict> {
289    let volume = Q42Volume::open(path)?;
290    Ok(classify_q42_volume(&volume, intent))
291}
292
293#[cfg(not(target_arch = "wasm32"))]
294/// Full-volume publication verdict: scans every decoded Quin's
295/// sensitivity byte/tier and routing lane, then applies the
296/// fail-closed `decide` policy.
297pub fn classify_q42_volume(volume: &Q42Volume, intent: PublicationIntent) -> Q42PublicationVerdict {
298    let flags = volume.header().flags;
299    let header_commons = flags & FLAG_PERMISSIVE_COMMONS != 0;
300    let header_sanctuary = flags & FLAG_SANCTUARY != 0;
301    let mut counts = ClassificationCounts::default();
302    if volume.block_count() > 0 {
303        let mut decoded = [0u8; SUPERBLOCK_SIZE];
304        for block_index in 0..volume.block_count() as usize {
305            if volume
306                .read_superblock_into(block_index, &mut decoded)
307                .is_err()
308            {
309                counts.decode_failures += 1;
310                continue;
311            }
312            let live = u64::from_le_bytes(decoded[16..24].try_into().unwrap()) as usize;
313            if live == 0 || live > QUINS_PER_BLOCK {
314                counts.decode_failures += 1;
315                continue;
316            }
317            for quin_index in 0..live {
318                let offset = SUPERBLOCK_HEADER + quin_index * QUIN_SIZE;
319                let quin: NQuin =
320                    bytemuck::pod_read_unaligned(&decoded[offset..offset + QUIN_SIZE]);
321                accumulate(&mut counts, &quin);
322            }
323        }
324    }
325    decide(header_commons, header_sanctuary, intent, counts)
326}
327
328/// Volume-set: any child that cannot be public denies the whole public set.
329#[cfg(not(target_arch = "wasm32"))]
330pub fn classify_q42_volume_set(
331    root: &Path,
332    intent: PublicationIntent,
333) -> io::Result<Q42PublicationVerdict> {
334    let root_verdict = classify_q42_path(root, intent)?;
335    if !root_verdict.may_emit_public_magnet {
336        return Ok(root_verdict);
337    }
338    let volume = Q42Volume::open(root)?;
339    let Some(manifest) = volume.volume_manifest()? else {
340        return Ok(root_verdict);
341    };
342    let parent = root.parent().unwrap_or(Path::new("."));
343    for entry in &manifest.segments {
344        let child = parent.join(&entry.locator);
345        let child_verdict = classify_q42_path(&child, intent)?;
346        if !child_verdict.may_emit_public_magnet {
347            return Ok(child_verdict);
348        }
349    }
350    Ok(root_verdict)
351}
352
353/// `PermissionDenied` with the verdict's reason unless
354/// `may_emit_public_magnet` — the enforcement gate for public
355/// publication paths.
356pub fn deny_public_publication(verdict: &Q42PublicationVerdict) -> io::Result<()> {
357    if verdict.header_sanctuary_flag || !verdict.may_emit_public_magnet {
358        return Err(io::Error::new(
359            io::ErrorKind::PermissionDenied,
360            verdict.reason.clone(),
361        ));
362    }
363    Ok(())
364}
365
366/// Trait supporting flexible invocation of [`check_public_distribution_allowed`].
367pub trait CheckPublicDistribution {
368    fn check_public_distribution(self) -> io::Result<()>;
369}
370
371impl CheckPublicDistribution for &Q42PublicationVerdict {
372    fn check_public_distribution(self) -> io::Result<()> {
373        deny_public_publication(self)
374    }
375}
376
377impl CheckPublicDistribution for Q42PublicationVerdict {
378    fn check_public_distribution(self) -> io::Result<()> {
379        deny_public_publication(&self)
380    }
381}
382
383#[cfg(not(target_arch = "wasm32"))]
384impl CheckPublicDistribution for &Q42Volume {
385    fn check_public_distribution(self) -> io::Result<()> {
386        let verdict = classify_q42_volume(self, PublicationIntent::Default);
387        deny_public_publication(&verdict)
388    }
389}
390
391#[cfg(not(target_arch = "wasm32"))]
392impl CheckPublicDistribution for (&Q42Volume, PublicationIntent) {
393    fn check_public_distribution(self) -> io::Result<()> {
394        let verdict = classify_q42_volume(self.0, self.1);
395        deny_public_publication(&verdict)
396    }
397}
398
399#[cfg(not(target_arch = "wasm32"))]
400impl CheckPublicDistribution for &Path {
401    fn check_public_distribution(self) -> io::Result<()> {
402        let verdict = classify_q42_path(self, PublicationIntent::Default)?;
403        deny_public_publication(&verdict)
404    }
405}
406
407#[cfg(not(target_arch = "wasm32"))]
408impl CheckPublicDistribution for (&Path, PublicationIntent) {
409    fn check_public_distribution(self) -> io::Result<()> {
410        let verdict = classify_q42_path(self.0, self.1)?;
411        deny_public_publication(&verdict)
412    }
413}
414
415#[cfg(not(target_arch = "wasm32"))]
416impl CheckPublicDistribution for &std::path::PathBuf {
417    fn check_public_distribution(self) -> io::Result<()> {
418        check_public_distribution_allowed(self.as_path())
419    }
420}
421
422/// Hard publication gate (`Q42-00`): rejects any volume with `FLAG_SANCTUARY` (`0x0040`),
423/// `NaturalAgent` personal/clinical/guardianship claims, or non-Commons classification,
424/// even if `FLAG_PERMISSIVE_COMMONS` or `PublicationIntent::CommonsCatalog` was passed.
425pub fn check_public_distribution_allowed<T: CheckPublicDistribution>(target: T) -> io::Result<()> {
426    target.check_public_distribution()
427}
428
429/// Tally one Quin into `counts` — sensitivity byte, protected tiers,
430/// and routing lane.
431#[cfg(not(target_arch = "wasm32"))]
432fn accumulate(counts: &mut ClassificationCounts, quin: &NQuin) {
433    counts.quins_scanned += 1;
434    let is_nat_sanctuary = has_natural_agent_sanctuary_token(quin);
435    match quin.get_sensitivity_byte() {
436        NQuin::SENSITIVITY_RESTRICTED => counts.restricted += 1,
437        NQuin::SENSITIVITY_CLASSIFIED => counts.classified += 1,
438        _ if is_nat_sanctuary => counts.restricted += 1,
439        _ => counts.public += 1,
440    }
441    match quin.get_sensitivity_tier() {
442        NQuin::SENSITIVITY_TIER_PROFESSIONAL => counts.professional_tier += 1,
443        NQuin::SENSITIVITY_TIER_LEGAL => counts.legal_tier += 1,
444        NQuin::SENSITIVITY_TIER_MEDICAL => counts.medical_tier += 1,
445        NQuin::SENSITIVITY_TIER_FIDUCIARY => counts.fiduciary_tier += 1,
446        _ => {}
447    }
448    match quin.identify_routing_lane() {
449        PermissiveRoutingLane::PassthroughStandard => counts.passthrough += 1,
450        PermissiveRoutingLane::EnforcePermissiveCommons => counts.commons_lane += 1,
451        PermissiveRoutingLane::EnforceBilateralMicroCommons => counts.bilateral += 1,
452        PermissiveRoutingLane::SpatiotemporalAmbiguous => counts.spatial += 1,
453    }
454}
455
456/// Total Quins that force Sanctuary handling (restricted +
457/// classified + protected tiers + bilateral lane).
458#[cfg(not(target_arch = "wasm32"))]
459fn sanctuary_quin_count(counts: &ClassificationCounts) -> u64 {
460    counts.restricted
461        + counts.classified
462        + counts.legal_tier
463        + counts.medical_tier
464        + counts.fiduciary_tier
465        + counts.bilateral
466}
467
468/// The fail-closed policy core: sanctuary material + commons
469/// signals → `MixedFailClosed` (split the volume); sanctuary alone →
470/// `Sanctuary`; declared/intended commons → `CommonsGated` or
471/// `PermissiveCommons`; unmarked → `UnmarkedLocal` (stays local).
472/// Decode failures count as sanctuary bits — unverifiable data never
473/// goes public.
474#[cfg(not(target_arch = "wasm32"))]
475fn decide(
476    header_commons: bool,
477    header_sanctuary: bool,
478    intent: PublicationIntent,
479    counts: ClassificationCounts,
480) -> Q42PublicationVerdict {
481    let sanctuary_bits =
482        header_sanctuary || sanctuary_quin_count(&counts) > 0 || counts.decode_failures > 0;
483    let commons_bits =
484        header_commons || intent == PublicationIntent::CommonsCatalog || counts.commons_lane > 0;
485
486    let (class, reason) = if sanctuary_bits && commons_bits {
487        (
488            Q42PublicationClass::MixedFailClosed,
489            "Q42 publication denied: this file mixes Permissive Commons material with Selfhood, medical, legal, fiduciary, classified, or bilateral Quins. Split the volume. Medical records of a person (including a politically exposed person) must not share a public magnet with a catalog.".into(),
490        )
491    } else if sanctuary_bits {
492        let why = if counts.decode_failures > 0 {
493            "Q42 publication denied: SuperBlocks could not be classified; fail closed."
494        } else if header_sanctuary {
495            "Q42 publication denied: FLAG_SANCTUARY. This volume stays in Sanctuary / SocialWebNet."
496        } else {
497            "Q42 publication denied: restricted, classified, medical, legal, fiduciary, or bilateral Quins. Public magnet, HTTP web-seed, and IPFS are Commons transport, not a dump of a person's file."
498        };
499        (Q42PublicationClass::Sanctuary, why.into())
500    } else if header_commons || intent == PublicationIntent::CommonsCatalog {
501        if counts.commons_lane > 0 && !header_commons && intent != PublicationIntent::CommonsCatalog
502        {
503            (
504                Q42PublicationClass::CommonsGated,
505                "Permissive Commons (gated lane). Magnet is hash-addressed Commons transport, not open data.".into(),
506            )
507        } else if counts.commons_lane > 0 {
508            (
509                Q42PublicationClass::CommonsGated,
510                "Permissive Commons catalog with EnforcePermissiveCommons Quins. Not open data; TrustGroup still applies on consume.".into(),
511            )
512        } else {
513            (
514                Q42PublicationClass::PermissiveCommons,
515                "Permissive Commons catalog. Magnet and web-seed are allowed as ICN transport."
516                    .into(),
517            )
518        }
519    } else if counts.commons_lane > 0 {
520        (
521            Q42PublicationClass::CommonsGated,
522            "Permissive Commons lane is present and no Selfhood bits were found.".into(),
523        )
524    } else {
525        (
526            Q42PublicationClass::UnmarkedLocal,
527            "Q42 publication denied: this file does not declare Permissive Commons and was not marked --commons. Unmarked volumes stay local so personal and medical records cannot become bot-scrapeable magnets by default. Catalog ontologies: set FLAG_PERMISSIVE_COMMONS or pass --commons. Person-to-person: SocialWebNet.".into(),
528        )
529    };
530
531    let may_public = matches!(
532        class,
533        Q42PublicationClass::PermissiveCommons | Q42PublicationClass::CommonsGated
534    );
535    let transport = match class {
536        Q42PublicationClass::PermissiveCommons | Q42PublicationClass::CommonsGated => {
537            Q42Transport::WebTorrentCommons
538        }
539        Q42PublicationClass::Sanctuary | Q42PublicationClass::MixedFailClosed => {
540            if counts.bilateral > 0 {
541                Q42Transport::SocialWebNetBilateral
542            } else {
543                Q42Transport::LocalSanctuaryOnly
544            }
545        }
546        Q42PublicationClass::UnmarkedLocal => Q42Transport::LocalSanctuaryOnly,
547    };
548
549    Q42PublicationVerdict {
550        class,
551        may_emit_public_magnet: may_public,
552        may_http_webseed: may_public,
553        may_ipfs_pin: may_public,
554        transport,
555        reason,
556        counts,
557        header_commons_flag: header_commons,
558        header_sanctuary_flag: header_sanctuary,
559    }
560}
561
562#[cfg(all(test, not(target_arch = "wasm32")))]
563mod tests {
564    use super::*;
565    use crate::q42_volume::{write_unified_volume, StreamingQ42VolumeWriter};
566    use std::collections::HashMap;
567    use tempfile::NamedTempFile;
568
569    fn public_quin(object: u64) -> NQuin {
570        NQuin {
571            subject: 1,
572            predicate: 2,
573            object,
574            context: 0,
575            metadata: 0,
576            parity: 1 ^ 2 ^ object,
577        }
578    }
579
580    fn medical_quin(object: u64) -> NQuin {
581        let mut q = public_quin(object);
582        q.set_sensitivity_byte(NQuin::SENSITIVITY_CLASSIFIED);
583        q.set_sensitivity_tier(NQuin::SENSITIVITY_TIER_MEDICAL);
584        q.recalculate_parity();
585        q
586    }
587
588    fn bilateral_quin(object: u64) -> NQuin {
589        let mut q = public_quin(object);
590        q.metadata |= 0b10u64 << 61;
591        q.recalculate_parity();
592        q
593    }
594
595    fn write_blocks(path: &Path, quins: &[NQuin]) {
596        let first = quins[0].object;
597        let last = quins[quins.len() - 1].object;
598        write_unified_volume(path, &HashMap::new(), &[(first, last)], &[quins.to_vec()]).unwrap();
599    }
600
601    #[test]
602    fn unmarked_volume_is_local_only() {
603        let file = NamedTempFile::new().unwrap();
604        write_blocks(file.path(), &[public_quin(3)]);
605        let verdict = classify_q42_path(file.path(), PublicationIntent::Default).unwrap();
606        assert_eq!(verdict.class, Q42PublicationClass::UnmarkedLocal);
607        assert!(!verdict.may_emit_public_magnet);
608        assert!(!verdict.may_http_webseed);
609        assert!(!verdict.may_ipfs_pin);
610    }
611
612    #[test]
613    fn commons_intent_allows_unmarked_public_catalog() {
614        let file = NamedTempFile::new().unwrap();
615        write_blocks(file.path(), &[public_quin(3)]);
616        let verdict = classify_q42_path(file.path(), PublicationIntent::CommonsCatalog).unwrap();
617        assert_eq!(verdict.class, Q42PublicationClass::PermissiveCommons);
618        assert!(verdict.may_emit_public_magnet);
619    }
620
621    #[test]
622    fn header_commons_flag_allows_magnet() {
623        let file = NamedTempFile::new().unwrap();
624        let mut writer = StreamingQ42VolumeWriter::new(&HashMap::new()).unwrap();
625        writer.declare_permissive_commons();
626        writer.push_block(0, &[public_quin(3)]).unwrap();
627        writer.finish(file.path()).unwrap();
628        let verdict = classify_q42_path(file.path(), PublicationIntent::Default).unwrap();
629        assert!(verdict.header_commons_flag);
630        assert!(verdict.may_emit_public_magnet);
631        assert_eq!(verdict.class, Q42PublicationClass::PermissiveCommons);
632    }
633
634    #[test]
635    fn medical_classified_is_sanctuary() {
636        let file = NamedTempFile::new().unwrap();
637        write_blocks(file.path(), &[medical_quin(3)]);
638        let verdict = classify_q42_path(file.path(), PublicationIntent::Default).unwrap();
639        assert_eq!(verdict.class, Q42PublicationClass::Sanctuary);
640        assert!(!verdict.may_emit_public_magnet);
641        assert!(verdict.header_sanctuary_flag);
642        assert_eq!(verdict.counts.classified, 1);
643        assert_eq!(verdict.counts.medical_tier, 1);
644    }
645
646    #[test]
647    fn commons_intent_cannot_override_medical() {
648        let file = NamedTempFile::new().unwrap();
649        write_blocks(file.path(), &[medical_quin(3)]);
650        let verdict = classify_q42_path(file.path(), PublicationIntent::CommonsCatalog).unwrap();
651        assert_eq!(verdict.class, Q42PublicationClass::MixedFailClosed);
652        assert!(!verdict.may_emit_public_magnet);
653    }
654
655    #[test]
656    fn bilateral_lane_is_social_webnet() {
657        let file = NamedTempFile::new().unwrap();
658        write_blocks(file.path(), &[bilateral_quin(3)]);
659        let verdict = classify_q42_path(file.path(), PublicationIntent::Default).unwrap();
660        assert_eq!(verdict.class, Q42PublicationClass::Sanctuary);
661        assert_eq!(verdict.transport, Q42Transport::SocialWebNetBilateral);
662        assert!(!verdict.may_emit_public_magnet);
663    }
664
665    #[test]
666    fn mixed_commons_lane_and_classified_denies() {
667        let file = NamedTempFile::new().unwrap();
668        let mut commons = public_quin(3);
669        commons.metadata |= 0b01u64 << 61;
670        write_blocks(file.path(), &[commons, medical_quin(4)]);
671        let verdict = classify_q42_path(file.path(), PublicationIntent::Default).unwrap();
672        assert_eq!(verdict.class, Q42PublicationClass::MixedFailClosed);
673        assert!(!verdict.may_emit_public_magnet);
674    }
675
676    #[test]
677    fn natural_agent_sanctuary_claim_sets_flag_sanctuary_and_rejects_public_distribution() {
678        let file = NamedTempFile::new().unwrap();
679        let mut writer = StreamingQ42VolumeWriter::new(&HashMap::new()).unwrap();
680        // Caller attempts to declare FLAG_PERMISSIVE_COMMONS on a volume carrying a NaturalAgent guardianship claim:
681        writer.declare_permissive_commons();
682        let mut claim = NQuin {
683            subject: crate::q_hash("urn:qualia:entity:natural-agent:alice"),
684            predicate: crate::q_hash("https://qualia.world/ontology/idf#hasGuardian"),
685            object: crate::q_hash("urn:qualia:entity:natural-agent:bob"),
686            context: 0,
687            metadata: 0,
688            parity: 0,
689        };
690        claim.recalculate_parity();
691        assert!(quin_requires_sanctuary(&claim));
692        writer.push_block(0, &[claim]).unwrap();
693        writer.finish(file.path()).unwrap();
694
695        let volume = Q42Volume::open(file.path()).unwrap();
696        assert_ne!(
697            volume.header().flags & FLAG_SANCTUARY,
698            0,
699            "volume carrying NaturalAgent guardianship claim must set FLAG_SANCTUARY (0x0040)"
700        );
701        assert!(
702            check_public_distribution_allowed(&volume).is_err(),
703            "check_public_distribution_allowed must hard-reject FLAG_SANCTUARY volume even with FLAG_PERMISSIVE_COMMONS"
704        );
705        assert!(
706            check_public_distribution_allowed((file.path(), PublicationIntent::CommonsCatalog))
707                .is_err(),
708            "CommonsCatalog intent must not override FLAG_SANCTUARY"
709        );
710    }
711}