diff --git a/Cargo.lock b/Cargo.lock index fa786237..6ed9125c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -126,6 +126,31 @@ dependencies = [ "parking_lot", ] +[[package]] +name = "aien-protocol-types" +version = "0.1.0" +dependencies = [ + "hex", + "serde", + "serde_json", + "thiserror 1.0.69", + "uuid", +] + +[[package]] +name = "aien-provenance" +version = "0.1.0" +dependencies = [ + "aien-protocol-types", + "bitflags 2.13.2", + "hex", + "serde", + "serde_json", + "sha2", + "thiserror 1.0.69", + "uuid", +] + [[package]] name = "aien-runtime" version = "0.1.0" @@ -490,6 +515,9 @@ name = "bitflags" version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +dependencies = [ + "serde_core", +] [[package]] name = "blake3" @@ -3373,6 +3401,9 @@ dependencies = [ name = "spark-harvester" version = "0.1.0" dependencies = [ + "aien-protocol-types", + "aien-provenance", + "bitflags 2.13.2", "chrono", "clap", "regex", @@ -3380,6 +3411,7 @@ dependencies = [ "serde", "serde_json", "sha2", + "tempfile", "thiserror 1.0.69", "tokio", "tracing", diff --git a/crates/spark-harvester/Cargo.toml b/crates/spark-harvester/Cargo.toml index ff576ad6..3a7d8204 100644 --- a/crates/spark-harvester/Cargo.toml +++ b/crates/spark-harvester/Cargo.toml @@ -4,7 +4,7 @@ version = "0.1.0" edition = "2021" authors = ["Drake Stapleton "] license.workspace = true -description = "Native Rust engine for harvesting reasoning traces from commercial APIs to distill open models for humanity" +description = "Native Rust rights-gated harvester and provenance engine for sovereign AI datasets" [dependencies] tokio = { version = "1.38", features = ["full"] } @@ -19,3 +19,9 @@ uuid = { version = "1.8", features = ["v4", "serde"] } regex = "1.10" sha2 = "0.10" thiserror = "1.0" +bitflags = { version = "2.5", features = ["serde"] } +aien-protocol-types = { path = "../../../aien-protocols/crates/aien-protocol-types" } +aien-provenance = { path = "../../../aien-protocols/crates/aien-provenance" } + +[dev-dependencies] +tempfile = "3.17" diff --git a/crates/spark-harvester/src/lib.rs b/crates/spark-harvester/src/lib.rs index b74e9509..6e9135ff 100644 --- a/crates/spark-harvester/src/lib.rs +++ b/crates/spark-harvester/src/lib.rs @@ -7,3 +7,6 @@ pub use client::HarvesterClient; pub use export::DatasetExporter; pub use extractor::{ExtractedPair, ReasoningExtractor}; pub use filter::DeduplicationFilter; + +pub mod rights_gate; +pub use rights_gate::{BundleKind, GatedDatasetBundle, GatedDatasetRecord, RightsGate}; diff --git a/crates/spark-harvester/src/rights_gate.rs b/crates/spark-harvester/src/rights_gate.rs new file mode 100644 index 00000000..8d96c9f9 --- /dev/null +++ b/crates/spark-harvester/src/rights_gate.rs @@ -0,0 +1,161 @@ +use crate::extractor::ExtractedPair; +use aien_protocol_types::Digest32; +use aien_provenance::{GrantPermissions, ProvenanceError, SourceGrant}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::fs::OpenOptions; +use std::io::{self, Write}; +use std::path::Path; +use uuid::Uuid; + +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] +pub enum BundleKind { + Training, + Distillation, + Evidence, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct GatedDatasetRecord { + pub record_id: Uuid, + pub bundle_kind: BundleKind, + pub grant_id: Uuid, + pub source_uri: String, + pub license_spdx: String, + pub pair: ExtractedPair, + pub provenance_digest: Digest32, +} + +impl GatedDatasetRecord { + pub fn compute_digest(&self) -> Digest32 { + let mut hasher = Sha256::new(); + hasher.update(self.record_id.as_bytes()); + hasher.update(self.grant_id.as_bytes()); + hasher.update(self.source_uri.as_bytes()); + hasher.update(self.license_spdx.as_bytes()); + hasher.update(self.pair.prompt.as_bytes()); + hasher.update(self.pair.completion.as_bytes()); + if let Some(ref r) = self.pair.reasoning { + hasher.update(r.as_bytes()); + } + Digest32(hasher.finalize().into()) + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct GatedDatasetBundle { + pub bundle_id: Uuid, + pub bundle_kind: BundleKind, + pub license_spdx: String, + pub records: Vec, + pub merkle_root: Digest32, + pub created_at: String, +} + +pub struct RightsGate; + +impl RightsGate { + /// Validates an array of extracted pairs against a SourceGrant and builds an immutable GatedDatasetBundle. + /// Fails closed if the grant lacks required permissions or contains an unapproved license. + pub fn validate_and_bundle( + grant: &SourceGrant, + pairs: &[ExtractedPair], + bundle_kind: BundleKind, + allowed_licenses: &[&str], + ) -> Result { + // 1. Verify license compatibility + grant.verify_license(allowed_licenses)?; + + // 2. Verify grant permissions based on bundle kind + let required_perm = match bundle_kind { + BundleKind::Training => GrantPermissions::TRAIN, + BundleKind::Distillation => GrantPermissions::DISTILL, + BundleKind::Evidence => GrantPermissions::EVALUATE, + }; + grant.verify_permission(required_perm)?; + + // 3. Build records and compute individual provenance digests + let mut records = Vec::with_capacity(pairs.len()); + let mut digests = Vec::with_capacity(pairs.len()); + + for pair in pairs { + let record_id = Uuid::new_v4(); + let mut record = GatedDatasetRecord { + record_id, + bundle_kind, + grant_id: grant.grant_id, + source_uri: grant.source_uri.clone(), + license_spdx: grant.license_spdx.clone(), + pair: pair.clone(), + provenance_digest: Digest32::ZERO, + }; + record.provenance_digest = record.compute_digest(); + digests.push(record.provenance_digest); + records.push(record); + } + + // 4. Compute Merkle root over records + let merkle_root = Self::compute_merkle_root(&digests); + + Ok(GatedDatasetBundle { + bundle_id: Uuid::new_v4(), + bundle_kind, + license_spdx: grant.license_spdx.clone(), + records, + merkle_root, + created_at: chrono::Utc::now().to_rfc3339(), + }) + } + + /// Exports a bundle to a JSONL file with strict segregation enforcement. + /// Evidence bundles are barred from being written to training/sft/dpo dataset paths. + pub fn export_bundle(bundle: &GatedDatasetBundle, output_path: &Path) -> io::Result { + let path_str = output_path.to_string_lossy().to_lowercase(); + if bundle.bundle_kind == BundleKind::Evidence { + if path_str.contains("train") || path_str.contains("sft") || path_str.contains("dpo") { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "Evidence bundles are strictly quarantined and cannot be written to training or distillation dataset paths", + )); + } + } + + let file = OpenOptions::new() + .create(true) + .append(true) + .open(output_path)?; + let mut writer = io::BufWriter::new(file); + + let mut count = 0; + for record in &bundle.records { + let serialized = serde_json::to_string(record)?; + writer.write_all(serialized.as_bytes())?; + writer.write_all(b"\n")?; + count += 1; + } + writer.flush()?; + Ok(count) + } + + fn compute_merkle_root(digests: &[Digest32]) -> Digest32 { + if digests.is_empty() { + return Digest32::ZERO; + } + let mut current = digests.to_vec(); + while current.len() > 1 { + let mut next = Vec::new(); + for chunk in current.chunks(2) { + let mut hasher = Sha256::new(); + hasher.update(&chunk[0].0); + if chunk.len() > 1 { + hasher.update(&chunk[1].0); + } else { + hasher.update(&chunk[0].0); + } + next.push(Digest32(hasher.finalize().into())); + } + current = next; + } + current[0] + } +} diff --git a/crates/spark-harvester/tests/rights_gating_tests.rs b/crates/spark-harvester/tests/rights_gating_tests.rs new file mode 100644 index 00000000..41a1c044 --- /dev/null +++ b/crates/spark-harvester/tests/rights_gating_tests.rs @@ -0,0 +1,126 @@ +use aien_provenance::{GrantPermissions, ProvenanceError, SourceGrant}; +use spark_harvester::{BundleKind, ExtractedPair, RightsGate}; +use std::io::ErrorKind; + +fn create_test_pair() -> ExtractedPair { + ExtractedPair { + prompt: "Explain copy-on-write paged attention".to_string(), + reasoning: Some("Analyze memory refcounting and block sharing mechanics".to_string()), + completion: "CoW allocates physical pages only when divergent tokens are written to a shared block.".to_string(), + provider: "sovereign-lab".to_string(), + model: "atlas-omni-reasoning".to_string(), + token_count: 32, + quality_score: 0.98, + } +} + +#[test] +fn test_rights_gated_training_bundle_admitted_with_valid_grant() { + let grant = SourceGrant::new( + "https://hf.co/datasets/aien/sovereign-math".to_string(), + "Apache-2.0".to_string(), + GrantPermissions::TRAIN | GrantPermissions::DISTILL, + "Atlas Rights Authority".to_string(), + ); + + let pairs = vec![create_test_pair()]; + let bundle = RightsGate::validate_and_bundle( + &grant, + &pairs, + BundleKind::Training, + &["Apache-2.0", "MIT", "SRCL-1.0"], + ) + .expect("Valid training grant must be accepted"); + + assert_eq!(bundle.bundle_kind, BundleKind::Training); + assert_eq!(bundle.records.len(), 1); + assert_ne!(bundle.merkle_root, aien_protocol_types::Digest32::ZERO); + assert_eq!(bundle.records[0].source_uri, "https://hf.co/datasets/aien/sovereign-math"); +} + +#[test] +fn test_unapproved_license_rejected() { + let grant = SourceGrant::new( + "https://example.com/proprietary-dataset".to_string(), + "CC-BY-NC-4.0".to_string(), + GrantPermissions::TRAIN, + "Untrusted Third Party".to_string(), + ); + + let pairs = vec![create_test_pair()]; + let res = RightsGate::validate_and_bundle( + &grant, + &pairs, + BundleKind::Training, + &["Apache-2.0", "MIT", "SRCL-1.0"], + ); + + match res { + Err(ProvenanceError::IncompatibleLicense { license }) => { + assert_eq!(license, "CC-BY-NC-4.0"); + } + other => panic!("Expected IncompatibleLicense, got {:?}", other), + } +} + +#[test] +fn test_missing_permission_rejected() { + let grant = SourceGrant::new( + "https://hf.co/datasets/aien/eval-set".to_string(), + "MIT".to_string(), + GrantPermissions::EVALUATE, // Only EVALUATE, not TRAIN + "Atlas Rights Authority".to_string(), + ); + + let pairs = vec![create_test_pair()]; + let res = RightsGate::validate_and_bundle( + &grant, + &pairs, + BundleKind::Training, + &["Apache-2.0", "MIT", "SRCL-1.0"], + ); + + match res { + Err(ProvenanceError::PermissionDenied { required, granted }) => { + assert_eq!(required, GrantPermissions::TRAIN); + assert_eq!(granted, GrantPermissions::EVALUATE); + } + other => panic!("Expected PermissionDenied, got {:?}", other), + } +} + +#[test] +fn test_evidence_bundle_quarantine_enforced() { + let grant = SourceGrant::new( + "https://hf.co/datasets/aien/benchmark-evidence".to_string(), + "MIT".to_string(), + GrantPermissions::EVALUATE, + "Atlas Rights Authority".to_string(), + ); + + let pairs = vec![create_test_pair()]; + let bundle = RightsGate::validate_and_bundle( + &grant, + &pairs, + BundleKind::Evidence, + &["Apache-2.0", "MIT", "SRCL-1.0"], + ) + .expect("Evidence grant must be accepted"); + + let tmp = tempfile::tempdir().unwrap(); + + // 1. Attempting to export evidence bundle to training path fails closed + let train_path = tmp.path().join("train_dataset.jsonl"); + let err = RightsGate::export_bundle(&bundle, &train_path).unwrap_err(); + assert_eq!(err.kind(), ErrorKind::PermissionDenied); + + let sft_path = tmp.path().join("sft.jsonl"); + let err_sft = RightsGate::export_bundle(&bundle, &sft_path).unwrap_err(); + assert_eq!(err_sft.kind(), ErrorKind::PermissionDenied); + + // 2. Exporting to quarantine evidence path succeeds + let evidence_path = tmp.path().join("evidence_audit.jsonl"); + let count = RightsGate::export_bundle(&bundle, &evidence_path).expect("Evidence export must succeed"); + assert_eq!(count, 1); + assert!(evidence_path.exists()); +}