Skill: schchit/jep-primitive-skills (version 1.0.0)

--- name: jep-primitive-skills version: 1.0.0 description: JEP Primitive Skills — Atomic Reference Implementations of Judge, Delegate, Terminate, Verify for Agent Collaboration Grammar author: Cognitive Emergence Lab <[REDACTED_SECRET]> license: MIT protocol: JEP tags: - jep - primitive - judge - delegate - terminate - verify - atomic - grammar entrypoint: skill.api:app host_targets: - mcp - api - python skills: - name: judge description: Initiate an observation assertion (J primitive) input_schema: type: object properties: issuer: type: string target: type: string subject: type: string predicate: type: string value: {} confidence: type: number parent_task_hash: type: string signature: type: string required: [issuer, target, subject, predicate, value] output_schema: type: object properties: success: type: boolean primitive: type: string nonce: type: string who: type: string when: type: integer what: type: string message: type: string next_suggested_primitive: type: string canonical_json: type: string - name: delegate description: Transfer authority to another agent (D primitive) input_schema: type: object properties: issuer: type: string delegate_to: type: string target: type: string scope: type: string prev_event_id: type: string signature: type: string required: [issuer, delegate_to, target] output_schema: type: object properties: success: type: boolean primitive: type: string nonce: type: string who: type: string when: type: integer what: type: string message: type: string next_suggested_primitive: type: string canonical_json: type: string - name: terminate description: Close the lifecycle of a prior assertion (T primitive) input_schema: type: object properties: issuer: type: string terminate_of: type: string target: type: string reason: type: string prev_event_id: type: string signature: type: string required: [issuer, terminate_of, target] output_schema: type: object properties: success: type: boolean primitive: type: string nonce: type: string who: type: string when: type: integer what: type: string message: type: string next_suggested_primitive: type: string canonical_json: type: string - name: verify description: Cross-validate an existing assertion (V primitive) input_schema: type: object properties: issuer: type: string verify_of: type: array items: type: string target: type: string verification_result: type: string enum: [confirmed, rejected, partial] confidence: type: number prev_event_id: type: string signature: type: string required: [issuer, verify_of, target] output_schema: type: object properties: success: type: boolean primitive: type: string nonce: type: string who: type: string when: type: integer what: type: string message: type: string next_suggested_primitive: type: string canonical_json: type: string --- # JEP Primitive Skills **Atomic Reference Implementations of Judge, Delegate, Terminate, Verify** ## The Four Primitives | Primitive | Verb | Purpose | |-----------|------|---------| | **Judge** | J | Initiate an observation assertion | | **Delegate** | D | Transfer authority to another agent | | **Terminate** | T | Close the lifecycle of a prior assertion | | **Verify** | V | Cross-validate an existing assertion | ## Complete Cognitive Interaction Algebra These four primitives form a complete algebra: - **J** creates state. - **V** validates state. - **D** distributes responsibility for state. - **T** invalidates state. Any complex multi-agent collaboration decomposes into ordered combinations of these four atoms. No fifth primitive is required. ## Protocol Alignment All events produced are strict JEP-04 compliant: - `jep`: "1" - `verb`: J/D/T/V - `who`: issuer DID - `when`: Unix timestamp - `what`: SHA-256 multihash of payload - `nonce`: UUIDv4 - `aud`: target - `ref`: chain link - `sig`: JWS signature - `task_based_on`: JAC-01 parent task hash ## Integration Events feed directly into: - **Determinability-Checker** — causal sufficiency verification - **COE-Consensus** — shared world state formation - **JEP-Guard-Audit** — compliance chain generation --- Cognitive Emergence Lab [REDACTED_SECRET]

path: jep-primitive-skills/CHANGELOG.md
content: # Changelog

## [1.0.0] - 2026-04-26

### Added
- Four atomic primitive skills, each <= 200 lines of core logic:
  - **JudgeSkill** (J): Initiate observation assertion with subject/predicate/value structure.
  - **DelegateSkill** (D): Transfer authority with assigner/assignee JAC extension.
  - **TerminateSkill** (T): Close lifecycle with JAC-Fault extension for audit trail.
  - **VerifySkill** (V): Cross-validate with confirmed/rejected/partial results.
- Three-layer architecture:
  - **PrimitiveSkill** (API): Friendly `execute()` methods returning `PrimitiveResult`.
  - **JEPAdapter** (Mapping): `FriendlyEvent` -> strict `JEP04Event` conversion.
  - **JEPCodec** (Protocol): Canonical JSON (RFC 8785), SHA-256 multihash (RFC 9122), UUIDv4 nonce (RFC 9562).
- FastAPI endpoints: `/judge`, `/delegate`, `/terminate`, `/verify`, `/health`.
- Example: `complex_workflow.py` — 7-step warehouse monitoring using only J/D/T/V primitives.
- Tests: 6 unit tests covering all four primitives, parent task hash, rejected verification.

### Design Principles
- **Minimal**: Each primitive does exactly one thing.
- **Composable**: Any complex workflow is an ordered sequence of these four atoms.
- **Interoperable**: Events are strict JEP-04 and feed into Determinability-Checker, COE-Consensus, and JEP-Guard-Audit without conversion.

### References
- Wang, Y. (2026). *JEP: Judgment Event Protocol* (draft-wang-jep-judgment-event-protocol-04).
- Wang, Y. (2026). *JAC: Judgment Accountability Chain* (draft-wang-jac-01).


path: jep-primitive-skills/manifest.json
content: {
  "name": "jep-primitive-skills",
  "version": "1.0.0",
  "description": "JEP Primitive Skills — Atomic Reference Implementations of Judge, Delegate, Terminate, Verify for Agent Collaboration Grammar",
  "author": "Cognitive Emergence Lab <[REDACTED_SECRET]>",
  "license": "MIT",
  "protocol": "JEP",
  "entrypoint": "skill.api:app",
  "host_targets": [
    "mcp",
    "api",
    "python"
  ],
  "dependencies": [
    "fastapi>=0.104.0",
    "uvicorn>=0.24.0",
    "pydantic>=2.5.0"
  ],
  "tags": [
    "jep",
    "primitive",
    "judge",
    "delegate",
    "terminate",
    "verify",
    "atomic",
    "grammar"
  ]
}

path: jep-primitive-skills/README.md
content: # JEP Primitive Skills v1.0.0

**Atomic Reference Implementations of Judge, Delegate, Terminate, Verify**

Based on **JEP-04** (draft-wang-jep-judgment-event-protocol-04) and **JAC-01** (draft-wang-jac-01).

> **Core Principle:** Any complex multi-agent collaboration can be decomposed into an ordered combination of these four atomic operations. No fifth primitive is required.

## The Four Primitives

| Primitive | Verb | Purpose | When to Use |
|-----------|------|---------|-------------|
| **Judge** | J | Initiate an observation assertion | "I observe X at this time" |
| **Delegate** | D | Transfer authority to another agent | "I authorize you to observe/confirm X" |
| **Terminate** | T | Close the lifecycle of a prior assertion | "This observation is no longer valid" |
| **Verify** | V | Cross-validate an existing assertion | "I confirm/verify that observation" |

## Architecture

```
PrimitiveSkill (API Layer)    — Friendly execute() methods
        ↓
JEPAdapter (Mapping Layer)    — FriendlyEvent → JEP04Event
        ↓
JEPCodec (Protocol Layer)     — Strict jep/verb/who/when/what/nonce/aud/ref/sig
```

## Quick Start

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

## API

### Judge

```bash
curl -X POST http://localhost:8000/judge   -H "Content-Type: application/json"   -d '{
    "issuer": "did:example:robotA",
    "target": "warehouse-zone-3",
    "subject": "door_01",
    "predicate": "status",
    "value": "open",
    "confidence": 0.95
  }'
```

### Delegate

```bash
curl -X POST http://localhost:8000/delegate   -H "Content-Type: application/json"   -d '{
    "issuer": "did:example:robotA",
    "delegate_to": "did:example:robotB",
    "target": "warehouse-zone-3",
    "scope": "continuous_observation"
  }'
```

### Terminate

```bash
curl -X POST http://localhost:8000/terminate   -H "Content-Type: application/json"   -d '{
    "issuer": "did:example:robotA",
    "terminate_of": "<nonce-of-prior-J-event>",
    "target": "warehouse-zone-3",
    "reason": "state_changed"
  }'
```

### Verify

```bash
curl -X POST http://localhost:8000/verify   -H "Content-Type: application/json"   -d '{
    "issuer": "did:example:robotB",
    "verify_of": ["<nonce-of-J-event>"],
    "target": "warehouse-zone-3",
    "verification_result": "confirmed",
    "confidence": 0.9
  }'
```

## Why These Four?

These four primitives form a **complete cognitive interaction algebra**:

- **J** creates state.
- **V** validates state.
- **D** distributes responsibility for state.
- **T** invalidates state.

Any complex scenario — robot collaboration, AR/VR co-presence, distributed scientific consensus, cognitive economy transactions — decomposes into sequences of these four atoms.

## Example

```bash
cd examples
python complex_workflow.py
```

Demonstrates a 7-step warehouse door monitoring workflow using only J/D/T/V.

## Integration

Events produced by these primitives are strict JEP-04 compliant and can be directly consumed by:

- **Determinability-Checker** — causal sufficiency verification
- **COE-Consensus** — shared world state formation
- **JEP-Guard-Audit** — compliance chain generation

---

Cognitive Emergence Lab  
[REDACTED_SECRET]


path: jep-primitive-skills/requirements.txt
content: fastapi>=0.104.0
uvicorn>=0.24.0
pydantic>=2.5.0


path: jep-primitive-skills/tests/test_primitives.py
content: """
Primitive Skills Unit Tests
Run: pytest tests/test_primitives.py
"""
import sys
sys.path.insert(0, "..")

from skill.primitives import JudgeSkill, DelegateSkill, TerminateSkill, VerifySkill
from skill.types import Verb


def test_judge_skill():
    r = JudgeSkill.execute(
        issuer="did:example:a", target="t1", subject="door",
        predicate="status", value="open", confidence=0.95
    )
    assert r.success is True
    assert r.event.verb == Verb.JUDGE
    assert r.event.who == "did:example:a"
    assert r.event.aud == "t1"
    assert r.event.what is not None  # multihash computed
    assert r.event.nonce != ""
    assert r.next_suggested_primitive == "V"


def test_delegate_skill():
    r = DelegateSkill.execute(
        issuer="did:example:a", delegate_to="did:example:b",
        target="t1", scope="continuous_observation"
    )
    assert r.success is True
    assert r.event.verb == Verb.DELEGATE
    assert r.event.who == "did:example:a"
    assert r.next_suggested_primitive == "J"
    # Check JAC assign extension
    assert r.event.extensions is not None
    assert "https://jac.org/assign" in r.event.extensions


def test_terminate_skill():
    r = TerminateSkill.execute(
        issuer="did:example:a", terminate_of="evt-123",
        target="t1", reason="state_changed"
    )
    assert r.success is True
    assert r.event.verb == Verb.TERMINATE
    assert r.event.who == "did:example:a"
    assert r.next_suggested_primitive == "J"
    # Check JAC fault extension
    assert r.event.extensions is not None
    assert "https://jac.org/fault" in r.event.extensions


def test_verify_skill():
    r = VerifySkill.execute(
        issuer="did:example:b", verify_of=["evt-123"],
        target="t1", verification_result="confirmed", confidence=0.9
    )
    assert r.success is True
    assert r.event.verb == Verb.VERIFY
    assert r.event.who == "did:example:b"
    assert r.event.ref == "evt-123"
    assert r.next_suggested_primitive == "V"


def test_judge_with_parent_task():
    r = JudgeSkill.execute(
        issuer="did:example:a", target="t1", subject="door",
        predicate="status", value="closed", parent_task_hash="parent-001"
    )
    assert r.event.task_based_on == "parent-001"


def test_verify_rejected():
    r = VerifySkill.execute(
        issuer="did:example:c", verify_of=["evt-456"],
        target="t1", verification_result="rejected"
    )
    assert r.event.extensions is not None
    jac_result = r.event.extensions.get("https://jac.org/result")
    assert jac_result["verification_result"] == "rejected"


if __name__ == "__main__":
    test_judge_skill()
    test_delegate_skill()
    test_terminate_skill()
    test_verify_skill()
    test_judge_with_parent_task()
    test_verify_rejected()
    print("All 6 tests passed.")


path: jep-primitive-skills/skill/adapter.py
content: """
JEPAdapter — Mapping Layer
Converts FriendlyEvent to strict JEP04Event.
"""
from typing import Any, Dict, Optional

from .types import FriendlyEvent, JEP04Event, Verb
from .codec import JEPCodec


class JEPAdapter:
    @staticmethod
    def to_jep04(friendly: FriendlyEvent) -> JEP04Event:
        verb = Verb(friendly.primitive)
        when = JEPCodec.iso_to_unix(friendly.timestamp)
        nonce = JEPCodec.generate_nonce()

        # Build what payload
        what_payload = {}
        if friendly.assertion:
            what_payload["assertion"] = friendly.assertion
        if friendly.delegate_to:
            what_payload["delegate_to"] = friendly.delegate_to
        if friendly.terminate_of:
            what_payload["terminate_of"] = friendly.terminate_of
        if friendly.verify_of:
            what_payload["verify_of"] = friendly.verify_of
            what_payload["verification_result"] = friendly.verification_result
        if friendly.confidence is not None:
            what_payload["confidence"] = friendly.confidence
        what = JEPCodec.compute_what(what_payload) if what_payload else None

        # ref from prev_event_id or verify_of
        ref = None
        if friendly.verify_of and len(friendly.verify_of) > 0:
            ref = friendly.verify_of[0]
        elif friendly.prev_event_id:
            ref = friendly.prev_event_id

        extensions = friendly.extensions or {}

        # JAC extensions
        if friendly.verification_result or friendly.confidence is not None:
            jac_result = {}
            if friendly.verification_result:
                jac_result["verification_result"] = friendly.verification_result
            if friendly.confidence is not None:
                jac_result["confidence"] = friendly.confidence
            extensions["https://jac.org/result"] = jac_result

        if friendly.delegate_to:
            extensions["https://jac.org/assign"] = {
                "assignee": friendly.delegate_to,
                "assigner": friendly.issuer
            }

        if verb == Verb.TERMINATE and friendly.terminate_of:
            extensions["https://jac.org/fault"] = {
                "expected_parent": friendly.terminate_of,
                "fault_type": "orphan_termination",
                "fault_reason": "Terminate references a non-existent or expired event"
            }

        if friendly.target:
            extensions["https://jep.org/subject"] = {
                "id": friendly.target,
                "predicate": friendly.assertion.get("predicate") if friendly.assertion else None
            }

        return JEP04Event(
            jep="1", verb=verb, who=friendly.issuer, when=when,
            what=what, nonce=nonce, aud=friendly.target, ref=ref,
            sig=friendly.signature or "",
            task_based_on=friendly.parent_task_hash,
            extensions=extensions if extensions else None,
        )

    @staticmethod
    def from_jep04(event: JEP04Event) -> FriendlyEvent:
        assertion = None
        delegate_to = None
        terminate_of = None
        verify_of = None
        verification_result = None
        confidence = None

        if event.extensions:
            jac_result = event.extensions.get("https://jac.org/result")
            if jac_result:
                verification_result = jac_result.get("verification_result")
                confidence = jac_result.get("confidence")
            jac_assign = event.extensions.get("https://jac.org/assign")
            if jac_assign:
                delegate_to = jac_assign.get("assignee")
            jac_fault = event.extensions.get("https://jac.org/fault")
            if jac_fault:
                terminate_of = jac_fault.get("expected_parent")

        return FriendlyEvent(
            event_id=event.nonce, primitive=event.verb.value,
            issuer=event.who, timestamp=JEPCodec.unix_to_iso(event.when),
            target=event.aud, assertion=assertion,
            delegate_to=delegate_to, terminate_of=terminate_of,
            verify_of=[event.ref] if event.ref else None,
            verification_result=verification_result,
            confidence=confidence, prev_event_id=event.ref,
            parent_task_hash=event.task_based_on,
            signature=event.sig, extensions=event.extensions,
        )


path: jep-primitive-skills/skill/api.py
content: """
JEP Primitive Skills API
Exposes Judge / Delegate / Terminate / Verify as HTTP endpoints.
Each endpoint returns a strict JEP-04 event.
"""
from typing import Any, Dict, List, Optional
from fastapi import FastAPI
from pydantic import BaseModel, Field

from .primitives import JudgeSkill, DelegateSkill, TerminateSkill, VerifySkill
from .types import PrimitiveResult
from .codec import JEPCodec


# ---------- Judge ----------

class JudgeRequest(BaseModel):
    issuer: str
    target: str
    subject: str
    predicate: str
    value: Any
    confidence: Optional[float] = Field(None, ge=0.0, le=1.0)
    parent_task_hash: Optional[str] = None
    signature: Optional[str] = None


# ---------- Delegate ----------

class DelegateRequest(BaseModel):
    issuer: str
    delegate_to: str
    target: str
    scope: Optional[str] = None
    prev_event_id: Optional[str] = None
    signature: Optional[str] = None


# ---------- Terminate ----------

class TerminateRequest(BaseModel):
    issuer: str
    terminate_of: str
    target: str
    reason: Optional[str] = None
    prev_event_id: Optional[str] = None
    signature: Optional[str] = None


# ---------- Verify ----------

class VerifyRequest(BaseModel):
    issuer: str
    verify_of: List[str]
    target: str
    verification_result: str = "confirmed"
    confidence: Optional[float] = Field(None, ge=0.0, le=1.0)
    prev_event_id: Optional[str] = None
    signature: Optional[str] = None


# ---------- Shared Response ----------

class PrimitiveResponse(BaseModel):
    success: bool
    primitive: str
    nonce: str
    who: str
    when: int
    what: Optional[str]
    ref: Optional[str]
    task_based_on: Optional[str]
    message: str
    next_suggested_primitive: Optional[str]
    canonical_json: str


def _to_response(result: PrimitiveResult) -> PrimitiveResponse:
    evt = result.event
    return PrimitiveResponse(
        success=result.success,
        primitive=evt.verb.value,
        nonce=evt.nonce,
        who=evt.who,
        when=evt.when,
        what=evt.what,
        ref=evt.ref,
        task_based_on=evt.task_based_on,
        message=result.message,
        next_suggested_primitive=result.next_suggested_primitive,
        canonical_json=JEPCodec.encode(evt),
    )


app = FastAPI(
    title="JEP Primitive Skills",
    description="Atomic Reference Implementations of Judge, Delegate, Terminate, Verify",
    version="1.0.0"
)


@app.post("/judge", response_model=PrimitiveResponse)
async def judge(request: JudgeRequest):
    result = JudgeSkill.execute(
        issuer=request.issuer,
        target=request.target,
        subject=request.subject,
        predicate=request.predicate,
        value=request.value,
        confidence=request.confidence,
        parent_task_hash=request.parent_task_hash,
        signature=request.signature,
    )
    return _to_response(result)


@app.post("/delegate", response_model=PrimitiveResponse)
async def delegate(request: DelegateRequest):
    result = DelegateSkill.execute(
        issuer=request.issuer,
        delegate_to=request.delegate_to,
        target=request.target,
        scope=request.scope,
        prev_event_id=request.prev_event_id,
        signature=request.signature,
    )
    return _to_response(result)


@app.post("/terminate", response_model=PrimitiveResponse)
async def terminate(request: TerminateRequest):
    result = TerminateSkill.execute(
        issuer=request.issuer,
        terminate_of=request.terminate_of,
        target=request.target,
        reason=request.reason,
        prev_event_id=request.prev_event_id,
        signature=request.signature,
    )
    return _to_response(result)


@app.post("/verify", response_model=PrimitiveResponse)
async def verify(request: VerifyRequest):
    result = VerifySkill.execute(
        issuer=request.issuer,
        verify_of=request.verify_of,
        target=request.target,
        verification_result=request.verification_result,
        confidence=request.confidence,
        prev_event_id=request.prev_event_id,
        signature=request.signature,
    )
    return _to_response(result)


@app.get("/health")
async def health():
    return {"status": "ok", "skill": "jep-primitive-skills", "version": "1.0.0", "primitives": ["J", "D", "T", "V"]}


@app.get("/")
async def root():
    return {
        "name": "JEP Primitive Skills",
        "version": "1.0.0",
        "description": "Atomic Reference Implementations of Judge, Delegate, Terminate, Verify",
        "primitives": ["/judge", "/delegate", "/terminate", "/verify"],
        "protocol": "JEP-04",
        "jac": "JAC-01",
    }


path: jep-primitive-skills/skill/codec.py
content: """
JEPCodec — Strict Protocol Layer
JEP-04 (draft-wang-jep-judgment-event-protocol-04) + JAC-01 (draft-wang-jac-01)
"""
import hashlib
import json
import uuid
from datetime import datetime, timezone
from typing import Any, Dict, Optional

from .types import JEP04Event, Verb


class JEPCodec:
    PROTOCOL_VERSION = "1"
    HASH_PREFIX = "sha256:"
    CLOCK_SKEW_TOLERANCE = 300

    @staticmethod
    def encode(event: JEP04Event) -> str:
        payload = {
            "jep": event.jep,
            "verb": event.verb.value,
            "who": event.who,
            "when": event.when,
            "what": event.what,
            "nonce": event.nonce,
            "aud": event.aud,
            "ref": event.ref,
            "sig": event.sig,
        }
        if event.task_based_on is not None:
            payload["task_based_on"] = event.task_based_on
        if event.extensions is not None:
            payload["extensions"] = event.extensions
        return json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str)

    @staticmethod
    def decode(raw: str) -> JEP04Event:
        payload = json.loads(raw)
        return JEP04Event(
            jep=payload.get("jep", "1"),
            verb=Verb(payload.get("verb", "J")),
            who=payload["who"],
            when=payload["when"],
            what=payload.get("what"),
            nonce=payload["nonce"],
            aud=payload.get("aud"),
            ref=payload.get("ref"),
            sig=payload.get("sig", ""),
            task_based_on=payload.get("task_based_on"),
            extensions=payload.get("extensions"),
        )

    @staticmethod
    def compute_what(data: Dict[str, Any]) -> str:
        canonical = json.dumps(data, sort_keys=True, separators=(",", ":"), default=str)
        digest = hashlib.sha256(canonical.encode("utf-8")).hexdigest()
        return f"{JEPCodec.HASH_PREFIX}{digest}"

    @staticmethod
    def generate_nonce() -> str:
        return str(uuid.uuid4())

    @staticmethod
    def iso_to_unix(iso_timestamp: str) -> int:
        dt = datetime.fromisoformat(iso_timestamp.replace("Z", "+00:00"))
        return int(dt.timestamp())

    @staticmethod
    def unix_to_iso(unix_ts: int) -> str:
        dt = datetime.fromtimestamp(unix_ts, tz=timezone.utc)
        return dt.strftime("%Y-%m-%dT%H:%M:%SZ")


path: jep-primitive-skills/skill/primitives.py
content: """
JEP Primitive Skills — Atomic Reference Implementations
Judge / Delegate / Terminate / Verify

Each skill is a minimal, self-contained atomic operation.
Any complex multi-agent collaboration can be decomposed into
an ordered combination of these four primitives.

Design constraints:
  - Each skill <= 200 lines of core logic
  - Strict JEP-04 event output via JEPAdapter
  - No business logic beyond the primitive semantics
  - Extensible via JAC-01 extension modules
"""
from typing import Any, Dict, List, Optional
from datetime import datetime, timezone

from .types import FriendlyEvent, JEP04Event, Verb, PrimitiveResult
from .codec import JEPCodec
from .adapter import JEPAdapter


# ---------------------------------------------------------------------------
# Primitive 1: JudgeSkill (J)
# ---------------------------------------------------------------------------

class JudgeSkill:
    """
    Initiate an observation assertion.
    Standard template for any agent declaring "I observe X at this time."
    """

    @staticmethod
    def execute(
        issuer: str,
        target: str,
        subject: str,
        predicate: str,
        value: Any,
        confidence: Optional[float] = None,
        parent_task_hash: Optional[str] = None,
        signature: Optional[str] = None,
        extensions: Optional[Dict[str, Any]] = None,
    ) -> PrimitiveResult:
        """
        Execute a Judge primitive.

        Args:
            issuer: Actor DID initiating the observation.
            target: Target world model or scene ID.
            subject: Identifier of the observed entity.
            predicate: Property being observed.
            value: Observed value (string, number, boolean, or JSON).
            confidence: Optional confidence score [0.0, 1.0].
            parent_task_hash: Optional JAC-01 parent task hash.
            signature: Optional JWS signature.
            extensions: Optional JAC/JEP extensions.

        Returns:
            PrimitiveResult with strict JEP-04 J event.
        """
        timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
        assertion = {
            "subject": subject,
            "predicate": predicate,
            "value": value,
        }
        if confidence is not None:
            assertion["confidence"] = confidence

        friendly = FriendlyEvent(
            event_id=f"j-{JEPCodec.generate_nonce()}",
            primitive="J",
            issuer=issuer,
            timestamp=timestamp,
            target=target,
            assertion=assertion,
            confidence=confidence,
            prev_event_id=None,
            parent_task_hash=parent_task_hash,
            signature=signature,
            extensions=extensions,
        )

        jep_event = JEPAdapter.to_jep04(friendly)

        return PrimitiveResult(
            success=True,
            event=jep_event,
            message=f"Judge event created: {subject}.{predicate}={value} by {issuer}",
            next_suggested_primitive="V",
        )


# ---------------------------------------------------------------------------
# Primitive 2: DelegateSkill (D)
# ---------------------------------------------------------------------------

class DelegateSkill:
    """
    Transfer observation or confirmation authority to another agent.
    Declares "I authorize you to observe or confirm X."
    """

    @staticmethod
    def execute(
        issuer: str,
        delegate_to: str,
        target: str,
        scope: Optional[str] = None,
        prev_event_id: Optional[str] = None,
        signature: Optional[str] = None,
        extensions: Optional[Dict[str, Any]] = None,
    ) -> PrimitiveResult:
        """
        Execute a Delegate primitive.

        Args:
            issuer: Actor DID delegating authority.
            delegate_to: Actor DID receiving authority.
            target: Target world model or scene ID.
            scope: Optional delegation scope (e.g., "continuous_observation").
            prev_event_id: Optional prior event to chain from.
            signature: Optional JWS signature.
            extensions: Optional extensions.

        Returns:
            PrimitiveResult with strict JEP-04 D event.
        """
        timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")

        ext = extensions or {}
        if scope:
            ext["https://jac.org/assign"] = {
                "assigner": issuer,
                "assignee": delegate_to,
                "delegation_scope": scope,
            }

        friendly = FriendlyEvent(
            event_id=f"d-{JEPCodec.generate_nonce()}",
            primitive="D",
            issuer=issuer,
            timestamp=timestamp,
            target=target,
            delegate_to=delegate_to,
            prev_event_id=prev_event_id,
            signature=signature,
            extensions=ext if ext else None,
        )

        jep_event = JEPAdapter.to_jep04(friendly)

        return PrimitiveResult(
            success=True,
            event=jep_event,
            message=f"Delegate event created: {issuer} -> {delegate_to} for {target}",
            next_suggested_primitive="J",
        )


# ---------------------------------------------------------------------------
# Primitive 3: TerminateSkill (T)
# ---------------------------------------------------------------------------

class TerminateSkill:
    """
    Declare that a previously initiated observation assertion is no longer valid.
    Closes the lifecycle of a state.
    """

    @staticmethod
    def execute(
        issuer: str,
        terminate_of: str,
        target: str,
        reason: Optional[str] = None,
        prev_event_id: Optional[str] = None,
        signature: Optional[str] = None,
        extensions: Optional[Dict[str, Any]] = None,
    ) -> PrimitiveResult:
        """
        Execute a Terminate primitive.

        Args:
            issuer: Actor DID terminating the assertion.
            terminate_of: Event ID (nonce) of the J event being terminated.
            target: Target world model or scene ID.
            reason: Optional termination reason (e.g., "observation_expired").
            prev_event_id: Optional prior event to chain from.
            signature: Optional JWS signature.
            extensions: Optional extensions.

        Returns:
            PrimitiveResult with strict JEP-04 T event.
        """
        timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")

        ext = extensions or {}
        ext["https://jac.org/fault"] = {
            "expected_parent": terminate_of,
            "fault_type": "termination",
            "fault_reason": reason or "State terminated by issuer",
        }

        friendly = FriendlyEvent(
            event_id=f"t-{JEPCodec.generate_nonce()}",
            primitive="T",
            issuer=issuer,
            timestamp=timestamp,
            target=target,
            terminate_of=terminate_of,
            prev_event_id=prev_event_id,
            signature=signature,
            extensions=ext,
        )

        jep_event = JEPAdapter.to_jep04(friendly)

        return PrimitiveResult(
            success=True,
            event=jep_event,
            message=f"Terminate event created: {terminate_of} terminated by {issuer}",
            next_suggested_primitive="J",
        )


# ---------------------------------------------------------------------------
# Primitive 4: VerifySkill (V)
# ---------------------------------------------------------------------------

class VerifySkill:
    """
    Cross-validate or confirm one or more observation assertions from other agents.
    Provides credibility weighting for consensus engines.
    """

    @staticmethod
    def execute(
        issuer: str,
        verify_of: List[str],
        target: str,
        verification_result: str = "confirmed",
        confidence: Optional[float] = None,
        prev_event_id: Optional[str] = None,
        signature: Optional[str] = None,
        extensions: Optional[Dict[str, Any]] = None,
    ) -> PrimitiveResult:
        """
        Execute a Verify primitive.

        Args:
            issuer: Actor DID performing verification.
            verify_of: List of event IDs (nonces) being verified.
            target: Target world model or scene ID.
            verification_result: "confirmed", "rejected", or "partial".
            confidence: Optional confidence score [0.0, 1.0].
            prev_event_id: Optional prior event to chain from.
            signature: Optional JWS signature.
            extensions: Optional extensions.

        Returns:
            PrimitiveResult with strict JEP-04 V event.
        """
        timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")

        friendly = FriendlyEvent(
            event_id=f"v-{JEPCodec.generate_nonce()}",
            primitive="V",
            issuer=issuer,
            timestamp=timestamp,
            target=target,
            verify_of=verify_of,
            verification_result=verification_result,
            confidence=confidence,
            prev_event_id=prev_event_id,
            signature=signature,
            extensions=extensions,
        )

        jep_event = JEPAdapter.to_jep04(friendly)

        return PrimitiveResult(
            success=True,
            event=jep_event,
            message=f"Verify event created: {issuer} {verification_result} {len(verify_of)} event(s)",
            next_suggested_primitive="V",
        )


path: jep-primitive-skills/skill/types.py
content: """
JEP Primitive Skills — Core Types
Strictly aligned with JEP-04 (draft-wang-jep-judgment-event-protocol-04)
and JAC-01 (draft-wang-jac-01).

Four atomic primitives form the complete collaboration grammar:
  J (Judge)     — Initiate an observation assertion
  D (Delegate)  — Transfer authority to another agent
  T (Terminate) — Close the lifecycle of a prior assertion
  V (Verify)    — Cross-validate an existing assertion

No fifth primitive is required.
"""
from typing import Any, Dict, List, Optional
from dataclasses import dataclass
from enum import Enum


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


@dataclass
class JEP04Event:
    """Strict JEP-04 event structure (Section 2.2)."""
    jep: str = "1"
    verb: Verb = Verb.JUDGE
    who: str = ""
    when: int = 0
    what: Optional[str] = None
    nonce: str = ""
    aud: Optional[str] = None
    ref: Optional[str] = None
    sig: str = ""
    task_based_on: Optional[str] = None
    extensions: Optional[Dict[str, Any]] = None


@dataclass
class FriendlyEvent:
    """Developer-friendly event format."""
    event_id: str
    primitive: str
    issuer: str
    timestamp: str
    target: Optional[str] = None
    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] = None
    prev_event_id: Optional[str] = None
    parent_task_hash: Optional[str] = None
    signature: Optional[str] = None
    extensions: Optional[Dict[str, Any]] = None


@dataclass
class PrimitiveResult:
    """Result of executing a primitive skill."""
    success: bool
    event: JEP04Event
    message: str
    next_suggested_primitive: Optional[str] = None


path: jep-primitive-skills/skill/__init__.py
content: """
JEP Primitive Skills v1.0.0
Cognitive Emergence Lab
"""
__version__ = "1.0.0"


path: jep-primitive-skills/examples/complex_workflow.py
content: """
JEP Primitive Skills Example: Complex Multi-Agent Workflow
Demonstrates how any complex collaboration decomposes into J/D/T/V atoms.
Run: python complex_workflow.py
"""
import sys
sys.path.insert(0, "..")

from skill.primitives import JudgeSkill, DelegateSkill, TerminateSkill, VerifySkill
from skill.codec import JEPCodec


def run_complex_workflow():
    print("=" * 70)
    print("JEP Primitive Skills: Complex Multi-Agent Workflow")
    print("=" * 70)

    agents = {
        "robot-A": "did:example:robotA",
        "robot-B": "did:example:robotB",
        "human-C": "did:example:humanC",
    }
    target = "warehouse-zone-3"

    # Step 1: Robot A observes door is open (J)
    print("
[Step 1] Robot A observes door is open")
    j1 = JudgeSkill.execute(
        issuer=agents["robot-A"],
        target=target,
        subject="door_01",
        predicate="status",
        value="open",
        confidence=0.95,
    )
    print(f"  J event: nonce={j1.event.nonce}, what={j1.event.what[:30]}...")
    print(f"  Next suggested: {j1.next_suggested_primitive}")

    # Step 2: Robot B verifies the observation (V)
    print("
[Step 2] Robot B confirms Robot A's observation")
    v1 = VerifySkill.execute(
        issuer=agents["robot-B"],
        verify_of=[j1.event.nonce],
        target=target,
        verification_result="confirmed",
        confidence=0.9,
    )
    print(f"  V event: nonce={v1.event.nonce}, ref={v1.event.ref}")

    # Step 3: Human C also verifies (V)
    print("
[Step 3] Human supervisor confirms")
    v2 = VerifySkill.execute(
        issuer=agents["human-C"],
        verify_of=[j1.event.nonce],
        target=target,
        verification_result="confirmed",
        confidence=1.0,
    )
    print(f"  V event: nonce={v2.event.nonce}")

    # Step 4: Robot A delegates continuous monitoring to Robot B (D)
    print("
[Step 4] Robot A delegates continuous observation to Robot B")
    d1 = DelegateSkill.execute(
        issuer=agents["robot-A"],
        delegate_to=agents["robot-B"],
        target=target,
        scope="continuous_observation",
        prev_event_id=j1.event.nonce,
    )
    print(f"  D event: nonce={d1.event.nonce}, assignee in extensions")

    # Step 5: Robot B observes door closed (J, based on prior task)
    print("
[Step 5] Robot B observes door is now closed")
    j2 = JudgeSkill.execute(
        issuer=agents["robot-B"],
        target=target,
        subject="door_01",
        predicate="status",
        value="closed",
        confidence=0.92,
        parent_task_hash=j1.event.nonce,  # JAC-01: this is based on prior task
    )
    print(f"  J event: nonce={j2.event.nonce}, task_based_on={j2.event.task_based_on}")

    # Step 6: Robot A terminates old observation (T)
    print("
[Step 6] Robot A terminates the old 'open' observation")
    t1 = TerminateSkill.execute(
        issuer=agents["robot-A"],
        terminate_of=j1.event.nonce,
        target=target,
        reason="state_changed",
        prev_event_id=j2.event.nonce,
    )
    print(f"  T event: nonce={t1.event.nonce}, terminate_of={t1.event.what[:30]}...")

    # Step 7: Human C verifies the new state (V)
    print("
[Step 7] Human supervisor confirms the closed state")
    v3 = VerifySkill.execute(
        issuer=agents["human-C"],
        verify_of=[j2.event.nonce],
        target=target,
        verification_result="confirmed",
        confidence=1.0,
    )
    print(f"  V event: nonce={v3.event.nonce}")

    # Summary
    print("
" + "=" * 70)
    print("Workflow Summary")
    print("=" * 70)
    events = [j1, v1, v2, d1, j2, t1, v3]
    for i, e in enumerate(events, 1):
        print(f"  {i}. {e.event.verb.value} | {e.event.nonce[:8]}... | {e.event.who[:20]} | {e.message[:50]}")

    print("
All events are strict JEP-04 compliant and can be fed into:")
    print("  - Determinability-Checker (causal sufficiency verification)")
    print("  - COE-Consensus (shared world state formation)")
    print("  - JEP-Guard-Audit (compliance chain generation)")
    print("=" * 70)


if __name__ == "__main__":
    run_complex_workflow()


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