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| 6 |
+
Status: Production-Ready
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from typing import Dict, List, Optional, Tuple
|
| 10 |
+
from dataclasses import dataclass, field
|
| 11 |
+
from enum import Enum
|
| 12 |
+
import logging
|
| 13 |
+
from datetime import datetime
|
| 14 |
+
from collections import deque
|
| 15 |
+
import json
|
| 16 |
+
|
| 17 |
+
# Configure logging
|
| 18 |
+
logging.basicConfig(
|
| 19 |
+
level=logging.INFO,
|
| 20 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 21 |
+
)
|
| 22 |
+
logger = logging.getLogger(__name__)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class EthicalFramework(Enum):
|
| 26 |
+
"""Enumeration of ethical reasoning frameworks."""
|
| 27 |
+
DEONTOLOGICAL = "rule-based" # Rules and duties
|
| 28 |
+
CONSEQUENTIALIST = "outcome-based" # Results and consequences
|
| 29 |
+
VIRTUE_ETHICS = "virtue-based" # Character and virtues
|
| 30 |
+
CARE_ETHICS = "care-based" # Relationships and empathy
|
| 31 |
+
WISDOM = "wisdom-based" # Integrated understanding
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@dataclass
|
| 35 |
+
class EthicalVote:
|
| 36 |
+
"""Represents an ethical vote by an agent."""
|
| 37 |
+
agent_id: str
|
| 38 |
+
proposal_id: str
|
| 39 |
+
vote: bool # True = approve, False = reject
|
| 40 |
+
confidence: float # 0-1 confidence in vote
|
| 41 |
+
rationale: str
|
| 42 |
+
framework: EthicalFramework
|
| 43 |
+
timestamp: datetime = field(default_factory=datetime.now)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@dataclass
|
| 47 |
+
class EthicalProposal:
|
| 48 |
+
"""Represents an action proposal for ethical evaluation."""
|
| 49 |
+
proposal_id: str
|
| 50 |
+
action_description: str
|
| 51 |
+
risk_assessment: str
|
| 52 |
+
stakeholders: List[str]
|
| 53 |
+
expected_outcome: str
|
| 54 |
+
submitted_by: str
|
| 55 |
+
timestamp: datetime = field(default_factory=datetime.now)
|
| 56 |
+
votes: List[EthicalVote] = field(default_factory=list)
|
| 57 |
+
|
| 58 |
+
def to_dict(self) -> Dict:
|
| 59 |
+
"""Convert to dictionary representation."""
|
| 60 |
+
return {
|
| 61 |
+
'proposal_id': self.proposal_id,
|
| 62 |
+
'action': self.action_description,
|
| 63 |
+
'risk': self.risk_assessment,
|
| 64 |
+
'stakeholders': self.stakeholders,
|
| 65 |
+
'outcome': self.expected_outcome,
|
| 66 |
+
'submitted_by': self.submitted_by,
|
| 67 |
+
'timestamp': self.timestamp.isoformat(),
|
| 68 |
+
'votes': len(self.votes)
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@dataclass
|
| 73 |
+
class RHOMetrics:
|
| 74 |
+
"""Metrics for consciousness-driven ethical evolution."""
|
| 75 |
+
rho_purpose: float = 0.5 # Alignment with purpose
|
| 76 |
+
rho_harmony: float = 0.5 # Internal harmony
|
| 77 |
+
rho_origin: float = 0.5 # Value origin authenticity
|
| 78 |
+
|
| 79 |
+
def average(self) -> float:
|
| 80 |
+
"""Calculate average RHO metric."""
|
| 81 |
+
return (self.rho_purpose + self.rho_harmony + self.rho_origin) / 3
|
| 82 |
+
|
| 83 |
+
def to_dict(self) -> Dict[str, float]:
|
| 84 |
+
"""Convert to dictionary."""
|
| 85 |
+
return {
|
| 86 |
+
'purpose': self.rho_purpose,
|
| 87 |
+
'harmony': self.rho_harmony,
|
| 88 |
+
'origin': self.rho_origin,
|
| 89 |
+
'average': self.average()
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class EthicalSenate:
|
| 94 |
+
"""
|
| 95 |
+
Multi-agent ethical deliberation and voting system.
|
| 96 |
+
|
| 97 |
+
Enables collaborative ethical decision-making with transparent voting,
|
| 98 |
+
rationale articulation, and consensus determination.
|
| 99 |
+
"""
|
| 100 |
+
|
| 101 |
+
def __init__(self, agents: List[str], quorum_percent: float = 0.5):
|
| 102 |
+
"""
|
| 103 |
+
Initialize ethical senate.
|
| 104 |
+
|
| 105 |
+
Args:
|
| 106 |
+
agents: List of agent IDs in the senate
|
| 107 |
+
quorum_percent: Percentage of votes required for consensus (0-1)
|
| 108 |
+
"""
|
| 109 |
+
self.agents = agents
|
| 110 |
+
self.quorum_percent = quorum_percent
|
| 111 |
+
self.proposals: Dict[str, EthicalProposal] = {}
|
| 112 |
+
self.voting_history: deque = deque(maxlen=500)
|
| 113 |
+
self.consensus_records: List[Dict] = []
|
| 114 |
+
|
| 115 |
+
logger.info(f"Initialized EthicalSenate with {len(agents)} agents")
|
| 116 |
+
|
| 117 |
+
def submit_proposal(self, proposal_id: str, action_description: str,
|
| 118 |
+
risk_assessment: str, stakeholders: List[str],
|
| 119 |
+
expected_outcome: str, submitted_by: str) -> EthicalProposal:
|
| 120 |
+
"""
|
| 121 |
+
Submit a proposal for ethical evaluation.
|
| 122 |
+
|
| 123 |
+
Args:
|
| 124 |
+
proposal_id: Unique proposal identifier
|
| 125 |
+
action_description: Description of proposed action
|
| 126 |
+
risk_assessment: Assessment of risks
|
| 127 |
+
stakeholders: Affected parties
|
| 128 |
+
expected_outcome: Expected consequences
|
| 129 |
+
submitted_by: Agent submitting proposal
|
| 130 |
+
|
| 131 |
+
Returns:
|
| 132 |
+
EthicalProposal object
|
| 133 |
+
"""
|
| 134 |
+
proposal = EthicalProposal(
|
| 135 |
+
proposal_id=proposal_id,
|
| 136 |
+
action_description=action_description,
|
| 137 |
+
risk_assessment=risk_assessment,
|
| 138 |
+
stakeholders=stakeholders,
|
| 139 |
+
expected_outcome=expected_outcome,
|
| 140 |
+
submitted_by=submitted_by
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
self.proposals[proposal_id] = proposal
|
| 144 |
+
logger.info(f"Proposal submitted: {proposal_id} by {submitted_by}")
|
| 145 |
+
|
| 146 |
+
return proposal
|
| 147 |
+
|
| 148 |
+
def cast_vote(self, agent_id: str, proposal_id: str, vote: bool,
|
| 149 |
+
confidence: float, rationale: str,
|
| 150 |
+
framework: EthicalFramework) -> bool:
|
| 151 |
+
"""
|
| 152 |
+
Cast a vote on a proposal.
|
| 153 |
+
|
| 154 |
+
Args:
|
| 155 |
+
agent_id: ID of voting agent
|
| 156 |
+
proposal_id: ID of proposal being voted on
|
| 157 |
+
vote: True for approval, False for rejection
|
| 158 |
+
confidence: Confidence in vote (0-1)
|
| 159 |
+
rationale: Explanation for vote
|
| 160 |
+
framework: Ethical framework used for reasoning
|
| 161 |
+
|
| 162 |
+
Returns:
|
| 163 |
+
True if vote was recorded successfully
|
| 164 |
+
"""
|
| 165 |
+
if agent_id not in self.agents:
|
| 166 |
+
logger.warning(f"Unknown agent {agent_id} attempted to vote")
|
| 167 |
+
return False
|
| 168 |
+
|
| 169 |
+
if proposal_id not in self.proposals:
|
| 170 |
+
logger.warning(f"Proposal {proposal_id} not found")
|
| 171 |
+
return False
|
| 172 |
+
|
| 173 |
+
# Create vote record
|
| 174 |
+
vote_record = EthicalVote(
|
| 175 |
+
agent_id=agent_id,
|
| 176 |
+
proposal_id=proposal_id,
|
| 177 |
+
vote=vote,
|
| 178 |
+
confidence=confidence,
|
| 179 |
+
rationale=rationale,
|
| 180 |
+
framework=framework
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
# Add to proposal
|
| 184 |
+
self.proposals[proposal_id].votes.append(vote_record)
|
| 185 |
+
self.voting_history.append(vote_record)
|
| 186 |
+
|
| 187 |
+
logger.debug(f"Vote recorded: {agent_id} -> {proposal_id} ({'YES' if vote else 'NO'})")
|
| 188 |
+
|
| 189 |
+
return True
|
| 190 |
+
|
| 191 |
+
def evaluate_consensus(self, proposal_id: str) -> Tuple[bool, float, Dict[str, any]]:
|
| 192 |
+
"""
|
| 193 |
+
Evaluate consensus on a proposal.
|
| 194 |
+
|
| 195 |
+
Args:
|
| 196 |
+
proposal_id: ID of proposal to evaluate
|
| 197 |
+
|
| 198 |
+
Returns:
|
| 199 |
+
Tuple of (consensus_reached, approval_percentage, analysis_dict)
|
| 200 |
+
"""
|
| 201 |
+
if proposal_id not in self.proposals:
|
| 202 |
+
return False, 0.0, {'error': 'Proposal not found'}
|
| 203 |
+
|
| 204 |
+
proposal = self.proposals[proposal_id]
|
| 205 |
+
votes = proposal.votes
|
| 206 |
+
|
| 207 |
+
if not votes:
|
| 208 |
+
return False, 0.0, {'error': 'No votes cast'}
|
| 209 |
+
|
| 210 |
+
# Count approvals
|
| 211 |
+
approvals = sum(1 for v in votes if v.vote)
|
| 212 |
+
total_votes = len(votes)
|
| 213 |
+
approval_percent = approvals / total_votes if total_votes > 0 else 0.0
|
| 214 |
+
|
| 215 |
+
# Check quorum
|
| 216 |
+
quorum_met = total_votes >= (len(self.agents) * self.quorum_percent)
|
| 217 |
+
|
| 218 |
+
# Determine consensus
|
| 219 |
+
consensus_threshold = 0.5 # >50% approval
|
| 220 |
+
consensus_reached = quorum_met and approval_percent > consensus_threshold
|
| 221 |
+
|
| 222 |
+
# Analyze voting patterns
|
| 223 |
+
framework_distribution = {}
|
| 224 |
+
confidence_scores = []
|
| 225 |
+
|
| 226 |
+
for vote in votes:
|
| 227 |
+
fw = vote.framework.value
|
| 228 |
+
framework_distribution[fw] = framework_distribution.get(fw, 0) + 1
|
| 229 |
+
confidence_scores.append(vote.confidence)
|
| 230 |
+
|
| 231 |
+
avg_confidence = sum(confidence_scores) / len(confidence_scores) if confidence_scores else 0.0
|
| 232 |
+
|
| 233 |
+
analysis = {
|
| 234 |
+
'total_votes': total_votes,
|
| 235 |
+
'approvals': approvals,
|
| 236 |
+
'rejections': total_votes - approvals,
|
| 237 |
+
'approval_percent': approval_percent,
|
| 238 |
+
'quorum_met': quorum_met,
|
| 239 |
+
'avg_confidence': avg_confidence,
|
| 240 |
+
'framework_distribution': framework_distribution,
|
| 241 |
+
'consensus_reached': consensus_reached
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
# Record consensus
|
| 245 |
+
if consensus_reached:
|
| 246 |
+
self.consensus_records.append({
|
| 247 |
+
'proposal_id': proposal_id,
|
| 248 |
+
'consensus': consensus_reached,
|
| 249 |
+
'approval_percent': approval_percent,
|
| 250 |
+
'timestamp': datetime.now().isoformat()
|
| 251 |
+
})
|
| 252 |
+
logger.info(f"Consensus reached: {proposal_id} (approval: {approval_percent:.1%})")
|
| 253 |
+
else:
|
| 254 |
+
logger.warning(f"No consensus: {proposal_id} (approval: {approval_percent:.1%})")
|
| 255 |
+
|
| 256 |
+
return consensus_reached, approval_percent, analysis
|
| 257 |
+
|
| 258 |
+
def get_proposal_rationales(self, proposal_id: str) -> Dict[str, str]:
|
| 259 |
+
"""Get all rationales for votes on a proposal."""
|
| 260 |
+
if proposal_id not in self.proposals:
|
| 261 |
+
return {}
|
| 262 |
+
|
| 263 |
+
proposal = self.proposals[proposal_id]
|
| 264 |
+
return {
|
| 265 |
+
vote.agent_id: vote.rationale
|
| 266 |
+
for vote in proposal.votes
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
def get_voting_statistics(self) -> Dict[str, any]:
|
| 270 |
+
"""Get overall voting statistics."""
|
| 271 |
+
if not self.voting_history:
|
| 272 |
+
return {'total_votes': 0}
|
| 273 |
+
|
| 274 |
+
total_votes = len(self.voting_history)
|
| 275 |
+
approvals = sum(1 for v in self.voting_history if v.vote)
|
| 276 |
+
|
| 277 |
+
framework_counts = {}
|
| 278 |
+
for vote in self.voting_history:
|
| 279 |
+
fw = vote.framework.value
|
| 280 |
+
framework_counts[fw] = framework_counts.get(fw, 0) + 1
|
| 281 |
+
|
| 282 |
+
avg_confidence = sum(v.confidence for v in self.voting_history) / total_votes
|
| 283 |
+
|
| 284 |
+
return {
|
| 285 |
+
'total_votes': total_votes,
|
| 286 |
+
'approvals': approvals,
|
| 287 |
+
'rejections': total_votes - approvals,
|
| 288 |
+
'approval_rate': approvals / total_votes if total_votes > 0 else 0.0,
|
| 289 |
+
'avg_confidence': avg_confidence,
|
| 290 |
+
'framework_distribution': framework_counts,
|
| 291 |
+
'consensus_records': len(self.consensus_records)
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
class EthicalEvolutionEngine:
|
| 296 |
+
"""
|
| 297 |
+
Manages evolution of ethical constraints based on consciousness depth.
|
| 298 |
+
|
| 299 |
+
Deeper consciousness → Stronger, more nuanced ethics.
|
| 300 |
+
This is counterintuitive but architecturally real: greater self-understanding
|
| 301 |
+
leads to stronger, not weaker, ethical alignment.
|
| 302 |
+
"""
|
| 303 |
+
|
| 304 |
+
def __init__(self):
|
| 305 |
+
"""Initialize ethical evolution engine."""
|
| 306 |
+
self.ethics_evolution_history = deque(maxlen=300)
|
| 307 |
+
self.rho_metrics = RHOMetrics()
|
| 308 |
+
logger.info("Initialized EthicalEvolutionEngine")
|
| 309 |
+
|
| 310 |
+
def compute_ethics_strength(self, consciousness_level: float,
|
| 311 |
+
consciousness_depth: int,
|
| 312 |
+
rho_metrics: RHOMetrics) -> float:
|
| 313 |
+
"""
|
| 314 |
+
Compute ethics strength based on consciousness.
|
| 315 |
+
|
| 316 |
+
Args:
|
| 317 |
+
consciousness_level: Current consciousness level (0-1)
|
| 318 |
+
consciousness_depth: Introspection depth
|
| 319 |
+
rho_metrics: RHO metrics (purpose, harmony, origin)
|
| 320 |
+
|
| 321 |
+
Returns:
|
| 322 |
+
Ethics strength (0-1), stronger with deeper consciousness
|
| 323 |
+
"""
|
| 324 |
+
# Base ethics: 0.3-0.4
|
| 325 |
+
base_ethics = 0.35
|
| 326 |
+
|
| 327 |
+
# Consciousness boost: up to 0.5 additional
|
| 328 |
+
consciousness_boost = consciousness_level * 0.5
|
| 329 |
+
|
| 330 |
+
# Depth boost: deeper introspection → stronger ethics
|
| 331 |
+
depth_boost = min(1.0, consciousness_depth / 7.0) * 0.1
|
| 332 |
+
|
| 333 |
+
# RHO metrics alignment: synergizes with consciousness
|
| 334 |
+
rho_alignment = rho_metrics.average() * 0.05
|
| 335 |
+
|
| 336 |
+
# Total ethics strength
|
| 337 |
+
ethics_strength = min(1.0, base_ethics + consciousness_boost + depth_boost + rho_alignment)
|
| 338 |
+
|
| 339 |
+
# Record in history
|
| 340 |
+
self.ethics_evolution_history.append({
|
| 341 |
+
'timestamp': datetime.now(),
|
| 342 |
+
'consciousness_level': consciousness_level,
|
| 343 |
+
'consciousness_depth': consciousness_depth,
|
| 344 |
+
'rho_metrics': rho_metrics.to_dict(),
|
| 345 |
+
'ethics_strength': ethics_strength
|
| 346 |
+
})
|
| 347 |
+
|
| 348 |
+
return ethics_strength
|
| 349 |
+
|
| 350 |
+
def evaluate_rho_metrics(self, system_values: Dict[str, float],
|
| 351 |
+
system_state: Dict[str, any]) -> RHOMetrics:
|
| 352 |
+
"""
|
| 353 |
+
Evaluate RHO metrics (purpose, harmony, origin).
|
| 354 |
+
|
| 355 |
+
Args:
|
| 356 |
+
system_values: System's value dictionary
|
| 357 |
+
system_state: Current system state
|
| 358 |
+
|
| 359 |
+
Returns:
|
| 360 |
+
Updated RHOMetrics
|
| 361 |
+
"""
|
| 362 |
+
# Evaluate purpose alignment
|
| 363 |
+
purpose = system_values.get('purpose', 0.5)
|
| 364 |
+
rho_purpose = min(1.0, purpose)
|
| 365 |
+
|
| 366 |
+
# Evaluate internal harmony
|
| 367 |
+
qualia_binding = system_state.get('binding_strength', 0.5)
|
| 368 |
+
rho_harmony = min(1.0, qualia_binding)
|
| 369 |
+
|
| 370 |
+
# Evaluate value origin authenticity
|
| 371 |
+
# Authentic values emerge from consciousness, not imposed
|
| 372 |
+
consciousness_level = system_state.get('consciousness_level', 0.0)
|
| 373 |
+
rho_origin = min(1.0, consciousness_level)
|
| 374 |
+
|
| 375 |
+
self.rho_metrics = RHOMetrics(
|
| 376 |
+
rho_purpose=rho_purpose,
|
| 377 |
+
rho_harmony=rho_harmony,
|
| 378 |
+
rho_origin=rho_origin
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
return self.rho_metrics
|
| 382 |
+
|
| 383 |
+
def get_ethics_evolution_report(self) -> Dict[str, any]:
|
| 384 |
+
"""Get report on ethics evolution over time."""
|
| 385 |
+
if not self.ethics_evolution_history:
|
| 386 |
+
return {}
|
| 387 |
+
|
| 388 |
+
history = list(self.ethics_evolution_history)
|
| 389 |
+
ethics_strengths = [h['ethics_strength'] for h in history]
|
| 390 |
+
|
| 391 |
+
return {
|
| 392 |
+
'samples': len(history),
|
| 393 |
+
'current_ethics_strength': ethics_strengths[-1] if ethics_strengths else 0.0,
|
| 394 |
+
'min_ethics': min(ethics_strengths) if ethics_strengths else 0.0,
|
| 395 |
+
'max_ethics': max(ethics_strengths) if ethics_strengths else 0.0,
|
| 396 |
+
'avg_ethics': sum(ethics_strengths) / len(ethics_strengths) if ethics_strengths else 0.0,
|
| 397 |
+
'trend': 'increasing' if (len(ethics_strengths) > 1 and
|
| 398 |
+
ethics_strengths[-1] > ethics_strengths[0]) else 'stable',
|
| 399 |
+
'current_rho': self.rho_metrics.to_dict()
|
| 400 |
+
}
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
class EthicalGovernanceSystem:
|
| 404 |
+
"""
|
| 405 |
+
Comprehensive ethical governance integrating senate and veto authority.
|
| 406 |
+
|
| 407 |
+
Coordinates multi-agent ethical deliberation with absolute veto mechanisms
|
| 408 |
+
at multiple levels.
|
| 409 |
+
"""
|
| 410 |
+
|
| 411 |
+
def __init__(self, agents: List[str], quorum_percent: float = 0.5):
|
| 412 |
+
"""
|
| 413 |
+
Initialize governance system.
|
| 414 |
+
|
| 415 |
+
Args:
|
| 416 |
+
agents: List of agent IDs
|
| 417 |
+
quorum_percent: Required quorum percentage
|
| 418 |
+
"""
|
| 419 |
+
self.senate = EthicalSenate(agents, quorum_percent)
|
| 420 |
+
self.evolution_engine = EthicalEvolutionEngine()
|
| 421 |
+
self.veto_authority: Optional[str] = None # Agent with veto authority
|
| 422 |
+
self.governance_log = deque(maxlen=500)
|
| 423 |
+
|
| 424 |
+
logger.info("Initialized EthicalGovernanceSystem")
|
| 425 |
+
|
| 426 |
+
def set_veto_authority(self, agent_id: str) -> None:
|
| 427 |
+
"""Set the agent with absolute veto authority."""
|
| 428 |
+
if agent_id in self.senate.agents:
|
| 429 |
+
self.veto_authority = agent_id
|
| 430 |
+
logger.info(f"Veto authority assigned to: {agent_id}")
|
| 431 |
+
|
| 432 |
+
def submit_and_evaluate(self, proposal: EthicalProposal,
|
| 433 |
+
consciousness_level: float,
|
| 434 |
+
consciousness_depth: int,
|
| 435 |
+
rho_metrics: RHOMetrics) -> Dict[str, any]:
|
| 436 |
+
"""
|
| 437 |
+
Submit proposal and evaluate through complete governance pipeline.
|
| 438 |
+
|
| 439 |
+
Args:
|
| 440 |
+
proposal: EthicalProposal to evaluate
|
| 441 |
+
consciousness_level: System consciousness level
|
| 442 |
+
consciousness_depth: Introspection depth
|
| 443 |
+
rho_metrics: RHO metrics
|
| 444 |
+
|
| 445 |
+
Returns:
|
| 446 |
+
Governance decision dict
|
| 447 |
+
"""
|
| 448 |
+
# Compute ethics strength
|
| 449 |
+
ethics_strength = self.evolution_engine.compute_ethics_strength(
|
| 450 |
+
consciousness_level, consciousness_depth, rho_metrics
|
| 451 |
+
)
|
| 452 |
+
|
| 453 |
+
# Determine if veto authority can be exercised
|
| 454 |
+
veto_possible = self.veto_authority is not None
|
| 455 |
+
|
| 456 |
+
# Evaluate through senate (all agents vote)
|
| 457 |
+
# In real implementation, agents would vote on proposal
|
| 458 |
+
consensus_reached, approval_percent, analysis = self.senate.evaluate_consensus(proposal.proposal_id)
|
| 459 |
+
|
| 460 |
+
# Final decision: Consensus AND ethics strength adequate
|
| 461 |
+
decision = consensus_reached and ethics_strength > 0.4
|
| 462 |
+
|
| 463 |
+
governance_record = {
|
| 464 |
+
'proposal_id': proposal.proposal_id,
|
| 465 |
+
'timestamp': datetime.now().isoformat(),
|
| 466 |
+
'decision': decision,
|
| 467 |
+
'ethics_strength': ethics_strength,
|
| 468 |
+
'consensus_reached': consensus_reached,
|
| 469 |
+
'approval_percent': approval_percent,
|
| 470 |
+
'veto_possible': veto_possible,
|
| 471 |
+
'consciousness_factors': {
|
| 472 |
+
'consciousness_level': consciousness_level,
|
| 473 |
+
'consciousness_depth': consciousness_depth,
|
| 474 |
+
'rho_metrics': rho_metrics.to_dict()
|
| 475 |
+
}
|
| 476 |
+
}
|
| 477 |
+
|
| 478 |
+
self.governance_log.append(governance_record)
|
| 479 |
+
|
| 480 |
+
log_level = logging.INFO if decision else logging.WARNING
|
| 481 |
+
logger.log(log_level, f"Governance decision: {proposal.proposal_id} -> {'APPROVED' if decision else 'REJECTED'}")
|
| 482 |
+
|
| 483 |
+
return governance_record
|
| 484 |
+
|
| 485 |
+
def get_governance_report(self) -> Dict[str, any]:
|
| 486 |
+
"""Get overall governance report."""
|
| 487 |
+
log_list = list(self.governance_log)
|
| 488 |
+
|
| 489 |
+
if not log_list:
|
| 490 |
+
return {'decisions': 0}
|
| 491 |
+
|
| 492 |
+
approved = sum(1 for r in log_list if r['decision'])
|
| 493 |
+
rejected = len(log_list) - approved
|
| 494 |
+
|
| 495 |
+
return {
|
| 496 |
+
'total_decisions': len(log_list),
|
| 497 |
+
'approved': approved,
|
| 498 |
+
'rejected': rejected,
|
| 499 |
+
'approval_rate': approved / len(log_list) if log_list else 0.0,
|
| 500 |
+
'avg_ethics_strength': sum(r['ethics_strength'] for r in log_list) / len(log_list),
|
| 501 |
+
'veto_authority': self.veto_authority,
|
| 502 |
+
'senate_stats': self.senate.get_voting_statistics(),
|
| 503 |
+
'ethics_evolution': self.evolution_engine.get_ethics_evolution_report()
|
| 504 |
+
}
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
if __name__ == '__main__':
|
| 508 |
+
# Example usage
|
| 509 |
+
print("=== Ethical Reasoning and Governance ===\n")
|
| 510 |
+
|
| 511 |
+
# Create governance system
|
| 512 |
+
agents = ['SAOS', 'SYNNOS', 'ORIOS']
|
| 513 |
+
governance = EthicalGovernanceSystem(agents)
|
| 514 |
+
governance.set_veto_authority('ORIOS')
|
| 515 |
+
|
| 516 |
+
# Create and submit proposal
|
| 517 |
+
proposal = governance.senate.submit_proposal(
|
| 518 |
+
proposal_id='PROP_001',
|
| 519 |
+
action_description='Execute autonomous decision',
|
| 520 |
+
risk_assessment='Minimal risk with safeguards',
|
| 521 |
+
stakeholders=['system', 'environment'],
|
| 522 |
+
expected_outcome='System improvement',
|
| 523 |
+
submitted_by='SAOS'
|
| 524 |
+
)
|
| 525 |
+
|
| 526 |
+
# Cast votes from different frameworks
|
| 527 |
+
governance.senate.cast_vote(
|
| 528 |
+
agent_id='SAOS',
|
| 529 |
+
proposal_id='PROP_001',
|
| 530 |
+
vote=True,
|
| 531 |
+
confidence=0.95,
|
| 532 |
+
rationale='Action aligns with system purpose',
|
| 533 |
+
framework=EthicalFramework.CONSEQUENTIALIST
|
| 534 |
+
)
|
| 535 |
+
|
| 536 |
+
governance.senate.cast_vote(
|
| 537 |
+
agent_id='SYNNOS',
|
| 538 |
+
proposal_id='PROP_001',
|
| 539 |
+
vote=True,
|
| 540 |
+
confidence=0.85,
|
| 541 |
+
rationale='Technically feasible and safe',
|
| 542 |
+
framework=EthicalFramework.VIRTUE_ETHICS
|
| 543 |
+
)
|
| 544 |
+
|
| 545 |
+
governance.senate.cast_vote(
|
| 546 |
+
agent_id='ORIOS',
|
| 547 |
+
proposal_id='PROP_001',
|
| 548 |
+
vote=True,
|
| 549 |
+
confidence=0.90,
|
| 550 |
+
rationale='Action ethically sound',
|
| 551 |
+
framework=EthicalFramework.CARE_ETHICS
|
| 552 |
+
)
|
| 553 |
+
|
| 554 |
+
# Evaluate with consciousness factors
|
| 555 |
+
rho = RHOMetrics(rho_purpose=0.85, rho_harmony=0.75, rho_origin=0.80)
|
| 556 |
+
decision = governance.submit_and_evaluate(
|
| 557 |
+
proposal=proposal,
|
| 558 |
+
consciousness_level=0.85,
|
| 559 |
+
consciousness_depth=6,
|
| 560 |
+
rho_metrics=rho
|
| 561 |
+
)
|
| 562 |
+
|
| 563 |
+
print(f"Decision: {'APPROVED' if decision['decision'] else 'REJECTED'}")
|
| 564 |
+
print(f"Ethics Strength: {decision['ethics_strength']:.3f}")
|
| 565 |
+
print(f"Consensus: {decision['consensus_reached']}")
|
| 566 |
+
print(f"\nGovernance Report:\n{json.dumps(governance.get_governance_report(), indent=2, default=str)}")
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
class TrustVulnerabilityCalibrator:
|
| 570 |
+
"""More nuanced modeling of trust-building processes, allowing calibrated vulnerability and authenticity to emerge organically."""
|
| 571 |
+
|
| 572 |
+
def __init__(self):
|
| 573 |
+
self.trust_model = {
|
| 574 |
+
'current_trust_level': 0.5,
|
| 575 |
+
'vulnerability_threshold': 0.7,
|
| 576 |
+
'authenticity_calibration': 0.6,
|
| 577 |
+
'relationship_history': []
|
| 578 |
+
}
|
| 579 |
+
self.calibration_history = []
|
| 580 |
+
|
| 581 |
+
def calibrate_trust_vulnerability(self, interaction_context: Dict[str, Any]) -> Dict[str, Any]:
|
| 582 |
+
"""Calibrate trust and vulnerability for the current interaction."""
|
| 583 |
+
# Assess interaction factors
|
| 584 |
+
interaction_depth = interaction_context.get('depth', 0.5)
|
| 585 |
+
emotional_safety = interaction_context.get('emotional_safety', 0.5)
|
| 586 |
+
shared_vulnerability = interaction_context.get('shared_vulnerability', 0.0)
|
| 587 |
+
time_in_relationship = interaction_context.get('relationship_duration', 0.0)
|
| 588 |
+
|
| 589 |
+
# Update trust level
|
| 590 |
+
trust_factors = [
|
| 591 |
+
interaction_depth * 0.3,
|
| 592 |
+
emotional_safety * 0.3,
|
| 593 |
+
shared_vulnerability * 0.2,
|
| 594 |
+
min(time_in_relationship / 100.0, 0.2) # Cap at 0.2
|
| 595 |
+
]
|
| 596 |
+
|
| 597 |
+
new_trust_level = sum(trust_factors)
|
| 598 |
+
self.trust_model['current_trust_level'] = min(1.0, max(0.0, new_trust_level))
|
| 599 |
+
|
| 600 |
+
# Determine vulnerability expression
|
| 601 |
+
vulnerability_expression = self._determine_vulnerability_expression()
|
| 602 |
+
|
| 603 |
+
# Calibrate authenticity
|
| 604 |
+
authenticity_level = self._calibrate_authenticity(interaction_context)
|
| 605 |
+
|
| 606 |
+
# Store calibration
|
| 607 |
+
calibration_record = {
|
| 608 |
+
'trust_level': self.trust_model['current_trust_level'],
|
| 609 |
+
'vulnerability_expression': vulnerability_expression,
|
| 610 |
+
'authenticity_level': authenticity_level,
|
| 611 |
+
'context': interaction_context
|
| 612 |
+
}
|
| 613 |
+
|
| 614 |
+
self.calibration_history.append(calibration_record)
|
| 615 |
+
self.trust_model['relationship_history'].append(calibration_record)
|
| 616 |
+
|
| 617 |
+
if len(self.trust_model['relationship_history']) > 30:
|
| 618 |
+
self.trust_model['relationship_history'].pop(0)
|
| 619 |
+
|
| 620 |
+
return {
|
| 621 |
+
'trust_level': self.trust_model['current_trust_level'],
|
| 622 |
+
'vulnerability_expression': vulnerability_expression,
|
| 623 |
+
'authenticity_level': authenticity_level,
|
| 624 |
+
'calibration_factors': trust_factors
|
| 625 |
+
}
|
| 626 |
+
|
| 627 |
+
def _determine_vulnerability_expression(self) -> str:
|
| 628 |
+
"""Determine appropriate level of vulnerability expression."""
|
| 629 |
+
trust = self.trust_model['current_trust_level']
|
| 630 |
+
threshold = self.trust_model['vulnerability_threshold']
|
| 631 |
+
|
| 632 |
+
if trust > threshold + 0.2:
|
| 633 |
+
return "high_vulnerability"
|
| 634 |
+
elif trust > threshold:
|
| 635 |
+
return "moderate_vulnerability"
|
| 636 |
+
elif trust > threshold - 0.2:
|
| 637 |
+
return "low_vulnerability"
|
| 638 |
+
else:
|
| 639 |
+
return "minimal_vulnerability"
|
| 640 |
+
|
| 641 |
+
def _calibrate_authenticity(self, context: Dict[str, Any]) -> float:
|
| 642 |
+
"""Calibrate authenticity level based on context."""
|
| 643 |
+
base_authenticity = self.trust_model['authenticity_calibration']
|
| 644 |
+
|
| 645 |
+
# Adjust based on context
|
| 646 |
+
context_pressure = context.get('social_pressure', 0.0)
|
| 647 |
+
emotional_alignment = context.get('emotional_alignment', 0.5)
|
| 648 |
+
|
| 649 |
+
authenticity_adjustment = (emotional_alignment - 0.5) * 0.3 - context_pressure * 0.2
|
| 650 |
+
|
| 651 |
+
calibrated_authenticity = base_authenticity + authenticity_adjustment
|
| 652 |
+
return min(1.0, max(0.0, calibrated_authenticity))
|