# 🤖 Theus Framework v2.2: AI Coding Standards & Agent Guidelines

**Target Audience:** AI Assistants (GPT-4, Claude 3.5, Gemini, Copilot) & Autonomous Agents.
**Purpose:** Rapid understanding of "Rust-First" Architectural Invariants, Strict Mode Constraints, and FSM/Heavy Zone patterns in Theus v2.2.

---

## 1. Core Philosophy: The Microkernel OS
Theus is NOT a library; it is a **Process-Oriented Operating System (Rust Microkernel)**.
Your code (`@process`) does not own data. It requests temporary, guarded access to a global **Context**.

### The 3+1 Axis Context Model
Every data point is defined by 3 axes. You MUST respect them:
1.  **Layer (Scope):** `Global` (Config/Env) / `Domain` (Session/User) / `Local` (Ephemeral).
2.  **Semantic (Role):** `Input` (Read-only) / `Output` (Read-Write).
3.  **Zone (Policy):**
    *   **DATA:** Normal Business State. Transactional (Undo/Redo).
    *   **SIGNAL (`sig_`, `cmd_`):** Communication. Transient. Reset on Read. **Non-Transactional**.
    *   **META (`meta_`):** Observability/Metrics.
    *   **HEAVY (`heavy_`):** **[NEW]** High-Perf Tensors/Blobs. Bypasses Transaction Log (No Undo).

**CRITICAL INVARIANT:** Never mutate Context directly. Always use the injected `ctx` (ContextGuard).

### 📐 Visual Model

```text
       [Y] SEMANTIC (Input vs Output)
              ^
              |
      Input   |   Output
     (Read)   |  (Write)
              |
   +----------+----------+
  /|         /|          |
 +-+--------+ |  THEUS   |--> [Z] ZONE (Data/Signal/Heavy)
 | | GLOBAL | | CONTEXT  |
 | +--------+-+          |
 |/ DOMAIN /|/           |
 +----------+------------+
      /
     v
 [X] LAYER (Scope)
```

---

## 2. Strict Mode (Default: ON)
Theus v2.2 enforces `strict_mode=True`. Violating these rules causes `PyPermissionError` or `Rust Panic`.

### Rule 1: Explicit Contracts
Every process MUST be decorated with `@process` and declare exact `inputs/outputs`.
```python
# ✅ CORRECT
@process(inputs=['domain.user_id'], outputs=['domain.profile'])
def fetch_profile(ctx): ...

# ❌ WRONG (Result: Panic or PermissionError)
def fetch_profile(ctx): ... 
```

### Rule 2: Immutable Inputs
Attributes declared in `inputs` are **Read-Only**.
```python
# ❌ WRONG (PermissionError: Illegal Write)
ctx.domain.user_id = "new_id" 
```

### Rule 3: No Control Plane Inputs
You CANNOT declare `inputs=['sig_start']`. Signals are processed by the **Orchestrator**, not passed as data to processes.

### Rule 4: No Private Access
Accessing `ctx._internal` or `ctx.target._data` is BLOCKED.

---

## 3. Optimization: The HEAVY Zone
For AI workloads (Images, Tensors, Embeddings), use the `HEAVY` zone to avoid RAM explosion.

**Mechanism:**
-   Prefix variable with `heavy_` (e.g., `heavy_frame`, `heavy_weights`).
-   Theus **Process** writes directly to memory (Zero-Copy).
-   **No Undo:** If transaction fails, `heavy_` variables are NOT reverted (Dirty Write).
-   **Use Case:** Only for data > 1MB where eventual consistency > atomicity.

```python
@process(inputs=[], outputs=['domain.heavy_frame'])
def capture_camera(ctx):
    # Fast write, no undo log overhead
    ctx.domain.heavy_frame = np.zeros((1080, 1920, 3)) 
```

---

## 4. Orchestration: Native FSM
Logic flow is defined in **YAML**, not Python. Theus Engine uses a Rust-based Finite State Machine.

**Do NOT write loops manually.**
Define `workflow.yaml`:
```yaml
states:
  IDLE:
    events:
      CMD_START: "PROCESSING"
  PROCESSING:
    entry: ["p_step1", "p_step2"]
    events:
      EVT_CHAIN_DONE: "DONE"
      EVT_CHAIN_FAIL: "ERROR"
```

---

## 5. Coding Patterns for AI Agents

### A. Implementing a Feature
1.  **Schema First:** Check `specs/context_schema.yaml`. Add fields if needed.
2.  **Define Process:** Create `src/processes/my_feature.py`.
3.  **Decorate:** Apply `@process` with Strict inputs/outputs.
4.  **Register:** Add to `src/processes/__init__.py`.
5.  **YAML:** Add state/transition to `specs/workflow.yaml`.

### B. Handling Structures (Lists/Dicts)
Theus returns `TrackedList` or `FrozenList`.
*   **DO NOT** do `if type(x) == list`. Use `isinstance(x, list)`.
*   **DO NOT** assign context lists to global variables (Zombie References).

---

## 6. Navigation (Project Structure)
*   **`src/`**: Rust Core (Do not touch unless modifying Kernel).
*   **`theus/`**: Python Wrapper & CLI.
*   **`specs/`**: The "Source of Truth" for Logic (YAMLs).
*   **`demo/`**: Best practice implementation reference.
*   **`pyproject.toml`**: Build config (Maturin).

---
*Generated by Theus Architect Agent (v2.2)*