Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /dislovelhl_enhanced-agent-bus /constitutional /refoundation.py
| """ | |
| ACGS-2 Constitutional Refoundation System | |
| Constitutional Hash: 608508a9bd224290 | |
| The ONLY mechanism for changing HARD or META invariants. A refoundation | |
| creates a new constitutional epoch — not just a version bump. | |
| Requirements (all must be met): | |
| 1. Cannot be auto-generated by DTMC/SDPC (human-initiated only) | |
| 2. Requires approval from ALL constitutional roles (LEGISLATIVE + EXECUTIVE + JUDICIAL) | |
| 3. Must include sandbox execution results showing no degradation | |
| 4. Creates a new epoch with new invariant_hash | |
| 5. Old epoch's invariant history is preserved (append-only) | |
| """ | |
| from __future__ import annotations | |
| from datetime import UTC, datetime | |
| from enum import StrEnum | |
| from uuid import uuid4 | |
| from pydantic import BaseModel, Field | |
| from enhanced_agent_bus.observability.structured_logging import get_logger | |
| from .invariants import InvariantManifest | |
| logger = get_logger(__name__) | |
| __all__ = [ | |
| "ConstitutionalEpoch", | |
| "RefoundationApproval", | |
| "RefoundationEngine", | |
| "RefoundationError", | |
| "RefoundationProposal", | |
| "RefoundationStatus", | |
| "SandboxExecutionResult", | |
| ] | |
| _CONSTITUTIONAL_HASH = "608508a9bd224290" | |
| _VALID_ROLES = frozenset({"legislative", "executive", "judicial"}) | |
| _MIN_JUSTIFICATION_LENGTH = 50 | |
| # --------------------------------------------------------------------------- | |
| # Enums | |
| # --------------------------------------------------------------------------- | |
| class RefoundationStatus(StrEnum): | |
| """Lifecycle status of a refoundation proposal.""" | |
| DRAFTED = "drafted" | |
| SUBMITTED = "submitted" | |
| UNDER_REVIEW = "under_review" | |
| SANDBOX_TESTING = "sandbox_testing" | |
| APPROVED = "approved" | |
| ACTIVATED = "activated" | |
| REJECTED = "rejected" | |
| ROLLED_BACK = "rolled_back" | |
| # --------------------------------------------------------------------------- | |
| # Data models | |
| # --------------------------------------------------------------------------- | |
| class RefoundationApproval(BaseModel): | |
| """Approval from one MACI role for a refoundation.""" | |
| role: str | |
| approver_id: str | |
| approved: bool | |
| reasoning: str | |
| approved_at: datetime = Field(default_factory=lambda: datetime.now(UTC)) | |
| class SandboxExecutionResult(BaseModel): | |
| """Results from running the new invariant manifest in sandbox.""" | |
| sandbox_id: str | |
| passed: bool | |
| governance_metrics_before: dict[str, float] = Field(default_factory=dict) | |
| governance_metrics_after: dict[str, float] = Field(default_factory=dict) | |
| degradation_detected: bool = False | |
| test_duration_seconds: float = 0.0 | |
| error_details: str | None = None | |
| class ConstitutionalEpoch(BaseModel): | |
| """Represents a constitutional epoch — a complete invariant regime. | |
| Each refoundation creates a new epoch. Epochs are append-only. | |
| """ | |
| epoch_id: str = Field(default_factory=lambda: str(uuid4())) | |
| epoch_number: int | |
| invariant_manifest: InvariantManifest | |
| predecessor_epoch_id: str | None = None | |
| created_at: datetime = Field(default_factory=lambda: datetime.now(UTC)) | |
| created_by: str | |
| reason: str | |
| class RefoundationProposal(BaseModel): | |
| """Proposal to change HARD or META invariants. | |
| Much stricter than AmendmentProposal: | |
| - Requires unanimous approval from all MACI roles | |
| - Must include sandbox results | |
| - Cannot be auto-generated | |
| - Creates a new constitutional epoch | |
| """ | |
| proposal_id: str = Field(default_factory=lambda: str(uuid4())) | |
| status: RefoundationStatus = RefoundationStatus.DRAFTED | |
| # What's changing | |
| current_epoch_id: str | |
| proposed_invariant_changes: dict[str, str] = Field(default_factory=dict) | |
| proposed_manifest: InvariantManifest | |
| # Why | |
| justification: str | |
| risk_assessment: str | |
| rollback_plan: str | |
| # Who | |
| proposer_id: str | |
| proposer_role: str = "human_operator" | |
| # Approvals (all three required) | |
| legislative_approval: RefoundationApproval | None = None | |
| executive_approval: RefoundationApproval | None = None | |
| judicial_approval: RefoundationApproval | None = None | |
| # Sandbox | |
| sandbox_results: SandboxExecutionResult | None = None | |
| # Timestamps | |
| created_at: datetime = Field(default_factory=lambda: datetime.now(UTC)) | |
| submitted_at: datetime | None = None | |
| approved_at: datetime | None = None | |
| activated_at: datetime | None = None | |
| # Epoch transition | |
| new_epoch_id: str | None = None | |
| # --------------------------------------------------------------------------- | |
| # Exception | |
| # --------------------------------------------------------------------------- | |
| class RefoundationError(Exception): | |
| """Raised when refoundation rules are violated.""" | |
| # --------------------------------------------------------------------------- | |
| # Engine | |
| # --------------------------------------------------------------------------- | |
| class RefoundationEngine: | |
| """Manages the refoundation lifecycle. | |
| Enforces: | |
| - Only humans can propose (proposer_role must be "human_operator") | |
| - All three MACI roles must approve | |
| - Sandbox must pass before activation | |
| - New epoch created on activation with new invariant_hash | |
| - Old epoch preserved in history (append-only) | |
| Constitutional Hash: 608508a9bd224290 | |
| """ | |
| def __init__(self) -> None: | |
| self._proposals: dict[str, RefoundationProposal] = {} | |
| self._epochs: list[ConstitutionalEpoch] = [] | |
| self._current_epoch: ConstitutionalEpoch | None = None | |
| def create_proposal( | |
| self, | |
| proposer_id: str, | |
| proposer_role: str, | |
| current_epoch_id: str, | |
| proposed_invariant_changes: dict[str, str], | |
| proposed_manifest: InvariantManifest, | |
| justification: str, | |
| risk_assessment: str, | |
| rollback_plan: str, | |
| ) -> RefoundationProposal: | |
| """Create a refoundation proposal. Raises if proposer is not human.""" | |
| if proposer_role != "human_operator": | |
| raise RefoundationError("Only human operators can propose refoundations") | |
| if len(justification) < _MIN_JUSTIFICATION_LENGTH: | |
| raise RefoundationError( | |
| f"Refoundation justification must be at least " | |
| f"{_MIN_JUSTIFICATION_LENGTH} characters" | |
| ) | |
| proposal = RefoundationProposal( | |
| proposer_id=proposer_id, | |
| proposer_role=proposer_role, | |
| current_epoch_id=current_epoch_id, | |
| proposed_invariant_changes=proposed_invariant_changes, | |
| proposed_manifest=proposed_manifest, | |
| justification=justification, | |
| risk_assessment=risk_assessment, | |
| rollback_plan=rollback_plan, | |
| ) | |
| self._proposals[proposal.proposal_id] = proposal | |
| logger.info( | |
| "refoundation_proposal_created", | |
| constitutional_hash=_CONSTITUTIONAL_HASH, | |
| proposal_id=proposal.proposal_id, | |
| proposer_id=proposer_id, | |
| ) | |
| return proposal | |
| def submit_for_review(self, proposal_id: str) -> RefoundationProposal: | |
| """Submit a drafted proposal for multi-role review.""" | |
| proposal = self._get_proposal(proposal_id) | |
| if proposal.status != RefoundationStatus.DRAFTED: | |
| raise RefoundationError( | |
| f"Can only submit proposals in DRAFTED status (current: {proposal.status})" | |
| ) | |
| updated = proposal.model_copy( | |
| update={ | |
| "status": RefoundationStatus.SUBMITTED, | |
| "submitted_at": datetime.now(UTC), | |
| } | |
| ) | |
| self._proposals[proposal_id] = updated | |
| logger.info( | |
| "refoundation_submitted", | |
| constitutional_hash=_CONSTITUTIONAL_HASH, | |
| proposal_id=proposal_id, | |
| ) | |
| return updated | |
| def add_approval( | |
| self, | |
| proposal_id: str, | |
| role: str, | |
| approver_id: str, | |
| approved: bool, | |
| reasoning: str, | |
| ) -> RefoundationProposal: | |
| """Add approval from one MACI role. | |
| Enforces: | |
| - Role must be one of: legislative, executive, judicial | |
| - Approver cannot approve their own proposal (MACI separation) | |
| - Each role can only approve once | |
| """ | |
| proposal = self._get_proposal(proposal_id) | |
| if proposal.status not in { | |
| RefoundationStatus.SUBMITTED, | |
| RefoundationStatus.UNDER_REVIEW, | |
| }: | |
| raise RefoundationError( | |
| f"Can only add approvals when status is SUBMITTED or " | |
| f"UNDER_REVIEW (current: {proposal.status})" | |
| ) | |
| if role not in _VALID_ROLES: | |
| raise RefoundationError( | |
| f"Invalid role '{role}'. Must be one of: {', '.join(sorted(_VALID_ROLES))}" | |
| ) | |
| if approver_id == proposal.proposer_id: | |
| raise RefoundationError( | |
| "MACI separation: proposer cannot approve their own refoundation proposal" | |
| ) | |
| approval_field = f"{role}_approval" | |
| existing = getattr(proposal, approval_field) | |
| if existing is not None: | |
| raise RefoundationError( | |
| f"Role '{role}' has already provided approval for this proposal" | |
| ) | |
| approval = RefoundationApproval( | |
| role=role, | |
| approver_id=approver_id, | |
| approved=approved, | |
| reasoning=reasoning, | |
| ) | |
| update: dict[str, object] = { | |
| approval_field: approval, | |
| "status": RefoundationStatus.UNDER_REVIEW, | |
| } | |
| if not approved: | |
| update["status"] = RefoundationStatus.REJECTED | |
| updated = proposal.model_copy(update=update) | |
| # Check if all three roles have approved (and none rejected) | |
| if ( | |
| updated.status != RefoundationStatus.REJECTED | |
| and updated.legislative_approval is not None | |
| and updated.executive_approval is not None | |
| and updated.judicial_approval is not None | |
| and updated.legislative_approval.approved | |
| and updated.executive_approval.approved | |
| and updated.judicial_approval.approved | |
| ): | |
| if updated.sandbox_results is not None and updated.sandbox_results.passed: | |
| updated = updated.model_copy( | |
| update={ | |
| "status": RefoundationStatus.APPROVED, | |
| "approved_at": datetime.now(UTC), | |
| } | |
| ) | |
| else: | |
| updated = updated.model_copy(update={"status": RefoundationStatus.SANDBOX_TESTING}) | |
| self._proposals[proposal_id] = updated | |
| logger.info( | |
| "refoundation_approval_recorded", | |
| constitutional_hash=_CONSTITUTIONAL_HASH, | |
| proposal_id=proposal_id, | |
| role=role, | |
| approved=approved, | |
| ) | |
| return updated | |
| def record_sandbox_results( | |
| self, | |
| proposal_id: str, | |
| results: SandboxExecutionResult, | |
| ) -> RefoundationProposal: | |
| """Record sandbox execution results. Must pass before activation.""" | |
| proposal = self._get_proposal(proposal_id) | |
| if proposal.status not in { | |
| RefoundationStatus.UNDER_REVIEW, | |
| RefoundationStatus.SANDBOX_TESTING, | |
| }: | |
| raise RefoundationError( | |
| f"Can only record sandbox results when status is " | |
| f"UNDER_REVIEW or SANDBOX_TESTING (current: {proposal.status})" | |
| ) | |
| update: dict[str, object] = {"sandbox_results": results} | |
| # If all approvals are in and sandbox passed, move to APPROVED | |
| all_approved = ( | |
| proposal.legislative_approval is not None | |
| and proposal.executive_approval is not None | |
| and proposal.judicial_approval is not None | |
| and proposal.legislative_approval.approved | |
| and proposal.executive_approval.approved | |
| and proposal.judicial_approval.approved | |
| ) | |
| if all_approved and results.passed and not results.degradation_detected: | |
| update["status"] = RefoundationStatus.APPROVED | |
| update["approved_at"] = datetime.now(UTC) | |
| elif not results.passed or results.degradation_detected: | |
| update["status"] = RefoundationStatus.REJECTED | |
| updated = proposal.model_copy(update=update) | |
| self._proposals[proposal_id] = updated | |
| logger.info( | |
| "refoundation_sandbox_recorded", | |
| constitutional_hash=_CONSTITUTIONAL_HASH, | |
| proposal_id=proposal_id, | |
| passed=results.passed, | |
| degradation=results.degradation_detected, | |
| ) | |
| return updated | |
| def activate(self, proposal_id: str) -> ConstitutionalEpoch: | |
| """Activate a fully-approved refoundation. | |
| Requirements (all must be met): | |
| 1. All three roles approved (legislative + executive + judicial) | |
| 2. Sandbox passed (no degradation) | |
| 3. Status is APPROVED | |
| On activation: | |
| - Creates new ConstitutionalEpoch | |
| - Sets new_epoch_id on proposal | |
| - Appends to epoch history | |
| - Returns the new epoch | |
| """ | |
| proposal = self._get_proposal(proposal_id) | |
| if proposal.status != RefoundationStatus.APPROVED: | |
| raise RefoundationError( | |
| f"Can only activate proposals in APPROVED status (current: {proposal.status})" | |
| ) | |
| # Double-check all approvals (defense in depth) | |
| if ( | |
| proposal.legislative_approval is None | |
| or proposal.executive_approval is None | |
| or proposal.judicial_approval is None | |
| ): | |
| raise RefoundationError("All three MACI roles must approve before activation") | |
| if not all( | |
| a.approved | |
| for a in [ | |
| proposal.legislative_approval, | |
| proposal.executive_approval, | |
| proposal.judicial_approval, | |
| ] | |
| ): | |
| raise RefoundationError( | |
| "All three MACI roles must approve (not reject) before activation" | |
| ) | |
| # Double-check sandbox (defense in depth) | |
| if proposal.sandbox_results is None: | |
| raise RefoundationError("Sandbox execution results required before activation") | |
| if not proposal.sandbox_results.passed: | |
| raise RefoundationError("Sandbox execution must pass before activation") | |
| if proposal.sandbox_results.degradation_detected: | |
| raise RefoundationError("Cannot activate: sandbox detected governance degradation") | |
| # Create new epoch | |
| predecessor_id = self._current_epoch.epoch_id if self._current_epoch else None | |
| epoch_number = self._current_epoch.epoch_number + 1 if self._current_epoch else 1 | |
| new_epoch = ConstitutionalEpoch( | |
| epoch_number=epoch_number, | |
| invariant_manifest=proposal.proposed_manifest, | |
| predecessor_epoch_id=predecessor_id, | |
| created_by=proposal.proposer_id, | |
| reason=proposal.justification, | |
| ) | |
| # Update proposal | |
| updated = proposal.model_copy( | |
| update={ | |
| "status": RefoundationStatus.ACTIVATED, | |
| "activated_at": datetime.now(UTC), | |
| "new_epoch_id": new_epoch.epoch_id, | |
| } | |
| ) | |
| self._proposals[proposal_id] = updated | |
| # Append to epoch history (append-only) | |
| self._epochs.append(new_epoch) | |
| self._current_epoch = new_epoch | |
| logger.info( | |
| "refoundation_activated", | |
| constitutional_hash=_CONSTITUTIONAL_HASH, | |
| proposal_id=proposal_id, | |
| new_epoch_id=new_epoch.epoch_id, | |
| epoch_number=new_epoch.epoch_number, | |
| invariant_hash=new_epoch.invariant_manifest.invariant_hash, | |
| ) | |
| return new_epoch | |
| def get_current_epoch(self) -> ConstitutionalEpoch | None: | |
| """Return the current active epoch.""" | |
| return self._current_epoch | |
| def get_epoch_history(self) -> list[ConstitutionalEpoch]: | |
| """Return all epochs (append-only history). Returns a copy.""" | |
| return list(self._epochs) | |
| def get_proposal(self, proposal_id: str) -> RefoundationProposal | None: | |
| """Return a proposal by ID, or None if not found.""" | |
| return self._proposals.get(proposal_id) | |
| def _get_proposal(self, proposal_id: str) -> RefoundationProposal: | |
| """Return a proposal by ID, raising if not found.""" | |
| proposal = self._proposals.get(proposal_id) | |
| if proposal is None: | |
| raise RefoundationError(f"Refoundation proposal '{proposal_id}' not found") | |
| return proposal | |
Xet Storage Details
- Size:
- 16.7 kB
- Xet hash:
- ebe482bc95a6fc7c602c9ddce9ef0fa8dbb5f1f7a0f475a0dbd55467931862c2
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.