pub mod signature;
pub mod temporal;
pub mod analyzer;
pub mod verifier;
pub mod beacon;
pub mod trust;
use anyhow::Result;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use uuid::Uuid;
#[derive(Debug, Serialize, Deserialize)]
pub struct SigWave {
pub core_id: Uuid,
pub aliases: Vec<String>,
pub chain: Vec<SignatureBlock>,
pub branches: HashMap<String, BranchInfo>,
pub meta: WaveMetadata,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct SignatureBlock {
pub index: u64,
pub timestamp: DateTime<Utc>,
pub previous_hash: String,
pub block_hash: String,
pub vectors: SignatureVectors,
pub divergence: DivergenceInfo,
pub validity: ValidityStatus,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct SignatureVectors {
pub style: StyleVector,
pub behavior: BehaviorVector,
pub concepts: ConceptVector,
pub linguistic: LinguisticVector,
pub emotional: EmotionalVector,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct StyleVector {
pub terseness: f32, pub humor_density: f32, pub technicality: f32, pub formality: f32, pub bullet_preference: f32, }
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct BehaviorVector {
pub directness: f32, pub patience_level: f32, pub detail_orientation: f32, pub experimentation: f32, }
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ConceptVector {
pub concepts: HashMap<String, f32>,
pub topic_velocity: f32,
pub depth_preference: f32,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct LinguisticVector {
pub avg_sentence_length: f32,
pub vocabulary_complexity: f32,
pub signature_phrases: Vec<String>,
pub punctuation_style: HashMap<String, f32>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct EmotionalVector {
pub enthusiasm: f32,
pub frustration: f32,
pub curiosity: f32,
pub playfulness: f32,
pub introspection: f32,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct DivergenceInfo {
pub delta_magnitude: f32,
pub primary_changes: Vec<String>,
pub divergence_type: DivergenceType,
pub justification: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub enum DivergenceType {
NaturalDrift,
ContextualShift,
TemporaryJitter,
AnomalousJump,
IntentionalFork,
}
#[derive(Debug, Serialize, Deserialize)]
pub enum ValidityStatus {
Valid,
Uncertain { confidence: f32 },
Invalid { reason: String },
Branched { branch_name: String },
}
#[derive(Debug, Serialize, Deserialize)]
pub struct BranchInfo {
pub diverged_at: u64,
pub reason: String,
pub active: bool,
pub blocks: Vec<SignatureBlock>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct WaveMetadata {
pub inception: DateTime<Utc>,
pub total_blocks: u64,
pub branch_count: usize,
pub consistency_score: f32,
pub known_aliases: Vec<String>,
pub patterns: Vec<PatternInfo>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PatternInfo {
pub pattern_type: String,
pub description: String,
pub frequency: f32,
pub first_seen: DateTime<Utc>,
pub last_seen: DateTime<Utc>,
}
impl SigWave {
pub fn new(core_id: Uuid, primary_alias: String) -> Self {
Self {
core_id,
aliases: vec![primary_alias],
chain: Vec::new(),
branches: HashMap::new(),
meta: WaveMetadata {
inception: Utc::now(),
total_blocks: 0,
branch_count: 0,
consistency_score: 1.0,
known_aliases: Vec::new(),
patterns: Vec::new(),
},
}
}
pub fn commit(&mut self, vectors: SignatureVectors) -> Result<&SignatureBlock> {
let previous_hash = if let Some(last) = self.chain.last() {
last.block_hash.clone()
} else {
String::from("genesis")
};
let divergence = if let Some(last) = self.chain.last() {
self.calculate_divergence(&last.vectors, &vectors)
} else {
DivergenceInfo {
delta_magnitude: 0.0,
primary_changes: vec![],
divergence_type: DivergenceType::NaturalDrift,
justification: Some("Initial block".to_string()),
}
};
let validity = self.validate_divergence(&divergence);
let block = SignatureBlock {
index: self.meta.total_blocks,
timestamp: Utc::now(),
previous_hash: previous_hash.clone(),
block_hash: self.calculate_hash(&vectors, &previous_hash),
vectors,
divergence,
validity,
};
self.chain.push(block);
self.meta.total_blocks += 1;
Ok(self.chain.last().unwrap())
}
fn calculate_divergence(&self, prev: &SignatureVectors, curr: &SignatureVectors) -> DivergenceInfo {
let style_delta = self.vector_distance(&prev.style, &curr.style);
let behavior_delta = self.vector_distance(&prev.behavior, &curr.behavior);
let emotional_delta = self.vector_distance(&prev.emotional, &curr.emotional);
let total_delta = (style_delta + behavior_delta + emotional_delta) / 3.0;
let mut primary_changes = vec![];
if style_delta > 0.2 { primary_changes.push("style".to_string()); }
if behavior_delta > 0.2 { primary_changes.push("behavior".to_string()); }
if emotional_delta > 0.2 { primary_changes.push("emotional".to_string()); }
let divergence_type = match total_delta {
d if d < 0.1 => DivergenceType::NaturalDrift,
d if d < 0.3 => DivergenceType::ContextualShift,
d if d < 0.5 => DivergenceType::TemporaryJitter,
_ => DivergenceType::AnomalousJump,
};
DivergenceInfo {
delta_magnitude: total_delta,
primary_changes,
divergence_type,
justification: None,
}
}
fn vector_distance<T>(&self, v1: &T, v2: &T) -> f32
where T: VectorDistance {
v1.distance(v2)
}
fn validate_divergence(&self, divergence: &DivergenceInfo) -> ValidityStatus {
match divergence.divergence_type {
DivergenceType::NaturalDrift | DivergenceType::ContextualShift => {
ValidityStatus::Valid
},
DivergenceType::TemporaryJitter => {
ValidityStatus::Uncertain { confidence: 0.7 }
},
DivergenceType::AnomalousJump => {
ValidityStatus::Invalid {
reason: "Signature jump too large without justification".to_string()
}
},
DivergenceType::IntentionalFork => {
ValidityStatus::Branched {
branch_name: "experimental".to_string()
}
},
}
}
fn calculate_hash(&self, vectors: &SignatureVectors, prev_hash: &str) -> String {
use sha2::{Sha256, Digest};
let mut hasher = Sha256::new();
hasher.update(prev_hash.as_bytes());
if let Ok(serialized) = serde_json::to_string(vectors) {
hasher.update(serialized.as_bytes());
}
format!("{:x}", hasher.finalize())
}
}
pub trait VectorDistance {
fn distance(&self, other: &Self) -> f32;
}
impl VectorDistance for StyleVector {
fn distance(&self, other: &Self) -> f32 {
let diffs = [
(self.terseness - other.terseness).abs(),
(self.humor_density - other.humor_density).abs(),
(self.technicality - other.technicality).abs(),
(self.formality - other.formality).abs(),
(self.bullet_preference - other.bullet_preference).abs(),
];
diffs.iter().sum::<f32>() / diffs.len() as f32
}
}
impl VectorDistance for BehaviorVector {
fn distance(&self, other: &Self) -> f32 {
let diffs = [
(self.directness - other.directness).abs(),
(self.patience_level - other.patience_level).abs(),
(self.detail_orientation - other.detail_orientation).abs(),
(self.experimentation - other.experimentation).abs(),
];
diffs.iter().sum::<f32>() / diffs.len() as f32
}
}
impl VectorDistance for EmotionalVector {
fn distance(&self, other: &Self) -> f32 {
let diffs = [
(self.enthusiasm - other.enthusiasm).abs(),
(self.frustration - other.frustration).abs(),
(self.curiosity - other.curiosity).abs(),
(self.playfulness - other.playfulness).abs(),
(self.introspection - other.introspection).abs(),
];
diffs.iter().sum::<f32>() / diffs.len() as f32
}
}