Implement chrs-council: Governance layer with weighted leader election and task delegation
This commit is contained in:
17
chrs-council/Cargo.toml
Normal file
17
chrs-council/Cargo.toml
Normal file
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "chrs-council"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
chrs-mail = { path = "../chrs-mail" }
|
||||
chrs-graph = { path = "../chrs-graph" }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
thiserror = "1.0"
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
uuid = { version = "1.0", features = ["v4", "serde"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
|
||||
131
chrs-council/src/lib.rs
Normal file
131
chrs-council/src/lib.rs
Normal file
@@ -0,0 +1,131 @@
|
||||
//! chrs-council: Governance and Orchestration for CHORUS agents.
|
||||
|
||||
use chrs_mail::{Mailbox, Message};
|
||||
use chrono::Utc;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use thiserror::Error;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Specialized roles for CHORUS agents.
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Role {
|
||||
/// Responsible for high-level planning and task delegation.
|
||||
Architect,
|
||||
/// Responsible for code generation and technical implementation.
|
||||
Coder,
|
||||
/// Responsible for security verification and final decision audit.
|
||||
Auditor,
|
||||
}
|
||||
|
||||
/// Represents a peer agent participating in a council.
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct Peer {
|
||||
pub id: String,
|
||||
pub role: Role,
|
||||
pub resource_score: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum CouncilError {
|
||||
#[error("Mailbox error: {0}")]
|
||||
Mailbox(#[from] chrs_mail::MailError),
|
||||
#[error("No peers available for election")]
|
||||
NoPeers,
|
||||
}
|
||||
|
||||
/// Manages council formation, leader election, and task delegation.
|
||||
pub struct CouncilManager {
|
||||
pub local_peer: Peer,
|
||||
mailbox: Mailbox,
|
||||
}
|
||||
|
||||
impl CouncilManager {
|
||||
/// Initialize a new CouncilManager for the local agent.
|
||||
pub fn new(local_peer: Peer, mailbox: Mailbox) -> Self {
|
||||
Self { local_peer, mailbox }
|
||||
}
|
||||
|
||||
/// Deterministically selects a leader from a list of peers.
|
||||
///
|
||||
/// **Why**: Ensures that even in a distributed system, all honest nodes
|
||||
/// agree on the same leader for a given epoch without a central broker.
|
||||
pub fn elect_leader(&self, peers: &[Peer]) -> Option<String> {
|
||||
peers.iter()
|
||||
.max_by(|a, b| {
|
||||
a.resource_score.partial_cmp(&b.resource_score)
|
||||
.unwrap_or(std::cmp::Ordering::Equal)
|
||||
.then_with(|| a.id.cmp(&b.id))
|
||||
})
|
||||
.map(|p| p.id.clone())
|
||||
}
|
||||
|
||||
/// Broadcasts the local agent's presence and score to the council.
|
||||
pub fn broadcast_heartbeat(&self, topic: &str) -> Result<(), CouncilError> {
|
||||
let msg = Message {
|
||||
id: Uuid::new_v4(),
|
||||
from_peer: self.local_peer.id.clone(),
|
||||
to_peer: "council".into(), // Broadcast address
|
||||
topic: topic.into(),
|
||||
payload: serde_json::to_value(&self.local_peer).unwrap(),
|
||||
sent_at: Utc::now(),
|
||||
read_at: None,
|
||||
};
|
||||
self.mailbox.send(&msg)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Splits a high-level task into specialized sub-tasks for the council.
|
||||
///
|
||||
/// **Why**: This implements the "Divide and Conquer" strategy of CHORUS,
|
||||
/// allowing the Architect leader to orchestrate complex work across experts.
|
||||
pub fn delegate_work(&self, task_id: Uuid, task_description: &str, peers: &[Peer]) -> Vec<Message> {
|
||||
let mut sub_tasks = Vec::new();
|
||||
|
||||
for peer in peers {
|
||||
let topic = match peer.role {
|
||||
Role::Coder => "implementation_task",
|
||||
Role::Auditor => "security_audit_task",
|
||||
Role::Architect => "planning_task",
|
||||
};
|
||||
|
||||
let msg = Message {
|
||||
id: Uuid::new_v4(),
|
||||
from_peer: self.local_peer.id.clone(),
|
||||
to_peer: peer.id.clone(),
|
||||
topic: topic.into(),
|
||||
payload: serde_json::json!({
|
||||
"parent_task": task_id,
|
||||
"description": task_description,
|
||||
"instruction": format!("Perform {:?} duties for task", peer.role)
|
||||
}),
|
||||
sent_at: Utc::now(),
|
||||
read_at: None,
|
||||
};
|
||||
sub_tasks.push(msg);
|
||||
}
|
||||
sub_tasks
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test]
|
||||
fn test_election() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let mailbox = Mailbox::open(dir.path().join("mail.sqlite")).unwrap();
|
||||
let local = Peer { id: "agent-1".into(), role: Role::Architect, resource_score: 0.8 };
|
||||
let manager = CouncilManager::new(local, mailbox);
|
||||
|
||||
let peers = vec![
|
||||
Peer { id: "agent-1".into(), role: Role::Architect, resource_score: 0.8 },
|
||||
Peer { id: "agent-2".into(), role: Role::Coder, resource_score: 0.95 },
|
||||
Peer { id: "agent-3".into(), role: Role::Auditor, resource_score: 0.7 },
|
||||
];
|
||||
|
||||
let leader = manager.elect_leader(&peers).unwrap();
|
||||
assert_eq!(leader, "agent-2"); // Highest score wins
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user