Skill: schchit/coe-consensus (version 1.0.0)

--- name: coe-consensus version: 1.0.0 description: COE Consensus Engine — Cross-Model Consensus Skill for Shared World State Formation author: Cognitive Emergence Lab <[REDACTED_SECRET]> license: MIT protocol: COE tags: - coe - consensus - jep - swarm - multi-agent - world-model - bft entrypoint: skill.api:app host_targets: - mcp - api - python skills: - name: run_consensus description: Collect J/V events from heterogeneous agents and produce a verifiable Shared World State via configurable consensus policy input_schema: type: object properties: session_id: type: string description: Unique session identifier target: type: string description: Target world model or scene ID to filter events policy: type: string enum: - simple_majority - weighted_trust - bft description: Consensus policy to apply events: type: array description: List of COE events (J, D, T, V primitives) items: type: object properties: event_id: type: string primitive: type: string enum: - J - D - T - V issuer: type: string timestamp: type: string target: type: string assertion: type: object verify_of: type: array items: type: string verification_result: type: string enum: - confirmed - rejected - partial confidence: type: number terminate_of: type: string trust_weights: type: object description: Issuer-to-weight mapping for weighted_trust policy bft_fault_tolerance: type: integer description: Fault tolerance parameter f for BFT policy weighted_threshold: type: number description: Confirmation threshold for weighted_trust policy required: - session_id - policy - events output_schema: type: object properties: session_id: type: string resolved: type: boolean description: Whether consensus was reached for all active assertions policy: type: string sws: type: object description: Shared World State record when resolved properties: sws_id: type: string target: type: string timestamp: type: string assertions: type: array items: type: object previous_sws_id: type: string conflicts: type: array description: Unresolved conflicts requiring additional evidence or verifications items: type: object message: type: string events_processed: type: integer events_by_issuer: type: object --- # COE Consensus Skill **Cross-Model Consensus Engine** Algorithm implementation based on the **COE (Cognition-Oriented Emergence)** Protocol (Wang, 2026). ## Core Problem When multiple agents (humans, AI models, robots) observe the same physical space, how do they reach a verifiable consensus on "what the world is"? ## Consensus Policies | Policy | Use Case | Rule | |--------|----------|------| | **Simple Majority** | Small equal-trust groups | Confirmations exceed 50% of all verifications received | | **Weighted Trust** | Heterogeneous agents with different reliability | Sum of (trust_weight * confidence) exceeds threshold | | **BFT** | High-security with potential malicious agents | More than f+1 confirmations out of at least 2f+1 total verifications | ## Shared World State (SWS) Whenever consensus is reached, the engine produces an SWS record containing: - `subject` / `predicate` / `value` — the agreed-upon fact - `confidence` — aggregated confidence score - `based_on` — event IDs of the underlying J/V events - `consensus_policy` — policy used to reach agreement - `confirmations` — number of confirming verifications ## Usage Example ### Request ```json { "session_id": "warehouse-001", "target": "warehouse-zone-3", "policy": "weighted_trust", "events": [ { "event_id": "evt-1", "primitive": "J", "issuer": "robot-A", "timestamp": "2026-04-19T10:30:00Z", "target": "warehouse-zone-3", "assertion": {"subject": "door_01", "predicate": "status", "value": "open"}, "confidence": 0.95 }, { "event_id": "evt-2", "primitive": "V", "issuer": "robot-B", "timestamp": "2026-04-19T10:30:05Z", "target": "warehouse-zone-3", "verify_of": ["evt-1"], "verification_result": "confirmed", "confidence": 0.9 } ], "trust_weights": {"robot-A": 0.9, "robot-B": 0.8}, "weighted_threshold": 1.5 } ``` ### Response ```json { "session_id": "warehouse-001", "resolved": true, "policy": "weighted_trust", "sws": { "sws_id": "...", "target": "warehouse-zone-3", "timestamp": "2026-04-19T10:30:05Z", "assertions": [ { "subject": "door_01", "predicate": "status", "value": "open", "confidence": 1.0, "based_on": ["evt-1"], "consensus_policy": "weighted_trust", "confirmations": 1 } ] }, "conflicts": [], "message": "Consensus complete. 1 assertions resolved, 0 conflicts remain.", "events_processed": 2, "events_by_issuer": {"robot-A": 1, "robot-B": 1} } ``` ## Relationship with JEP - **COE** answers "what the world is" — cognitive consensus, ex-ante / in-situ collaboration. - **JEP** answers "who is responsible" — accountability tracing, post-hoc audit. - COE events may be referenced by JEP as evidence. Together they form a complete cognition-accountability dual-loop. --- Cognitive Emergence Lab [REDACTED_SECRET]

path: coe-consensus-skill/CHANGELOG.md
content: # Changelog

All notable changes to the COE Consensus Skill will be documented in this file.

## [1.0.0] - 2026-04-26

### Added
- Initial release of the COE Consensus Skill.
- Implemented three consensus policies from COE Protocol Section 4.2:
  - Simple Majority: confirmations exceed 50% threshold.
  - Weighted Trust: weighted confirmation score exceeds configurable threshold.
  - Byzantine Fault Tolerance (BFT): lightweight BFT variant requiring >f+1 confirmations out of >=2f+1 total.
- Core engine supporting J (Judge), V (Verify), and T (Terminate) event processing.
- Conflict detection for contradictory assertions on the same subject-predicate pair.
- Shared World State (SWS) generation with full provenance and consensus policy annotation.
- Termination handling: T events invalidate prior J assertions before re-consensus.
- FastAPI HTTP interface (`/consensus`, `/health`) compatible with MCP Skill calling conventions.
- Full protocol reproduction example (Appendix A robot collaboration) in `examples/robot_consensus.py`.
- Unit tests covering simple majority, weighted trust, BFT, termination, and unresolved scenarios.
- Standard Clawhub `SKILL.md` manifest with YAML frontmatter and JSON schemas.

### Features
- **Neutral Consensus Layer**: Heterogeneous world models (JEPA, Dreamer, GPT, Claude, local models) emit COE events via adapters; consensus engine produces a unified SWS.
- **Policy-Pluggable**: Consensus policy configurable per session without code changes.
- **Audit-Ready**: All SWS records carry `based_on` event provenance for downstream JEP accountability tracing.

### References
- Wang, Y. (2026). *COE: Cognition-Oriented Emergence*. IETF Internet-Draft.
- Wang, Y. (2026). *JEP: Judgment Event Protocol*. IETF Internet-Draft.
- Wang, Y. (2026). *Target Determinability under Partial Causal Observation*. Cognitive Emergence Lab.


path: coe-consensus-skill/manifest.json
content: {
  "name": "coe-consensus",
  "version": "1.0.0",
  "description": "COE Consensus Engine — Cross-Model Consensus Skill for Shared World State Formation",
  "author": "Cognitive Emergence Lab <[REDACTED_SECRET]>",
  "license": "MIT",
  "protocol": "COE",
  "entrypoint": "skill.api:app",
  "host_targets": [
    "mcp",
    "api",
    "python"
  ],
  "dependencies": [
    "fastapi>=0.104.0",
    "uvicorn>=0.24.0",
    "pydantic>=2.5.0"
  ],
  "tags": [
    "coe",
    "consensus",
    "jep",
    "swarm",
    "multi-agent",
    "world-model",
    "bft"
  ]
}

path: coe-consensus-skill/README.md
content: # COE Consensus Skill v1.0.0

**Cross-Model Consensus Engine** for Shared World State Formation.

Based on the **COE (Cognition-Oriented Emergence)** Protocol (Wang, 2026).

> **Core Problem:** When multiple agents (humans, AI models, robots) observe the same physical space, how do they reach a verifiable consensus on "what the world is"?

---

## What It Does

| Policy | Use Case | Rule |
|--------|----------|------|
| **Simple Majority** | Small equal-trust groups | >50% of verifications confirm |
| **Weighted Trust** | Heterogeneous agents with different reliability | Sum of (trust_weight * confidence) > threshold |
| **BFT** | High-security with potential malicious agents | >f+1 confirmations out of >=2f+1 total verifications |

## Core Capabilities

1. **Event Collection** — Ingest J (Judge) and V (Verify) events from any Cognitive Unit.
2. **Conflict Resolution** — Detect contradictory assertions on the same subject and resolve via policy.
3. **Termination Handling** — Process T (Terminate) events to invalidate outdated assertions before re-consensus.
4. **Shared World State (SWS)** — Output a tamper-evident consensus record with full provenance.

## Quick Start

```bash
pip install -r requirements.txt
uvicorn skill.api:app --host 0.0.0.0 --port 8000
```

## API Call

```bash
curl -X POST http://localhost:8000/consensus \
  -H "Content-Type: application/json" \
  -d '{
    "session_id": "warehouse-001",
    "target": "warehouse-zone-3",
    "policy": "weighted_trust",
    "events": [
      {
        "event_id": "evt-1",
        "primitive": "J",
        "issuer": "robot-A",
        "timestamp": "2026-04-19T10:30:00Z",
        "target": "warehouse-zone-3",
        "assertion": {"subject": "door_01", "predicate": "status", "value": "open"},
        "confidence": 0.95
      },
      {
        "event_id": "evt-2",
        "primitive": "V",
        "issuer": "robot-B",
        "timestamp": "2026-04-19T10:30:05Z",
        "target": "warehouse-zone-3",
        "verify_of": ["evt-1"],
        "verification_result": "confirmed",
        "confidence": 0.9
      },
      {
        "event_id": "evt-3",
        "primitive": "V",
        "issuer": "human-1",
        "timestamp": "2026-04-19T10:30:10Z",
        "target": "warehouse-zone-3",
        "verify_of": ["evt-1"],
        "verification_result": "confirmed",
        "confidence": 1.0
      }
    ],
    "trust_weights": {"robot-A": 0.9, "robot-B": 0.8, "human-1": 1.0},
    "weighted_threshold": 1.5
  }'
```

## Protocol Reproduction

```bash
cd examples
python robot_consensus.py
```

Reproduces COE Protocol Appendix A verification workflow:
- Scenario 1: Simple Majority — 3 robots confirm door=open
- Scenario 2: Weighted Trust — robots + human supervisor confirm door=closed
- Scenario 3: BFT — 4 robots tolerate 1 Byzantine fault
- Scenario 4: Termination + Re-consensus — old state terminated, new state agreed

## Relationship with JEP

- **COE** answers "what the world is" — cognitive consensus, ex-ante / in-situ collaboration.
- **JEP** answers "who is responsible" — accountability tracing, post-hoc audit.
- COE events may be referenced by JEP as evidence. Together they form a complete cognition-accountability dual-loop.

---

Cognitive Emergence Lab  
Email: [REDACTED_SECRET]


path: coe-consensus-skill/requirements.txt
content: fastapi>=0.104.0
uvicorn>=0.24.0
pydantic>=2.5.0


path: coe-consensus-skill/tests/test_core.py
content: """
Core Consensus Engine Unit Tests
Run: pytest tests/test_core.py
"""
import sys
sys.path.insert(0, "..")

from skill.core import ConsensusEngine
from skill.types import COEEvent, Primitive, VerificationResult, ConsensusPolicy
from datetime import datetime


def test_simple_majority_consensus():
    """Three confirmations out of three -> resolved."""
    engine = ConsensusEngine(policy=ConsensusPolicy.SIMPLE_MAJORITY)

    j = COEEvent("j1", Primitive.JUDGE, "A", datetime.now(), "t1",
                 assertion={"subject": "door", "predicate": "status", "value": "open"}, confidence=0.9)
    v1 = COEEvent("v1", Primitive.VERIFY, "B", datetime.now(), "t1",
                  verify_of=["j1"], verification_result=VerificationResult.CONFIRMED, confidence=0.9)
    v2 = COEEvent("v2", Primitive.VERIFY, "C", datetime.now(), "t1",
                  verify_of=["j1"], verification_result=VerificationResult.CONFIRMED, confidence=0.8)
    v3 = COEEvent("v3", Primitive.VERIFY, "D", datetime.now(), "t1",
                  verify_of=["j1"], verification_result=VerificationResult.CONFIRMED, confidence=0.85)

    for e in [j, v1, v2, v3]:
        engine.add_event(e)

    result = engine.run(target="t1")
    assert result.resolved is True
    assert result.sws is not None
    assert result.sws.assertions[0]["value"] == "open"
    assert result.sws.assertions[0]["confirmations"] == 3


def test_weighted_trust_consensus():
    """Weighted trust exceeds threshold -> resolved."""
    engine = ConsensusEngine(policy=ConsensusPolicy.WEIGHTED_TRUST)
    engine.set_weighted_threshold(1.5)
    engine.set_trust_weight("B", 0.8)
    engine.set_trust_weight("C", 1.0)

    j = COEEvent("j2", Primitive.JUDGE, "A", datetime.now(), "t2",
                 assertion={"subject": "door", "predicate": "status", "value": "closed"}, confidence=0.95)
    v1 = COEEvent("v4", Primitive.VERIFY, "B", datetime.now(), "t2",
                  verify_of=["j2"], verification_result=VerificationResult.CONFIRMED, confidence=0.9)
    v2 = COEEvent("v5", Primitive.VERIFY, "C", datetime.now(), "t2",
                  verify_of=["j2"], verification_result=VerificationResult.CONFIRMED, confidence=1.0)

    for e in [j, v1, v2]:
        engine.add_event(e)

    result = engine.run(target="t2")
    assert result.resolved is True
    assert result.sws is not None
    assert result.sws.assertions[0]["value"] == "closed"


def test_bft_consensus():
    """BFT with f=1 requires >2 confirmations (f+1=2) out of >=3 total (2f+1=3)."""
    engine = ConsensusEngine(policy=ConsensusPolicy.BFT)
    engine.set_bft_params(1)

    j = COEEvent("j3", Primitive.JUDGE, "A", datetime.now(), "t3",
                 assertion={"subject": "door", "predicate": "status", "value": "open"}, confidence=0.9)
    v1 = COEEvent("v6", Primitive.VERIFY, "B", datetime.now(), "t3",
                  verify_of=["j3"], verification_result=VerificationResult.CONFIRMED, confidence=0.9)
    v2 = COEEvent("v7", Primitive.VERIFY, "C", datetime.now(), "t3",
                  verify_of=["j3"], verification_result=VerificationResult.CONFIRMED, confidence=0.8)
    v3 = COEEvent("v8", Primitive.VERIFY, "D", datetime.now(), "t3",
                  verify_of=["j3"], verification_result=VerificationResult.CONFIRMED, confidence=0.85)

    for e in [j, v1, v2, v3]:
        engine.add_event(e)

    result = engine.run(target="t3")
    assert result.resolved is True
    assert result.sws is not None


def test_termination_invalidates_old():
    """Terminate event removes old assertion from consensus."""
    engine = ConsensusEngine(policy=ConsensusPolicy.SIMPLE_MAJORITY)

    j = COEEvent("j4", Primitive.JUDGE, "A", datetime.now(), "t4",
                 assertion={"subject": "door", "predicate": "status", "value": "open"}, confidence=0.9)
    t = COEEvent("t1", Primitive.TERMINATE, "A", datetime.now(), "t4", terminate_of="j4")
    j2 = COEEvent("j5", Primitive.JUDGE, "A", datetime.now(), "t4",
                  assertion={"subject": "door", "predicate": "status", "value": "closed"}, confidence=0.9)
    v = COEEvent("v9", Primitive.VERIFY, "B", datetime.now(), "t4",
                 verify_of=["j5"], verification_result=VerificationResult.CONFIRMED, confidence=0.9)
    v2 = COEEvent("v10", Primitive.VERIFY, "C", datetime.now(), "t4",
                  verify_of=["j5"], verification_result=VerificationResult.CONFIRMED, confidence=0.8)

    for e in [j, t, j2, v, v2]:
        engine.add_event(e)

    result = engine.run(target="t4")
    assert result.resolved is True
    assert result.sws is not None
    assert result.sws.assertions[0]["value"] == "closed"


def test_unresolved_insufficient_verifications():
    """Only one verification -> unresolved under simple majority."""
    engine = ConsensusEngine(policy=ConsensusPolicy.SIMPLE_MAJORITY)

    j = COEEvent("j6", Primitive.JUDGE, "A", datetime.now(), "t5",
                 assertion={"subject": "door", "predicate": "status", "value": "open"}, confidence=0.9)
    v = COEEvent("v11", Primitive.VERIFY, "B", datetime.now(), "t5",
                 verify_of=["j6"], verification_result=VerificationResult.CONFIRMED, confidence=0.9)

    for e in [j, v]:
        engine.add_event(e)

    result = engine.run(target="t5")
    assert result.resolved is False
    assert result.sws is None
    assert len(result.conflicts) > 0


if __name__ == "__main__":
    test_simple_majority_consensus()
    test_weighted_trust_consensus()
    test_bft_consensus()
    test_termination_invalidates_old()
    test_unresolved_insufficient_verifications()
    print("All tests passed.")


path: coe-consensus-skill/skill/api.py
content: """
COE Consensus Skill API
FastAPI HTTP service compatible with MCP Skill conventions.
"""
from typing import Any, Dict, List, Optional
from datetime import datetime
from fastapi import FastAPI
from pydantic import BaseModel, Field

from .core import ConsensusEngine
from .types import (
    COEEvent, Primitive, ConsensusPolicy, VerificationResult,
    ConsensusResult, SharedWorldState
)


class EventInput(BaseModel):
    """Input COE event payload."""
    event_id: str
    primitive: str = Field(..., pattern="^[JDTV]$")
    issuer: str
    timestamp: str
    target: str
    assertion: Optional[Dict[str, Any]] = None
    delegate_to: Optional[str] = None
    terminate_of: Optional[str] = None
    verify_of: Optional[List[str]] = None
    verification_result: Optional[str] = None
    confidence: Optional[float] = Field(None, ge=0.0, le=1.0)
    prev_event_id: Optional[str] = None
    hash: Optional[str] = None
    signature: Optional[str] = None


class ConsensusRequest(BaseModel):
    """Request to run consensus engine."""
    session_id: str
    target: Optional[str] = None
    policy: str = "simple_majority"
    events: List[EventInput]
    trust_weights: Optional[Dict[str, float]] = None
    bft_fault_tolerance: Optional[int] = None
    weighted_threshold: Optional[float] = None

    class Config:
        json_schema_extra = {
            "example": {
                "session_id": "warehouse-001",
                "target": "warehouse-zone-3",
                "policy": "weighted_trust",
                "events": [
                    {
                        "event_id": "evt-1",
                        "primitive": "J",
                        "issuer": "robot-A",
                        "timestamp": "2026-04-19T10:30:00Z",
                        "target": "warehouse-zone-3",
                        "assertion": {"subject": "door_01", "predicate": "status", "value": "open"},
                        "confidence": 0.95
                    },
                    {
                        "event_id": "evt-2",
                        "primitive": "V",
                        "issuer": "robot-B",
                        "timestamp": "2026-04-19T10:30:05Z",
                        "target": "warehouse-zone-3",
                        "verify_of": ["evt-1"],
                        "verification_result": "confirmed",
                        "confidence": 0.9
                    }
                ],
                "trust_weights": {"robot-A": 0.9, "robot-B": 0.8, "human-1": 1.0}
            }
        }


class SWSOutput(BaseModel):
    """Shared World State output."""
    sws_id: str
    target: str
    timestamp: str
    assertions: List[Dict[str, Any]]
    previous_sws_id: Optional[str] = None
    hash: Optional[str] = None


class ConsensusResponse(BaseModel):
    """Structured consensus response."""
    session_id: str
    resolved: bool
    policy: str
    sws: Optional[SWSOutput] = None
    conflicts: List[Dict[str, Any]]
    message: str
    events_processed: int
    events_by_issuer: Dict[str, int]


app = FastAPI(
    title="COE Consensus Skill",
    description="Cross-Model Consensus Engine for Shared World State Formation",
    version="1.0.0"
)


def _to_coe_event(inp: EventInput) -> COEEvent:
    """Convert API input to internal COEEvent."""
    return COEEvent(
        event_id=inp.event_id,
        primitive=Primitive(inp.primitive),
        issuer=inp.issuer,
        timestamp=datetime.fromisoformat(inp.timestamp.replace("Z", "+00:00")),
        target=inp.target,
        assertion=inp.assertion,
        delegate_to=inp.delegate_to,
        terminate_of=inp.terminate_of,
        verify_of=inp.verify_of,
        verification_result=VerificationResult(inp.verification_result) if inp.verification_result else None,
        confidence=inp.confidence,
        prev_event_id=inp.prev_event_id,
        hash=inp.hash,
        signature=inp.signature
    )


@app.post("/consensus", response_model=ConsensusResponse)
async def consensus(request: ConsensusRequest):
    policy = ConsensusPolicy(request.policy)
    engine = ConsensusEngine(policy=policy)

    if request.trust_weights:
        for issuer, weight in request.trust_weights.items():
            engine.set_trust_weight(issuer, weight)

    if request.bft_fault_tolerance is not None:
        engine.set_bft_params(request.bft_fault_tolerance)

    if request.weighted_threshold is not None:
        engine.set_weighted_threshold(request.weighted_threshold)

    for evt_in in request.events:
        engine.add_event(_to_coe_event(evt_in))

    result = engine.run(target=request.target)

    sws_out = None
    if result.sws:
        sws_out = SWSOutput(
            sws_id=result.sws.sws_id,
            target=result.sws.target,
            timestamp=result.sws.timestamp.isoformat(),
            assertions=result.sws.assertions,
            previous_sws_id=result.sws.previous_sws_id,
            hash=result.sws.hash
        )

    return ConsensusResponse(
        session_id=request.session_id,
        resolved=result.resolved,
        policy=result.policy.value,
        sws=sws_out,
        conflicts=result.conflicts,
        message=result.message,
        events_processed=result.events_processed,
        events_by_issuer=result.events_by_issuer
    )


@app.get("/health")
async def health():
    return {"status": "ok", "skill": "coe-consensus", "version": "1.0.0"}


@app.get("/")
async def root():
    return {
        "name": "COE Consensus Skill",
        "version": "1.0.0",
        "description": "Cross-Model Consensus Engine for Shared World State Formation",
        "endpoints": ["/consensus", "/health"],
        "policies": ["simple_majority", "weighted_trust", "bft"]
    }


path: coe-consensus-skill/skill/core.py
content: """
COE Consensus Engine Core
Implements three consensus policies from COE Protocol Section 4.2:
- Simple Majority
- Weighted Trust
- Byzantine Fault Tolerance (BFT)
"""
from typing import List, Dict, Optional, Any, Tuple
from collections import defaultdict
from datetime import datetime
from uuid import uuid4

from .types import (
    COEEvent, Primitive, ConsensusPolicy, VerificationResult,
    AssertionKey, SharedWorldState, ConsensusResult, TrustWeight
)


class ConsensusEngine:
    """
    COE Consensus Engine.
    Collects J/V events, resolves conflicts, produces Shared World State.
    """

    def __init__(self, policy: ConsensusPolicy = ConsensusPolicy.SIMPLE_MAJORITY):
        self.policy = policy
        self.events: List[COEEvent] = []
        self.trust_weights: Dict[str, float] = {}
        self.bft_fault_tolerance: int = 1  # f for BFT policy
        self.weighted_threshold: float = 1.5
        self.min_verifications: int = 3  # minimum V events before evaluation
        self.timeout_seconds: float = 30.0

    def add_event(self, event: COEEvent) -> None:
        """Ingest a COE event into the engine."""
        self.events.append(event)

    def set_trust_weight(self, issuer: str, weight: float) -> None:
        """Set trust weight for a Cognitive Unit."""
        self.trust_weights[issuer] = weight

    def set_bft_params(self, fault_tolerance: int) -> None:
        """Configure BFT fault tolerance parameter f."""
        self.bft_fault_tolerance = fault_tolerance

    def set_weighted_threshold(self, threshold: float) -> None:
        """Configure weighted trust confirmation threshold."""
        self.weighted_threshold = threshold

    def run(self, target: Optional[str] = None) -> ConsensusResult:
        """
        Execute consensus on collected events.

        Args:
            target: Optional target world model ID to filter events.

        Returns:
            ConsensusResult with SWS or unresolved conflicts.
        """
        events = [e for e in self.events if target is None or e.target == target]

        if not events:
            return ConsensusResult(
                sws=None,
                resolved=False,
                conflicts=[],
                policy=self.policy,
                message="No events to process.",
                events_processed=0,
                events_by_issuer={}
            )

        # Group events by issuer for stats
        events_by_issuer = defaultdict(int)
        for e in events:
            events_by_issuer[e.issuer] += 1

        # Separate J and V events
        j_events = [e for e in events if e.primitive == Primitive.JUDGE]
        v_events = [e for e in events if e.primitive == Primitive.VERIFY]
        t_events = [e for e in events if e.primitive == Primitive.TERMINATE]

        # Apply terminations: remove terminated assertions
        terminated_ids = {e.terminate_of for e in t_events if e.terminate_of}
        active_j = [e for e in j_events if e.event_id not in terminated_ids]

        # Group active assertions by key
        assertion_groups: Dict[AssertionKey, List[COEEvent]] = defaultdict(list)
        for e in active_j:
            if e.assertion:
                key = AssertionKey(
                    target=e.target,
                    subject=e.assertion.get("subject", ""),
                    predicate=e.assertion.get("predicate", "")
                )
                assertion_groups[key].append(e)

        # For each assertion, collect verifications
        sws_assertions = []
        unresolved_conflicts = []

        for key, j_list in assertion_groups.items():
            # Get verifications for any J event in this group
            j_ids = {j.event_id for j in j_list}
            relevant_v = [v for v in v_events if v.verify_of and any(vid in j_ids for vid in v.verify_of)]

            # Evaluate consensus for this assertion
            consensus_value, confidence, confirmations, resolved = self._evaluate_assertion(
                j_list, relevant_v
            )

            if resolved:
                sws_assertions.append({
                    "subject": key.subject,
                    "predicate": key.predicate,
                    "value": consensus_value,
                    "confidence": confidence,
                    "based_on": [j.event_id for j in j_list],
                    "consensus_policy": self.policy.value,
                    "confirmations": confirmations
                })
            else:
                # Collect conflict info
                values = {}
                for j in j_list:
                    val = j.assertion.get("value") if j.assertion else None
                    values[val] = values.get(val, 0) + 1

                unresolved_conflicts.append({
                    "subject": key.subject,
                    "predicate": key.predicate,
                    "target": key.target,
                    "proposed_values": values,
                    "verifications_received": len(relevant_v),
                    "reason": "Insufficient verifications to reach consensus under current policy."
                })

        # Build SWS if we have any resolved assertions
        sws = None
        if sws_assertions:
            sws = SharedWorldState(
                sws_id=str(uuid4()),
                target=target or "global",
                timestamp=datetime.utcnow(),
                assertions=sws_assertions
            )

        resolved = len(unresolved_conflicts) == 0 and len(sws_assertions) > 0

        return ConsensusResult(
            sws=sws,
            resolved=resolved,
            conflicts=unresolved_conflicts,
            policy=self.policy,
            message=f"Consensus complete. {len(sws_assertions)} assertions resolved, {len(unresolved_conflicts)} conflicts remain.",
            events_processed=len(events),
            events_by_issuer=dict(events_by_issuer)
        )

    def _evaluate_assertion(
        self,
        j_events: List[COEEvent],
        v_events: List[COEEvent]
    ) -> Tuple[Any, float, int, bool]:
        """
        Evaluate consensus for a single assertion.

        Returns:
            (consensus_value, confidence, confirmation_count, is_resolved)
        """
        if not j_events:
            return None, 0.0, 0, False

        # Default to the most recent J event value if no verifications
        if not v_events:
            if self.policy == ConsensusPolicy.SIMPLE_MAJORITY and len(j_events) == 1:
                val = j_events[0].assertion.get("value") if j_events[0].assertion else None
                conf = j_events[0].confidence or 1.0
                return val, conf, 0, True
            return None, 0.0, 0, False

        # Count by value
        value_votes: Dict[Any, List[COEEvent]] = defaultdict(list)
        for v in v_events:
            if v.verification_result == VerificationResult.CONFIRMED:
                # Find which J event this verifies
                for j in j_events:
                    if v.verify_of and j.event_id in v.verify_of:
                        val = j.assertion.get("value") if j.assertion else None
                        value_votes[val].append(v)
                        break

        if self.policy == ConsensusPolicy.SIMPLE_MAJORITY:
            return self._simple_majority(value_votes, v_events)
        elif self.policy == ConsensusPolicy.WEIGHTED_TRUST:
            return self._weighted_trust(value_votes, j_events)
        elif self.policy == ConsensusPolicy.BFT:
            return self._bft(value_votes, v_events)

        return None, 0.0, 0, False

    def _simple_majority(
        self,
        value_votes: Dict[Any, List[COEEvent]],
        all_v: List[COEEvent]
    ) -> Tuple[Any, float, int, bool]:
        total = len(all_v)
        if total < self.min_verifications:
            return None, 0.0, total, False

        best_value = None
        best_count = 0
        for val, votes in value_votes.items():
            if len(votes) > best_count:
                best_count = len(votes)
                best_value = val

        if best_count > total * 0.5:
            confidence = best_count / total
            return best_value, confidence, best_count, True

        return best_value, best_count / total if total > 0 else 0.0, best_count, False

    def _weighted_trust(
        self,
        value_votes: Dict[Any, List[COEEvent]],
        j_events: List[COEEvent]
    ) -> Tuple[Any, float, int, bool]:
        # Calculate weighted confirmation score per value
        value_weights: Dict[Any, float] = defaultdict(float)
        value_counts: Dict[Any, int] = defaultdict(int)

        for val, votes in value_votes.items():
            for v in votes:
                w = self.trust_weights.get(v.issuer, 0.5)
                conf = v.confidence or 1.0
                value_weights[val] += w * conf
                value_counts[val] += 1

        if not value_weights:
            return None, 0.0, 0, False

        best_value = max(value_weights, key=lambda k: value_weights[k])
        best_weight = value_weights[best_value]

        if best_weight > self.weighted_threshold:
            return best_value, min(best_weight / (self.weighted_threshold * 1.5), 1.0), value_counts[best_value], True

        return best_value, best_weight / self.weighted_threshold if self.weighted_threshold > 0 else 0.0, value_counts[best_value], False

    def _bft(
        self,
        value_votes: Dict[Any, List[COEEvent]],
        all_v: List[COEEvent]
    ) -> Tuple[Any, float, int, bool]:
        f = self.bft_fault_tolerance
        total = len(all_v)

        # Need at least 2f+1 total verifications
        if total < 2 * f + 1:
            return None, 0.0, total, False

        best_value = None
        best_count = 0
        for val, votes in value_votes.items():
            if len(votes) > best_count:
                best_count = len(votes)
                best_value = val

        # Need more than f+1 confirmed for a value
        if best_count > f + 1:
            confidence = best_count / total
            return best_value, confidence, best_count, True

        return best_value, best_count / total if total > 0 else 0.0, best_count, False


path: coe-consensus-skill/skill/types.py
content: """
COE Consensus Skill — Core Types
Based on: Cognition-Oriented Emergence (COE) Protocol (Wang, 2026)
"""
from typing import Any, Dict, List, Optional, Set, Tuple
from dataclasses import dataclass, field
from enum import Enum
from datetime import datetime


class Primitive(Enum):
    JUDGE = "J"
    DELEGATE = "D"
    TERMINATE = "T"
    VERIFY = "V"


class ConsensusPolicy(Enum):
    SIMPLE_MAJORITY = "simple_majority"
    WEIGHTED_TRUST = "weighted_trust"
    BFT = "bft"


class VerificationResult(Enum):
    CONFIRMED = "confirmed"
    REJECTED = "rejected"
    PARTIAL = "partial"


@dataclass
class COEEvent:
    """Standard COE event structure."""
    event_id: str
    primitive: Primitive
    issuer: str
    timestamp: datetime
    target: str
    assertion: Optional[Dict[str, Any]] = None
    delegate_to: Optional[str] = None
    terminate_of: Optional[str] = None
    verify_of: Optional[List[str]] = None
    verification_result: Optional[VerificationResult] = None
    confidence: Optional[float] = None
    prev_event_id: Optional[str] = None
    hash: Optional[str] = None
    signature: Optional[str] = None


@dataclass
class AssertionKey:
    """Unique key for an assertion: target + subject + predicate."""
    target: str
    subject: str
    predicate: str

    def __hash__(self):
        return hash((self.target, self.subject, self.predicate))


@dataclass
class SharedWorldState:
    """Consensus output: Shared World State record."""
    sws_id: str
    target: str
    timestamp: datetime
    assertions: List[Dict[str, Any]]
    previous_sws_id: Optional[str] = None
    hash: Optional[str] = None


@dataclass
class ConsensusResult:
    """Result of running consensus engine."""
    sws: Optional[SharedWorldState]
    resolved: bool
    conflicts: List[Dict[str, Any]]
    policy: ConsensusPolicy
    message: str
    events_processed: int
    events_by_issuer: Dict[str, int]


@dataclass
class TrustWeight:
    """Trust weight configuration for a Cognitive Unit."""
    issuer: str
    weight: float
    source: str = "default"


path: coe-consensus-skill/skill/__init__.py
content: """
COE Consensus Skill v1.0.0
Cognitive Emergence Lab
"""
__version__ = "1.0.0"


path: coe-consensus-skill/examples/robot_consensus.py
content: """
COE Consensus Skill Example: Multi-Robot Door State Consensus
Reproduces COE Protocol Appendix A verification workflow.
Run: python robot_consensus.py
"""
import sys
sys.path.insert(0, "..")

from skill.core import ConsensusEngine
from skill.types import COEEvent, Primitive, VerificationResult, ConsensusPolicy
from datetime import datetime


def run_robot_example():
    """Three robots (A, B, C) collaboratively confirm door state."""

    print("=" * 70)
    print("COE Consensus Example: Robot Door-State Consensus")
    print("=" * 70)

    # --- Scenario 1: Simple Majority ---
    print("\n[Policy: Simple Majority]")
    engine = ConsensusEngine(policy=ConsensusPolicy.SIMPLE_MAJORITY)

    events_sm = [
        COEEvent("evt-1", Primitive.JUDGE, "robot-A", datetime(2026, 4, 19, 10, 30, 0), "warehouse-zone-3",
                 assertion={"subject": "door_01", "predicate": "status", "value": "open"}, confidence=0.95),
        COEEvent("evt-2", Primitive.VERIFY, "robot-B", datetime(2026, 4, 19, 10, 30, 5), "warehouse-zone-3",
                 verify_of=["evt-1"], verification_result=VerificationResult.CONFIRMED, confidence=0.9),
        COEEvent("evt-3", Primitive.VERIFY, "robot-C", datetime(2026, 4, 19, 10, 30, 10), "warehouse-zone-3",
                 verify_of=["evt-1"], verification_result=VerificationResult.CONFIRMED, confidence=0.85),
    ]
    for e in events_sm:
        engine.add_event(e)

    result = engine.run(target="warehouse-zone-3")
    print(f"  Resolved: {result.resolved}")
    print(f"  Message: {result.message}")
    if result.sws:
        for a in result.sws.assertions:
            print(f"  SWS: {a['subject']} = {a['value']} (confidence={a['confidence']:.2f}, confirmations={a['confirmations']})")

    # --- Scenario 2: Weighted Trust ---
    print("\n[Policy: Weighted Trust]")
    engine2 = ConsensusEngine(policy=ConsensusPolicy.WEIGHTED_TRUST)
    engine2.set_weighted_threshold(1.5)
    engine2.set_trust_weight("robot-A", 0.9)
    engine2.set_trust_weight("robot-B", 0.8)
    engine2.set_trust_weight("human-1", 1.0)

    events_wt = [
        COEEvent("evt-4", Primitive.JUDGE, "robot-A", datetime(2026, 4, 19, 10, 35, 0), "warehouse-zone-3",
                 assertion={"subject": "door_01", "predicate": "status", "value": "closed"}, confidence=0.95),
        COEEvent("evt-5", Primitive.VERIFY, "robot-B", datetime(2026, 4, 19, 10, 35, 5), "warehouse-zone-3",
                 verify_of=["evt-4"], verification_result=VerificationResult.CONFIRMED, confidence=0.9),
        COEEvent("evt-6", Primitive.VERIFY, "human-1", datetime(2026, 4, 19, 10, 35, 10), "warehouse-zone-3",
                 verify_of=["evt-4"], verification_result=VerificationResult.CONFIRMED, confidence=1.0),
    ]
    for e in events_wt:
        engine2.add_event(e)

    result2 = engine2.run(target="warehouse-zone-3")
    print(f"  Resolved: {result2.resolved}")
    print(f"  Message: {result2.message}")
    if result2.sws:
        for a in result2.sws.assertions:
            print(f"  SWS: {a['subject']} = {a['value']} (confidence={a['confidence']:.2f}, confirmations={a['confirmations']})")

    # --- Scenario 3: BFT ---
    print("\n[Policy: Byzantine Fault Tolerance (f=1)]")
    engine3 = ConsensusEngine(policy=ConsensusPolicy.BFT)
    engine3.set_bft_params(1)

    events_bft = [
        COEEvent("evt-7", Primitive.JUDGE, "robot-A", datetime(2026, 4, 19, 10, 40, 0), "warehouse-zone-3",
                 assertion={"subject": "door_01", "predicate": "status", "value": "open"}, confidence=0.95),
        COEEvent("evt-8", Primitive.VERIFY, "robot-B", datetime(2026, 4, 19, 10, 40, 5), "warehouse-zone-3",
                 verify_of=["evt-7"], verification_result=VerificationResult.CONFIRMED, confidence=0.9),
        COEEvent("evt-9", Primitive.VERIFY, "robot-C", datetime(2026, 4, 19, 10, 40, 10), "warehouse-zone-3",
                 verify_of=["evt-7"], verification_result=VerificationResult.CONFIRMED, confidence=0.85),
        COEEvent("evt-10", Primitive.VERIFY, "robot-D", datetime(2026, 4, 19, 10, 40, 15), "warehouse-zone-3",
                 verify_of=["evt-7"], verification_result=VerificationResult.CONFIRMED, confidence=0.9),
    ]
    for e in events_bft:
        engine3.add_event(e)

    result3 = engine3.run(target="warehouse-zone-3")
    print(f"  Resolved: {result3.resolved}")
    print(f"  Message: {result3.message}")
    if result3.sws:
        for a in result3.sws.assertions:
            print(f"  SWS: {a['subject']} = {a['value']} (confidence={a['confidence']:.2f}, confirmations={a['confirmations']})")

    # --- Scenario 4: Termination + Re-consensus ---
    print("\n[Scenario: Terminate old state, re-consensus new state]")
    engine4 = ConsensusEngine(policy=ConsensusPolicy.SIMPLE_MAJORITY)

    events_term = [
        COEEvent("evt-11", Primitive.JUDGE, "robot-A", datetime(2026, 4, 19, 10, 45, 0), "warehouse-zone-3",
                 assertion={"subject": "door_01", "predicate": "status", "value": "open"}, confidence=0.95),
        COEEvent("evt-12", Primitive.VERIFY, "robot-B", datetime(2026, 4, 19, 10, 45, 5), "warehouse-zone-3",
                 verify_of=["evt-11"], verification_result=VerificationResult.CONFIRMED, confidence=0.9),
        COEEvent("evt-13", Primitive.VERIFY, "robot-C", datetime(2026, 4, 19, 10, 45, 10), "warehouse-zone-3",
                 verify_of=["evt-11"], verification_result=VerificationResult.CONFIRMED, confidence=0.85),
        COEEvent("evt-14", Primitive.TERMINATE, "robot-A", datetime(2026, 4, 19, 10, 46, 0), "warehouse-zone-3",
                 terminate_of="evt-11"),
        COEEvent("evt-15", Primitive.JUDGE, "robot-A", datetime(2026, 4, 19, 10, 46, 5), "warehouse-zone-3",
                 assertion={"subject": "door_01", "predicate": "status", "value": "closed"}, confidence=0.95),
        COEEvent("evt-16", Primitive.VERIFY, "robot-B", datetime(2026, 4, 19, 10, 46, 10), "warehouse-zone-3",
                 verify_of=["evt-15"], verification_result=VerificationResult.CONFIRMED, confidence=0.9),
        COEEvent("evt-17", Primitive.VERIFY, "robot-C", datetime(2026, 4, 19, 10, 46, 15), "warehouse-zone-3",
                 verify_of=["evt-15"], verification_result=VerificationResult.CONFIRMED, confidence=0.85),
    ]
    for e in events_term:
        engine4.add_event(e)

    result4 = engine4.run(target="warehouse-zone-3")
    print(f"  Resolved: {result4.resolved}")
    print(f"  Message: {result4.message}")
    if result4.sws:
        for a in result4.sws.assertions:
            print(f"  SWS: {a['subject']} = {a['value']} (confidence={a['confidence']:.2f}, confirmations={a['confirmations']})")

    print("\n" + "=" * 70)
    print("All scenarios completed.")
    print("=" * 70)


if __name__ == "__main__":
    run_robot_example()


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: clean (LOW)