vela-protocol 0.230.0

Core library for the Vela scientific knowledge protocol: replayable frontier state, signed canonical events, and proof packets.
Documentation
//! v0.193: Scientific Diff Pack (`vsd_*`).
//!
//! The per-proposal `carina.diff.v0.3` schema captures the change
//! a single proposal would induce on frontier state. A Scientific
//! Diff Pack sits one level up: it bundles N proposals into one
//! reviewable change-set so a reviewer sees a coherent unit
//! ("BBB-shared sister findings reconciled") rather than 12
//! individual events.
//!
//! Substrate-honest framing: the Pack is purely an aggregator. It
//! does NOT introduce new event semantics; applying the pack is
//! exactly equivalent to applying its member proposals in canonical
//! order through the existing reducer. The pack id is content-
//! addressed over the (frontier_id, ordered proposals,
//! aggregate_kind, summary, created_at) tuple and pinned by Lean
//! Theorem 23 (Scientific Diff Pack id injectivity).
//!
//! Composition with later cycles:
//!   - v0.195 vaa_*: Pack carries optional `agent_run: vaa_*` so
//!     a pack produced by an LLM agent links to its signed
//!     attestation envelope.
//!   - v0.200 ver_*: an Evaluation Record can target a `vsd_*`,
//!     letting "this pack was replicated by Lab X" be a first-
//!     class statement.
//!   - v0.201 diff_pack.released: a canonical event arm that turns
//!     a signed pack into a federated record across hubs.

use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

pub const SCIENTIFIC_DIFF_SCHEMA: &str = "vela.scientific_diff.v0.1";

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ScientificDiffPack {
    pub schema: String,
    pub pack_id: String,
    pub frontier_id: String,
    pub created_at: String,
    pub summary: String,
    pub proposals: Vec<String>,
    pub aggregate_kind: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent_run: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parent_pack: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub applied_event_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub signer_pubkey_hex: Option<String>,
}

#[derive(Debug, Clone)]
pub struct PackDraft {
    pub frontier_id: String,
    pub created_at: String,
    pub summary: String,
    pub proposals: Vec<String>,
    pub aggregate_kind: String,
    pub agent_run: Option<String>,
    pub parent_pack: Option<String>,
}

impl ScientificDiffPack {
    /// Build an unsigned pack from a draft. The pack_id is
    /// content-addressed over canonical bytes; signing is a
    /// separate step via `sign`.
    pub fn build(draft: PackDraft) -> Result<Self, String> {
        validate_draft(&draft)?;
        let mut pack = Self {
            schema: SCIENTIFIC_DIFF_SCHEMA.to_string(),
            pack_id: String::new(),
            frontier_id: draft.frontier_id,
            created_at: draft.created_at,
            summary: draft.summary,
            proposals: draft.proposals,
            aggregate_kind: draft.aggregate_kind,
            agent_run: draft.agent_run,
            parent_pack: draft.parent_pack,
            applied_event_id: None,
            signature: None,
            signer_pubkey_hex: None,
        };
        pack.pack_id = pack.derive_id();
        Ok(pack)
    }

    /// Sign the pack with an Ed25519 key. Sets `signature` and
    /// `signer_pubkey_hex`; does NOT change `pack_id` (the pack
    /// is content-addressed over its body, not its signature).
    pub fn sign(&mut self, key: &SigningKey) {
        let preimage = self.preimage_bytes();
        let sig = key.sign(&preimage);
        self.signature = Some(hex::encode(sig.to_bytes()));
        self.signer_pubkey_hex = Some(hex::encode(key.verifying_key().to_bytes()));
    }

    /// Canonical bytes over which pack_id is derived AND signatures
    /// are computed. The order of fields is fixed; any change to
    /// this method is a breaking schema bump.
    fn preimage_bytes(&self) -> Vec<u8> {
        let mut out = Vec::new();
        out.extend_from_slice(self.frontier_id.as_bytes());
        out.push(b'|');
        out.extend_from_slice(self.aggregate_kind.as_bytes());
        out.push(b'|');
        out.extend_from_slice(self.summary.as_bytes());
        out.push(b'|');
        out.extend_from_slice(self.created_at.as_bytes());
        out.push(b'|');
        for (i, vpr) in self.proposals.iter().enumerate() {
            if i > 0 {
                out.push(b',');
            }
            out.extend_from_slice(vpr.as_bytes());
        }
        out.push(b'|');
        if let Some(parent) = &self.parent_pack {
            out.extend_from_slice(parent.as_bytes());
        }
        out.push(b'|');
        if let Some(agent) = &self.agent_run {
            out.extend_from_slice(agent.as_bytes());
        }
        out
    }

    fn derive_id(&self) -> String {
        let mut hasher = Sha256::new();
        hasher.update(self.preimage_bytes());
        format!("vsd_{}", &hex::encode(hasher.finalize())[..16])
    }

    /// Verify: pack_id matches re-derivation; if a signature is
    /// present, it verifies under the declared pubkey.
    pub fn verify(&self) -> Result<(), String> {
        let rederived = self.derive_id();
        if rederived != self.pack_id {
            return Err(format!(
                "pack_id mismatch: declared {}, rebuilt {}",
                self.pack_id, rederived
            ));
        }
        if let (Some(sig_hex), Some(pub_hex)) = (&self.signature, &self.signer_pubkey_hex) {
            let pubkey_bytes = hex::decode(pub_hex).map_err(|e| format!("decode pubkey: {e}"))?;
            let pubkey_arr: [u8; 32] = pubkey_bytes
                .try_into()
                .map_err(|_| "pubkey must be 32 bytes".to_string())?;
            let verifying =
                VerifyingKey::from_bytes(&pubkey_arr).map_err(|e| format!("verifying key: {e}"))?;
            let sig_bytes = hex::decode(sig_hex).map_err(|e| format!("decode signature: {e}"))?;
            let sig_arr: [u8; 64] = sig_bytes
                .try_into()
                .map_err(|_| "signature must be 64 bytes".to_string())?;
            let sig = Signature::from_bytes(&sig_arr);
            verifying
                .verify(&self.preimage_bytes(), &sig)
                .map_err(|e| format!("signature verify: {e}"))?;
        } else if self.signature.is_some() || self.signer_pubkey_hex.is_some() {
            return Err("signature and signer_pubkey_hex must be set together".to_string());
        }
        Ok(())
    }
}

fn validate_draft(d: &PackDraft) -> Result<(), String> {
    if !d.frontier_id.starts_with("vfr_") {
        return Err(format!(
            "frontier_id must start with `vfr_`, got `{}`",
            d.frontier_id
        ));
    }
    if d.summary.is_empty() {
        return Err("summary cannot be empty".to_string());
    }
    if d.summary.chars().count() > 280 {
        return Err("summary exceeds 280 chars".to_string());
    }
    if d.proposals.is_empty() {
        return Err("a pack must bundle at least one proposal".to_string());
    }
    for vpr in &d.proposals {
        if !vpr.starts_with("vpr_") {
            return Err(format!("every member must start with `vpr_`, got `{vpr}`"));
        }
    }
    if d.aggregate_kind.is_empty() {
        return Err("aggregate_kind cannot be empty".to_string());
    }
    if let Some(parent) = &d.parent_pack
        && !parent.starts_with("vsd_")
    {
        return Err(format!(
            "parent_pack must start with `vsd_`, got `{parent}`"
        ));
    }
    if let Some(agent) = &d.agent_run
        && !agent.starts_with("vaa_")
    {
        return Err(format!("agent_run must start with `vaa_`, got `{agent}`"));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use rand::rngs::OsRng;

    fn key() -> SigningKey {
        SigningKey::generate(&mut OsRng)
    }

    fn ok_draft() -> PackDraft {
        PackDraft {
            frontier_id: "vfr_5076e7b3ff8e6b0f".to_string(),
            created_at: "2026-05-11T00:00:00Z".to_string(),
            summary: "Test pack — bundles two proposals.".to_string(),
            proposals: vec!["vpr_a1".to_string(), "vpr_b2".to_string()],
            aggregate_kind: "finding.cluster_revision".to_string(),
            agent_run: None,
            parent_pack: None,
        }
    }

    #[test]
    fn builds_and_id_is_deterministic() {
        let p1 = ScientificDiffPack::build(ok_draft()).unwrap();
        let p2 = ScientificDiffPack::build(ok_draft()).unwrap();
        assert_eq!(p1.pack_id, p2.pack_id);
        assert!(p1.pack_id.starts_with("vsd_"));
        assert_eq!(p1.pack_id.len(), 4 + 16);
    }

    #[test]
    fn different_proposals_produce_different_ids() {
        let p1 = ScientificDiffPack::build(ok_draft()).unwrap();
        let mut d2 = ok_draft();
        d2.proposals = vec!["vpr_b2".to_string(), "vpr_a1".to_string()];
        let p2 = ScientificDiffPack::build(d2).unwrap();
        assert_ne!(p1.pack_id, p2.pack_id, "order matters in pack_id");
    }

    #[test]
    fn empty_pack_rejected() {
        let mut d = ok_draft();
        d.proposals.clear();
        assert!(ScientificDiffPack::build(d).is_err());
    }

    #[test]
    fn non_vpr_member_rejected() {
        let mut d = ok_draft();
        d.proposals[0] = "vsd_not_a_vpr".to_string();
        assert!(ScientificDiffPack::build(d).is_err());
    }

    #[test]
    fn summary_length_capped() {
        let mut d = ok_draft();
        d.summary = "x".repeat(281);
        assert!(ScientificDiffPack::build(d).is_err());
    }

    #[test]
    fn sign_then_verify() {
        let mut pack = ScientificDiffPack::build(ok_draft()).unwrap();
        pack.sign(&key());
        pack.verify().expect("verifies after signing");
    }

    #[test]
    fn tampered_body_after_sign_fails_verify() {
        let mut pack = ScientificDiffPack::build(ok_draft()).unwrap();
        pack.sign(&key());
        pack.summary = "different summary".to_string();
        // pack_id no longer matches re-derivation.
        assert!(pack.verify().is_err());
    }

    #[test]
    fn unsigned_pack_verifies_without_keys() {
        let pack = ScientificDiffPack::build(ok_draft()).unwrap();
        pack.verify().expect("unsigned pack still verifies its id");
    }

    #[test]
    fn cross_impl_python_sdk_pinned_id() {
        // v0.196: the Python `vela_agent` SDK mirrors this canonical-
        // bytes layout. The constants below are produced by the
        // Python SDK on the exact same inputs (see
        // clients/python/vela_agent/tests/test_primitives.py). Any
        // drift in either implementation flags here.
        let p = ScientificDiffPack::build(PackDraft {
            frontier_id: "vfr_5076e7b3ff8e6b0f".to_string(),
            created_at: "2026-05-11T00:00:00Z".to_string(),
            summary: "Test pack — bundles two proposals.".to_string(),
            proposals: vec!["vpr_a1".to_string(), "vpr_b2".to_string()],
            aggregate_kind: "finding.cluster_revision".to_string(),
            agent_run: None,
            parent_pack: None,
        })
        .unwrap();
        assert_eq!(p.pack_id, "vsd_cd2a0071e7ffbffd");
    }

    #[test]
    fn round_trips_through_json() {
        let mut pack = ScientificDiffPack::build(ok_draft()).unwrap();
        pack.sign(&key());
        let s = serde_json::to_string(&pack).unwrap();
        let back: ScientificDiffPack = serde_json::from_str(&s).unwrap();
        assert_eq!(pack, back);
        back.verify().unwrap();
    }
}