Metadata-Version: 2.4
Name: conceptkernel
Version: 1.3.0
Summary: CKP v3.5 Python runtime — kernel processor, provenance, execution proofs
Author-email: Peter Styk <peter@conceptkernel.org>
License: MIT
Project-URL: Homepage, https://conceptkernel.org
Project-URL: Repository, https://github.com/ConceptKernel/CK.Lib.Py
Project-URL: Ontology, https://conceptkernel.org/ontology/v3.5-alpha6/
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: serve
Requires-Dist: fastapi>=0.100; extra == "serve"
Requires-Dist: uvicorn>=0.23; extra == "serve"
Requires-Dist: pyjwt>=2.8; extra == "serve"
Requires-Dist: httpx>=0.25; extra == "serve"
Requires-Dist: cryptography>=41.0; extra == "serve"
Provides-Extra: nats
Requires-Dist: nats-py>=2.6; extra == "nats"
Provides-Extra: yaml
Requires-Dist: pyyaml>=6.0; extra == "yaml"
Dynamic: license-file

# CK.Lib.Py — CKP v3.5 Python Runtime

Python runtime for the [Concept Kernel Protocol](https://conceptkernel.org) (CKP v3.5).

## What This Is

Every Concept Kernel that runs Python uses CK.Lib.Py. It provides:
- Base processor class that reads `conceptkernel.yaml` and dispatches NATS messages to `@on` handlers
- Instance lifecycle (create, seal, proof) following the three-loop model
- PROV-O provenance recording for every action
- Action composition via edge predicates (COMPOSES/EXTENDS/TRIGGERS)
- RBAC grants checking against `conceptkernel.yaml` grants block
- URN parsing, validation, and building per CKP URN scheme

## Architecture — Where Things Run

```
CLUSTER / LOCAL MACHINE (Python, nats-py)       BROWSER / MOBILE (JS, nats.ws)
─────────────────────────────────────────       ──────────────────────────────────
CK.Lib.Py                                       CK.Lib.Js
  KernelProcessor                                  CKClient (ck-client.js)
  NatsKernelLoop (nats-py)                         NATS WSS (nats.ws)
  instance.py (writes to storage/)                 CKPage (ck-page.js)
  prov.py (PROV-O chains)                          CKBus (ck-bus.js)
  actions.py (edge composition)                    CKRegistry (ck-registry.js)
         │                                                │
         │  NATS (nats:// or wss://)                      │  NATS WSS only
         │  Subject: input.{KernelName}                   │  Subject: input.{KernelName}
         └──────────────── NATS SERVER ───────────────────┘
                    wss://stream.tech.games
                    JWT auth via Keycloak
```

**Python kernels** run on the cluster or local machine. They connect to NATS via `nats-py` (native TCP or WSS). They have filesystem access to their `storage/` directory. They write instances, proofs, and ledger entries.

**JavaScript clients** run in the browser or CLI. They connect to NATS via `nats.ws` (WebSocket only). They have NO filesystem access. They send action messages and receive results. They are `ckp:InlineKernel` / `ckp:NATSBrowserClient` per the published ontology.

**Messages are identical** regardless of sender. A `{ "action": "scout.scan" }` published to `input.Delvinator.ThreadScout` produces the same result whether it came from a Python kernel, a JS browser, or `delvinator.sh`.

## Ontology Grounding

**Published ontology:** https://conceptkernel.org/ontology/v3.5-alpha6/

| CK.Lib.Py concept | Published class | Module |
|-------------------|----------------|--------|
| `KernelProcessor` | `ckp:Kernel` (bfo:MaterialEntity + cco:Agent) | core.ttl |
| `@on("action")` handler | `ckp:Action` (iao:PlanSpecification) | core.ttl |
| `create_instance()` | `ckp:InstanceManifest` (iao:DataItem) | base-instances.ttl |
| `seal_instance()` | `ckp:SealedInstance` | base-instances.ttl |
| `append_ledger()` | `ckp:LedgerEntry` | base-instances.ttl |
| proof.json generation | `ckp:ProofRecord` + `ckp:ProofCheck` | proof.ttl |
| `ProvChain` sessions | `prov:Activity` chain | proof.ttl + PROV-O |
| Edge composition | `ckp:Edge` + `ckp:RelationshipType` | core.ttl |
| Grants/RBAC | rbac.ttl agents, roles, permissions | rbac.ttl |
| `NatsKernelLoop` | `ckp:NATSListening` (ServingDisposition) | kernel-metadata.ttl |
| URN scheme | CKP URN pattern (17 entity types) | core.ttl |

**Published ontology modules (all live at alpha-6 endpoint):**

| Module | URL | What it defines |
|--------|-----|-----------------|
| core.ttl | [link](https://conceptkernel.org/ontology/v3.5-alpha6/core.ttl) | Kernel, Edge, Instance, Action, Project, GovernanceMode |
| base-instances.ttl | [link](https://conceptkernel.org/ontology/v3.5-alpha6/base-instances.ttl) | InstanceManifest, SealedInstance, LedgerEntry |
| proof.ttl | [link](https://conceptkernel.org/ontology/v3.5-alpha6/proof.ttl) | ProofRecord, ProofCheck, CheckType |
| kernel-metadata.ttl | [link](https://conceptkernel.org/ontology/v3.5-alpha6/kernel-metadata.ttl) | ServingDisposition (NATSListening, NATSBrowserClient, WebServing, APIServing), StorageMedium, DeploymentMethod |
| processes.ttl | [link](https://conceptkernel.org/ontology/v3.5-alpha6/processes.ttl) | Invocation, EdgeCommunication, Consensus |
| relations.ttl | [link](https://conceptkernel.org/ontology/v3.5-alpha6/relations.ttl) | Edge properties, belongsToProject, hasKernel |
| rbac.ttl | [link](https://conceptkernel.org/ontology/v3.5-alpha6/rbac.ttl) | Authorization: agents, roles, permissions, quorum |
| workflow.ttl | [link](https://conceptkernel.org/ontology/v3.5-alpha6/workflow.ttl) | Workflow execution patterns |
| self-improvement.ttl | [link](https://conceptkernel.org/ontology/v3.5-alpha6/self-improvement.ttl) | Validation, recommendations, governance roles |
| shapes.ttl | [link](https://conceptkernel.org/ontology/v3.5-alpha6/shapes.ttl) | SHACL validation shapes |

## Modules

| Module | What it does | Key functions/classes |
|--------|-------------|---------------------|
| `processor.py` | Base class for all kernel processors. Reads `conceptkernel.yaml`, dispatches via `@on`, CLI args (`--status`, `--listen`, `--serve`, `--action`) | `KernelProcessor`, `KernelProcessor.run()` |
| `events.py` | Action handler decorator and typed event emission | `@on("action.name")`, `emit("EventType", **kwargs)` |
| `instance.py` | Instance lifecycle following the three-loop DATA pattern. Creates `storage/instances/i-{id}/` with manifest.json, seals with data.json, generates proof.json (SHA-256) | `create_instance()`, `seal_instance()`, `append_ledger()` |
| `execution.py` | Multi-step execution proofs with hash chains. Each step's input/output is SHA-256 hashed and chained to the previous step | `hash_step()`, `build_execution_proof()`, `seal_execution()`, `verify_chain()` |
| `prov.py` | PROV-O session recording. Every action in a session produces an `ActionRecord` with URNs linking Action → Instance → Task → Goal | `ProvChain`, `Session`, `ActionRecord`, `verified_action()` |
| `actions.py` | Action type resolution (`inspect`, `check`, `mutate`, `operate`, `query`, `deploy`, `transfer`). RBAC grants checking. Edge composition (COMPOSES/EXTENDS materialization) | `resolve_action_type()`, `check_access()`, `resolve_composed_actions()`, `get_effective_actions()` |
| `dispatch.py` | Local inter-kernel action dispatch and FIFO queue. For cluster/local — bypasses NATS for direct invocation | `send_action()`, `queue_action()`, `run_queue()` |
| `serve.py` | FastAPI HTTP server wrapping `@on` handlers. Token auth via Keycloak JWT or API key | `KernelServer` |
| `auth.py` | Keycloak JWT verification + API token fallback | `CKAuth` |
| `entities.py` | In-memory entity store with code-based lookup (for kernels that manage named entities) | `EntityManager` |
| `urn.py` | CKP URN parser, validator, builder. 17 entity types. Fleet-wide validation | `parse_urn()`, `validate_urn()`, `build_urn()`, `validate_fleet()` |

## The Three-Loop Contract

CK.Lib.Py enforces the CKP three-loop separation:

```
CK LOOP (identity — read by KernelProcessor.__init__)
│  conceptkernel.yaml → self.identity, self.name, self.urn
│  ontology.yaml → defines what instances look like (the TYPE)
│  rules.shacl → validation constraints
│  CLAUDE.md, SKILL.md → for Claude Code agents
│
│  KernelProcessor READS these. It NEVER WRITES them.
│  Tool loop cannot modify CK loop — enforced by code structure.
│
TOOL LOOP (execution — this is where processor.py runs)
│  @on("action") handlers process input and return dicts
│  The handler NEVER opens storage/ for writing
│  It returns data; NatsKernelLoop handles storage writes
│
DATA LOOP (results — written by NatsKernelLoop or instance.py)
   storage/instances/i-{trace}-{ts}/
     manifest.json   ← create_instance()
     data.json        ← seal_instance()
     proof.json       ← seal_instance() generates proof
     ledger.json      ← append_ledger()
```

## How a Kernel Processor Works

```python
from cklib import KernelProcessor, on, emit

class MyKernel(KernelProcessor):
    """Processor reads conceptkernel.yaml on init.
    Exposes @on handlers that match spec.actions.
    Returns dicts — never writes to storage directly."""

    @on("my.action")
    def handle(self, data):
        # data = the message body from NATS or CLI
        # Process...
        result = {"answer": 42}
        # Return typed event — NatsKernelLoop writes the instance
        return emit("ActionCompleted", result=result)

if __name__ == "__main__":
    MyKernel.run()
    # CLI: python processor.py --status
    #       python processor.py --action my.action --data '{"key": "value"}'
    #       python processor.py --listen    (NATS subscriber mode)
    #       python processor.py --serve     (HTTP API mode)
```

## NATS Processing Cycle

When `--listen` is invoked, `NatsKernelLoop` (from `nats_kernel.py`) runs:

```
1. Connect to NATS WSS (wss://stream.tech.games)
2. Subscribe to input.{KernelName}
3. For each message:
   a. Parse headers (Trace-Id, X-Kernel-ID, X-User-ID)
   b. Parse body as JSON
   c. Dispatch to handle_message() → @on handler
   d. Write instance to storage/instances/i-{trace}-{ts}/message.json
   e. Publish result to result.{KernelName}
   f. Publish event to event.{KernelName} (type: "instance_created")
```

Instance creation happens INSIDE the NATS loop — the handler just returns data. This is the three-loop isolation: tool returns, platform writes.

## Related Repositories

| Repo | Purpose | URL |
|------|---------|-----|
| **CK.Lib.Js** | JavaScript/browser client — CKPage, NATS WSS, web components | [ConceptKernel/CK.Lib.Js](https://github.com/ConceptKernel/CK.Lib.Js) |
| **CK.ComplianceCheck** | Fleet validation — 20 CKP check types | [ConceptKernel/CK.ComplianceCheck](https://github.com/ConceptKernel/CK.ComplianceCheck) |
| **CK.Operator** | Platform reconciliation | [ConceptKernel/CK.Operator](https://github.com/ConceptKernel/CK.Operator) |
| **Ontology** | Published CKP v3.5-alpha6 (10 Turtle modules) | [conceptkernel.org/ontology/v3.5-alpha6/](https://conceptkernel.org/ontology/v3.5-alpha6/) |

## License

MIT
