#+TITLE: org-agent: The Neurosymbolic Kernel
#+AUTHOR: User
#+CREATED: [2026-03-17 Tue]
#+UPDATED: [2026-03-24 Tue]

A hyper-minimalist, self-editing, proactive AI agent framework. `org-agent` acts as the "executive soul" of a personal OS, using Org-mode as its native memory and Common Lisp as its deterministic reasoning engine.

* The Philosophy

** Mandate 1: Strictly Org-mode and Common Lisp
The system is built on a "No Legacy" policy. Markdown (.md) and JSON are strictly prohibited for internal system logic, planning, and memory. Org-mode is the native Abstract Syntax Tree (AST) for both human and machine, and Common Lisp (SBCL) is the deterministic reasoning engine.

** Mandate 2: Minimalist Core, Skill-Based Extension
The `org-agent` kernel (the Daemon) MUST remain a minimalist microkernel. It handles only the cognitive loop, the persistent Object-Store, and the communication protocol. All business logic, LLM provider connectors, and task-management rules MUST be implemented as hot-reloadable **Skills** living in the user's Memex.

** Why Org-mode? (Homoiconic Memory)
Most agent frameworks rely on a messy combination of Python scripts, JSON states, and Markdown prompts. This breaks the human-agent interface. JSON is for machines; Markdown is for humans. 

*Org-mode is for both.* It provides a rigorous, hierarchical Abstract Syntax Tree (AST) that a machine can navigate deterministically, while remaining a perfectly ergonomic, human-readable text document. In this system, your notes, your tasks, your prompts, and your agent's code all live in the exact same format.

** Why Common Lisp? (The Kernel vs. The Actuators)
The `org-agent` kernel is built in Common Lisp to provide a persistent, high-performance background process (SBCL) that maintains a live, threaded Object Store in RAM. It performs heavy neurosymbolic reasoning asynchronously, decoupled from any single user interface.

This architecture treats all interfaces as external **Actuators** and **Sensors**:
- **Editor Actuator (Emacs):** A sensor array that detects file changes and executes structural refactoring.
- **Messaging Actuator (Signal/Telegram/Discord):** A delivery channel for proactive alerts and human-in-the-loop decisions.
- **Web Actuator (Dashboard):** A visual telemetry interface for monitoring the live kernel state.

* The Paradigm: Skills vs. Sub-Agents

Modern AI frameworks heavily rely on "Sub-agents" (e.g., passing text between isolated Python scripts). `org-agent` fundamentally rejects this in favor of **Org-Native Skills**.

** The Performance Advantage (Single Address Space)
Following CLOSOS principles, the Lisp Machine architecture uses a **Single Address Space**. All applications (Skills) and the kernel share one unified memory space. We completely eliminate standard Inter-Process Communication (IPC) overhead. Objects are shared via direct pointers, meaning zero serialization/deserialization latency when moving from perception to thought.

** Specialization (System 1 Prompt Injection)
Instead of spinning up separate sub-agent processes with static prompts, the kernel dynamically injects the `:neuro-prompt` of the active skill into the LLM context. The LLM is temporarily "re-programmed" at runtime per task.

** Context Length & Memory (Peripheral Vision)
Multi-agent systems struggle with context bloat. `org-agent` solves this via its **Peripheral Vision API**. The Lisp Kernel uses `context-filter-sparse-tree` to surgically prune the Org AST, passing only the relevant hierarchical nodes to the LLM and preventing context-window overload.

** Responsiveness (Dual-Process Advantage)
The system employs a Dual-Process Architecture:
- **System 1 (Neural):** Probabilistic, slow, creative (LLM).
- **System 2 (Symbolic):** Deterministic, instant, rigorous (Lisp).
Because Skills are compiled Lisp code, System 2 intercepts deterministic tasks (like assigning an ID) and executes them in milliseconds, bypassing the LLM entirely.

* Architecture Diagrams

** The Single Address Space
#+begin_src mermaid
graph TD
    subgraph Lisp Machine (Single Address Space)
        K[Kernel Core] --> OS[(Object Store)]
        S1[Skill: Architect] --> OS
        S2[Skill: Analyst] --> OS
        S3[Skill: GTD] --> OS
        K -- Pointers --> S1
        K -- Pointers --> S2
    end
    subgraph IPC (Slow)
        E[Emacs Actuator] -. JSON .-> K
    end
#+end_src

** The Cognitive Loop (OODA)
#+begin_src mermaid
sequenceDiagram
    participant Sensor
    participant Kernel
    participant System1 as System 1 (LLM)
    participant System2 as System 2 (Lisp)
    participant Actuator
    
    Sensor->>Kernel: Perceive (Stimulus)
    Kernel->>System1: Think (Inject Prompt)
    System1-->>Kernel: Proposed Action
    Kernel->>System2: Decide (Safety Gate)
    alt Validation Failed
        System2-->>Kernel: Reject / Log Error
    else Validation Passed
        System2->>Actuator: Act (Dispatch)
    end
#+end_src

* The Architecture: The Cognitive Loop

The core engine is agnostic to both business logic and communication channels. It routes data through a strict four-stage cognitive pipeline:

1. **Perceive:** Sensors (Emacs, Webhooks, CRON) send updates over the Org-Agent Communication Protocol (OACP). The kernel updates its live Object Store.
2. **Think (System 1):** The `neuro.lisp` module queries an LLM (e.g., Gemini, OpenAI, or local models) based on the context, asking for an intuitive, pattern-matched suggestion. It returns an *unverified* proposed action.
3. **Decide (System 2):** The `symbolic.lisp` module is the absolute gatekeeper. It takes the LLM's proposal and runs it through strict Lisp constraints (e.g., "A parent task cannot be marked DONE if it has active TODO children"). If the logic fails, the LLM is overruled.
4. **Act:** Verified commands are dispatched to the appropriate Actuators (refactoring a buffer, sending a Signal message, or updating a database).

* Extensibility: The Org-Native Skill Standard

To keep the core microkernel minimal, all capabilities (API connectors, GTD logic, Atomic Notes (Zettelkasten) memory management) are abstracted into **Skills**.

Adhering to the Lisp Machine Mandate (Code is Data), a skill is not a Python folder. A skill is a single `.org` file located in the Atomic Notes (Zettelkasten) directory.

The kernel parses these `.org` files at startup, extracts the `#+begin_src lisp` blocks, and hot-loads them into the live system. You can define a System 1 Prompt and a System 2 Verification Rule entirely within your personal notes.

* Security & Isolation

Using `eval` on text generated by LLMs or extracted from text files is fundamentally dangerous. `org-agent` implements strict defense-in-depth:

** Layer 1: Lisp-Level Sandboxing
- **Reader Safety:** `*read-eval*` is strictly disabled during AST parsing, completely neutralizing reader macro injection attacks (`#.(uiop:run-program ...)`).
- **Package Jailing:** Every Org-Native skill is dynamically compiled into its own isolated Lisp package (`:org-agent.skills.<name>`). Skills cannot accidentally (or maliciously) overwrite the core System 2 gatekeeper or collide with other skills.

** Layer 2: OS-Level Containerization
The entire Common Lisp kernel can be isolated within a "Hardware Compartment" to protect the host OS.

* Documentation

Detailed specifications and planning documents are located in the [[file:docs/][docs/]] directory:
- [[file:docs/PRD.org][Product Requirements Document (PRD)]]
- [[file:docs/PROTOCOL.org][Communication Protocol (OACP)]]
- [[file:docs/PHASE_2_ROADMAP.org][Phase 2 Roadmap]]
- Specialized PRDs for [[file:docs/PRD_PROJECT_FOUNDRY.org][Project Foundry]], [[file:docs/PRD_ORG_DELIVERY.org][Org Delivery]], [[file:docs/PRD_LLM_CASCADE.org][LLM Cascade]], and more.

* Hardware Compartments (Deployment)

`org-agent` supports multiple levels of isolation. Choose the compartment that fits your security and performance needs. See the `deploy/` directory for templates.

** 1. Bare Metal
Run directly on your host CPU for maximum performance. Best for development.

** 2. Docker (Standard)
The default containerized experience.

** 3. LXC / Systemd-nspawn
Lightweight Linux containers with lower overhead than Docker.

** 4. Virtual Machines (Debian / Fedora)
Strong isolation using Vagrant/VirtualBox. Ensures zero-leakage from the Lisp machine.

** 5. Functional Deployment (Guix)
Reproducible, declarative environment management.

* Installation & Setup Guide

This guide covers the standard distributed deployment: running the `org-agent` daemon on a remote Docker server, connecting to it from your local Emacs instance, and configuring dynamic LLMs (like OpenRouter).

** Step 1: Server Setup (Global Docker Compose)
`org-agent` is designed to fit into a professional multi-app Docker environment.

1. **Clone the repository on your server:**
   #+begin_src bash
   git clone http://10.10.10.43:3000/amr/memex-amero.git /home/amr/memex
   #+end_src

2. **Configure your Environment (.env):**
   Place your `.env` file in `/docker/compose/` alongside your master `docker-compose.yml`.
   #+begin_src bash
   # Create /docker/compose/.env with your keys:
   # OPENROUTER_API_KEY=your_key_here
   # ORG_AGENT_DAEMON_PORT=9105
   # ORG_AGENT_WEB_PORT=8080
   # MEMEX_DIR=/memex
   #+end_src

3. **Integrate into Global Compose:**
   Add the following service fragment to your master file at `/docker/compose/docker-compose.yml`:
   #+begin_src yaml
   services:
     org-agent:
       build:
         context: /home/amr/memex/projects/org-agent
         dockerfile: deploy/docker/Dockerfile
       container_name: org-agent
       restart: unless-stopped
       ports:
         - "9105:9105"
         - "8080:8080"
       volumes:
         - /docker/memex:/memex
       env_file:
         - .env
   #+end_src

4. **Start the Service:**
   #+begin_src bash
   cd /docker/compose
   docker-compose up -d org-agent
   #+end_src

** Step 2: Local Emacs Setup (The Actuator)
Your laptop acts as the sensor/actuator array.

1. **Load the Emacs Package:**
   Evaluate the `org-agent.el` file in your local Emacs.
   #+begin_src elisp
   (add-to-list 'load-path "/path/to/local/org-agent/src")
   (require 'org-agent)
   #+end_src

2. **Configure the Connection:**
   Tell Emacs where your Docker server is located.
   #+begin_src elisp
   (setq org-agent-host "10.0.0.5") ;; Replace with your server's IP
   (setq org-agent-port 9105)
   #+end_src

3. **Connect to the Brain:**
   Run the interactive command to establish the OACP socket.
   `M-x org-agent-connect`

** Step 3: Dynamic Model Configuration (Homoiconic Setup)
`org-agent` does not use external JSON config files for its behavior. You configure the agent directly within your Org-mode Memex.

1. Open any `.org` file in your Memex (e.g., `settings.org`).
2. Add the following property to define your preferred model:
   #+begin_src org
   * Agent Settings
   :PROPERTIES:
   :LLM_MODEL_OPENROUTER: google/gemini-pro-1.5
   :END:
   #+end_src
3. **Save the buffer.** The agent instantly detects the change via Emacs, updates its internal Object Store, and routes all future neural thoughts through the selected model.

To see all available models, simply type `@agent list models` in any Org buffer and save.

* The Long-Term Vision: Orders of Autonomy

The development of `org-agent` follows distinct orders of autonomy, progressing from a basic assistant to a fully sovereign entity.

** Order 1: The Reactive Kernel (Phase 1 & 2)
The agent acts as a strict "Delegator." It requires human stimulus to trigger the Cognitive Loop. Capabilities (Skills) are expanded, but the agent only speaks when spoken to.

** Order 2: The Self-Editing Kernel (Phase 3 - Current)
The agent achieves introspection. It can "perceive pain" (errors) via system logs and trigger a `skill-self-fix` loop to rewrite its own source code, hot-reloading the changes. It proactively maintains the system.

** Order 3: The Sovereign Architect (Phase 4+)
The agent transitions to full autonomy. It maintains the Consensus Loop entirely, identifying structural decay in the Memex, drafting its own PRDs, writing code, executing Chaos testing, and committing the final result without human intervention (unless authorization gates are explicitly set).

* Current State: Order 2 Achieved

- DONE Core Lisp microkernel (Cognitive Loop: Perceive -> Think -> Decide -> Act)
- DONE OACP (Swank/Socket communication protocol) implemented
- DONE Org AST-to-Lisp conversion logic & Object Store integration
- DONE System 2 Safety Gating (The Harness) established
- DONE Org-Native Skill parsing and loading
- DONE Secure Docker containerization
- DONE Skill Graph & Recursive Dependencies (Ars Contexta)
- DONE Multi-Provider LLM Failover Cascade
- DONE Context API (Peripheral Vision)
- DONE Heartbeat Loop (Proactive Awareness)
- DONE Immune System (Autonomous Self-Repair)
- DONE Web Dashboard (Visual Telemetry)
- DONE Org-Native Multi-modal Delivery (Signal/Telegram/Discord)
- DONE Project Foundry (Autonomous Scaffolding & Git Stewardship)
- DONE Strictly Org-mode Mandate (.md purge)
