{
  "markdown": "# korg\n\n**A causally-ordered, rewindable event-ledger for autonomous AI agents.**\n*Every step your AI agent takes, recorded in a hash-chained ledger you can independently verify — tamper-evident, zero trust, no blockchain.*\n\n[![CI](https://github.com/New1Direction/korg/actions/workflows/ci.yml/badge.svg)](https://github.com/New1Direction/korg/actions/workflows/ci.yml)\n[![License: MIT OR Apache-2.0](https://img.shields.io/badge/license-MIT%2FApache--2.0-blue.svg?style=flat-square)](https://opensource.org/licenses/MIT)\n[![Rust 2021](https://img.shields.io/badge/rust-2021-93450a.svg?style=flat-square)](https://www.rust-lang.org)\n[![Tests](https://img.shields.io/badge/tests-175%20passing-brightgreen.svg?style=flat-square)](https://github.com/New1Direction/korg)\n\n<p align=\"center\">\n  <b>English</b> · <a href=\"README.zh-CN.md\">简体中文</a> · <a href=\"README.zh-TW.md\">繁體中文</a>\n</p>\n\n---\n\n![korg demo — record, verify, and rewind an AI agent session as a hash-chained ledger](demo.gif)\n\n---\n\n> AI agents are black boxes. When they fail, you can't debug. When they succeed, you can't reproduce it.\n> When they do something wrong, you can't undo it.\n>\n> **Korg fixes this.**\n\n---\n\n## What Korg Does\n\n> [!NOTE]\n> **Universal Ingestion Integration Mode:**\n> Korg v1 is an MCP-callable audit sink. Any MCP-compatible coding agent (Claude Code, Codex, etc.) can call korg's tools to record its session as a causally-linked, replayable, rewindable ledger. The agent must be instructed to log its actions — typically via system prompt or MCP server configuration. Fully passive auditing without agent cooperation is on the roadmap for future versions.\n\n> [!WARNING]\n> **Trust Boundary & Deployment Scope:**\n> Korg v1 is designed strictly for local, single-user workspaces. Multi-tenant and networked deployments require cryptographic authentication and permission bounds that are not yet shipped. Running the server on an untrusted or public network exposes workspace read/write access.\n\nKorg is a **cognitive hypervisor** — a runtime layer that sits beneath your AI agents and governs every decision they make.\n\nIt doesn't replace your LLM. It governs what the LLM does.\n\n```\nFoundation Model          →  predicts, suggests, generates\n────────────────────────────────────────────────────────────\nKorg Cognitive Runtime    →  schedules, validates, isolates,\n                             reconciles, replays, heals, governs\n```\n\nEvery agent action is:\n- **Appended** to an immutable, cryptographically-signed ledger\n- **Ordered** with Hybrid Logical Clocks (causal, deterministic, globally consistent)\n- **Replayable** — rebuild exact state at any point in history\n- **Reversible** — rewind the ledger to any prior sequence point\n\n---\n\n## Try the Time-Travel Demo\n\nYou can run the built-in sandbox demo to see cognitive time-travel in action. The demo sets up a temporary workspace with a buggy Python script, lets a simulated coding agent make a wrong edit, catches the test failure, rewinds the workspace and ledger to before the edit, and speculatively commits the correct fix:\n\n```bash\ncargo run -- demo\n```\n\nYou will see the complete, colorized time-travel sequence:\n\n```\n⚡ STARTING KORG COGNITIVE TIME-TRAVEL DEMO ⚡\n────────────────────────────────────────────────────────────────────────────────\n[korg] Initializing sandboxed demo environment...\n[korg] Created temporary workspace with math_utils.py (subtraction bug present).\n\n🚀 PHASE 1: AGENT INITIATES RUN (WRONG PATH)\n  [seq 390] actor: agent:claude-code@0.2.29 | tool: user_prompt | prompt: \"Fix subtraction bug and verify tests pass\"\n  [seq 391] actor: agent:claude-code@0.2.29 | tool: Read        | file: math_utils.py\n  [seq 392] actor: agent:claude-code@0.2.29 | tool: Edit        | result: \"Modified return a + b (wrong fix)\"\n  [seq 393] actor: agent:claude-code@0.2.29 | tool: Bash        | command: \"pytest\" -> ❌ FAILED (2 tests failed)\n\n📊 LEDGER STATE (BEFORE REWIND):\n  Before rewind: events 390-393 (prompt, read, edit-wrong, test-failed)\n    ├── seq 390 (user_prompt) -> triggered_by: None\n    ├── seq 391 (Read) -> triggered_by: Some(390)\n    ├── seq 392 (Edit) -> triggered_by: Some(391)\n    ├── seq 393 (Bash) -> triggered_by: Some(392)\n\n⏳ PHASE 2: INITIATING REVERSIBLE REWIND TO SEQ 391\n  [korg] Truncating journal ledger to sequence ID 391...\n  [korg] Restoring workspace snapshot via git read-tree (O(1))...\n  [korg] Reset math_utils.py file state back to sequence 391 bug state.\n  [korg] Rebuilding 3 read-model projections...\n\n📊 LEDGER STATE (AFTER REWIND):\n  After rewind:  events 390-391 (prompt, read)\n    ├── seq 390 (user_prompt) -> triggered_by: None\n    ├── seq 391 (Read) -> triggered_by: Some(390)\n\n🚀 PHASE 3: AGENT DIVERGES DOWN CORRECT PATH (SPECULATIVE REPLAY)\n  [seq 392] actor: agent:claude-code@0.2.29 | tool: Edit        | result: \"Modified return a - b (correct fix)\"\n  [seq 393] actor: agent:claude-code@0.2.29 | tool: Bash        | command: \"pytest\" -> ✓ PASSED (2 passed)\n\n📊 LEDGER STATE (AFTER DIVERGENT RUN):\n  After new run: events 390-393 (prompt, read, edit-right, test-passed)\n    ├── seq 390 (user_prompt) -> triggered_by: None\n    ├── seq 391 (Read) -> triggered_by: Some(390)\n    ├── seq 392 (Edit) -> triggered_by: Some(391)\n    ├── seq 393 (Bash) -> triggered_by: Some(392)\n\n✓ DEMO COMPLETE: Time-travel execution succeeded!\n  Ledger truncated, workspace rolled back, and a different future was successfully committed.\n```\n\n> *No other AI agent runtime lets you do this.*\n\n---\n\n## Core Architecture\n\nKorg is built on the same theoretical foundations that make databases and operating systems reliable — applied to AI cognition for the first time.\n\n| Invariant | What it means |\n|:---|:---|\n| **Append-only WAL** | Every cognitive event is a ledger entry. Nothing is mutated, only appended. Like a database WAL, but for AI thought. |\n| **HLC Causal Ordering** | Hybrid Logical Clocks guarantee globally consistent, causally ordered event streams — even across distributed swarm workers. |\n| **Deterministic Replay** | Any campaign can be replayed byte-for-byte from the ledger. Same inputs, same outputs, every time. |\n| **Speculative Branches** | Fork execution into parallel hypothetical paths. Preview before committing. Discard freely. |\n| **Execution Checkpoints** | Snapshot the entire runtime state: ledger offset, projection views, lease maps, workspace tree. Restore in O(1). |\n| **Micro-Healing** | Transient failures (lock conflicts, stale state) are automatically healed at the effect level, with full retry audit trails. |\n| **Semantic Governance** | Swarm actions are validated against BERT embedding cosine similarity — semantic alignment, not keyword matching. |\n\n```\n┌────────────────────────────────────────────────────────────────┐\n│  korg v0.1.0  │  session: 019e5333-efc9-7c70  │  ● ACTIVE      │\n├───────────────────────────────┬────────────────────────────────┤\n│  SWARM PLAN                   │  LIVE MERKLE LEDGER            │\n│  ├─ [●] Captain  [PLANNING]   │  (tx_00)→(tx_01)→[tx_02]→...  │\n│  ├─ [●] Harper   [RESEARCH]   │                                │\n│  ├─ [●] Benjamin [SYNTHESIS]  │  TELEMETRY                     │\n│  └─ [○] Lucas    [IDLE]       │  ├─ Velocity  85.2 t/s  ▇▆▄▂█  │\n│                               │  ├─ Entropy    0.451     ▄▃▂▃▄  │\n│  GOVERNANCE GATES             │  └─ Progress  68.7 %    ▂▃▄▅▆▇  │\n│  ├─ 🟡 Amber Security [IDLE]  │                                │\n│  ├─ 🟢 Consensus     [ACTIVE] │  LEDGER STREAM                 │\n│  └─ 🔵 Steering Fork [IDLE]   │  [tx_03] Benjamin: patch auth  │\n└───────────────────────────────┴────────────────────────────────┘\n```\n\n---\n\n## Quick Start\n\n### Build from source\n\nThe crate is not yet published to crates.io; install from source:\n\n```bash\ngit clone https://github.com/New1Direction/korg\ncd korg\ncargo build --release\n./target/release/korg --help\n```\n\n### Python bridge (for korgex / korgchat)\n\n```bash\ncd crates/korg-bridge\nmaturin develop  # builds the PyO3 extension into the active venv\npython3 -c \"import korg_bridge; print(korg_bridge.__version__)\"\n```\n\n### Run your first campaign\n\n```bash\n# Interactive TUI dashboard\nkorg campaign --tui --prompt \"Refactor the auth layer to use JWTs\"\n\n# Web cockpit at localhost:8080\nkorg campaign --web --prompt \"Optimize the database connection pool\"\n\n# Pure autonomous goal mode (--goal is a top-level flag)\nkorg --goal \"Write and validate a full test suite for src/parser.rs\"\n\n# Run the full multi-persona swarm on a REAL local model — every persona\n# (Captain, Harper, Benjamin, Lucas, Evaluator) runs as a real worker\n# subprocess doing real, measured, attested work. Defaults to a hermetic\n# deterministic provider; `--provider ollama` makes it live.\nkorg --goal \"Fix the failing test in src/lib.rs\" --provider ollama --model qwen2.5:7b\n\n# Preview without committing (dry-run; --preview is a top-level flag)\nkorg --preview \"Refactor the main event loop\"\n```\n\n### Rewind & Verify\n\n```bash\n# Rewind the capability journal to a specific ledger sequence point\nkorg rewind --seq 4\n\n# Drive the honest pipeline on a fixture and emit a verifiable ledger\nkorg run-once \"Fix the add function in src/lib.rs so it adds\"\n\n# Same pipeline, but with a REAL local model (ollama) on an arbitrary task —\n# the model writes the patch, Korg applies it, measures the real git diff +\n# `cargo check`, and attests only what actually changed.\nkorg run-once \"Fix the bug in src/lib.rs: max() returns the minimum.\nOutput the COMPLETE corrected src/lib.rs:\n\\`\\`\\`rust\n$(cat your-repo/src/lib.rs)\n\\`\\`\\`\" --repo your-repo --provider ollama --model qwen2.5:7b\n\n# Independently verify any korg-ledger@v1 journal (no trust in the producer)\nkorg-verify <path-to-ledger.jsonl>\n```\n\n> **Honest by construction, with any model.** The default provider is a hermetic\n> deterministic stub (fixture-only, zero dependencies). `--provider ollama` runs\n> a real local model on *arbitrary* tasks — Korg asks OpenAI-compatible providers\n> for strictly valid JSON (`response_format: json_object`), so even a small (7B)\n> local model lands a real patch reliably (measured 5/5 with qwen2.5:7b). Either\n> way the attestation is **measured, never fabricated**: when the model produces a\n> patch, the ledger attests the real `git diff` file count and changed paths; if\n> it declines or writes a non-compiling change, Korg reports it honestly (an\n> *honest null* — zero changed, zero attested — or a failed `cargo check`). The\n> pipeline cannot attest a number the worktree does not actually show — that is\n> the guarantee, independent of model quality.\n\n> **Verify it in your browser — sends nothing.** Zero-install, client-side\n> verifiers (Web Crypto) for any `korg-ledger@v1` journal or Certificate:\n> [verify a session](https://new1direction.github.io/korg/web/index.html) ·\n> [verify a Certificate](https://new1direction.github.io/korg/web/seal.html) ·\n> [time-travel explorer](https://new1direction.github.io/korg/web/explore.html).\n> They hash-chain, check the causal DAG, validate Ed25519 signatures, and\n> re-derive the human summary from the events — all locally.\n\n> Speculative branch/fork and named checkpoints (`korg fork`, `korg checkpoints\n> list|restore`) are planned, not yet shipped. The reversibility surface today is\n> `korg rewind`.\n\n---\n\n## Cognition Modes\n\nKorg adapts its intelligence tier based on task complexity. Modes are governed exclusively through the capability resolver — every switch is ledger-logged.\n\n| Mode | Best for |\n|:---|:---|\n| `instant` | Ultra-low latency. Bypasses negotiation. Optimistic execution. |\n| `balanced` | Default. Structured multi-round contract negotiation. |\n| `heavy` | Deep multi-agent deliberation. Multiple evaluation rounds. |\n| `research` | Wide divergent exploration. Semantic index scanning across all crates. |\n| `recovery` | Safe rollback mode. Creates checkpoints before every mutation. |\n| `autonomous` | Full goal-mode. Self-steering with automatic re-planning. |\n| `heavy-consciousness` | Maximum depth. Full HeavyConsciousness context injection. |\n\n```bash\nkorg --mode research \"Explore alternative approaches to the rate limiter\"\nkorg --mode recovery \"Carefully migrate the database schema\"\n```\n\n---\n\n## Why Korg Exists\n\nCurrent AI coding agents are probabilistic black boxes. They:\n- **Can't be replayed** — same prompt, different output, every time\n- **Can't be rewound** — one wrong action and you're manually diffing git history\n- **Can't be audited** — no record of what the agent decided and why\n- **Can't be governed** — no way to set policy boundaries at runtime\n\nKorg treats AI cognition the same way a hypervisor treats compute and Git treats code:\n\n> **If it's not in the ledger, it didn't happen.**\n\n---\n\n## Comparison\n\n| Capability | Korg | LangChain / LangGraph | CrewAI | Standard CLI Agents |\n|:---|:---:|:---:|:---:|:---:|\n| Deterministic replay | ✅ | ❌ | ❌ | ❌ |\n| Causal HLC ordering | ✅ | ❌ | ❌ | ❌ |\n| Rewind execution | ✅ | ❌ | ❌ | ❌ |\n| Speculative branches | 🚧 planned | ❌ | ❌ | ❌ |\n| Execution checkpoints | 🚧 planned | ❌ | ❌ | ❌ |\n| Cryptographic audit trail | ✅ | ❌ | ❌ | ❌ |\n| Independently-verifiable Certificate | ✅ | ❌ | ❌ | ❌ |\n| Honest attestation (real diff, never fabricated) | ✅ | ❌ | ❌ | ❌ |\n| Micro-healing | ✅ | ❌ | ❌ | ❌ |\n| Model-agnostic | ✅ | ✅ | ✅ | ✅ |\n\n> **Korg is not an agent framework. It's the governance kernel that runs beneath all of them.**\n\n---\n\n## Technical Stack\n\n| Component | Technology |\n|:---|:---|\n| Core runtime | Rust 2021, Tokio async |\n| Ledger ordering | Hybrid Logical Clocks (HLC) |\n| Workspace snapshots | Git Merkle tree (O(1) restore via `write-tree` / `read-tree`) |\n| Cryptographic attestation | Ed25519 (ed25519-dalek) |\n| Semantic governance | BERT cosine similarity via the optional `candle` feature (Hugging Face); a deterministic embedding fallback runs when `candle` is not built |\n| TUI dashboard | Ratatui + Crossterm |\n| Web cockpit | Axum + SSE |\n| Syntax highlighting | Syntect + tree-sitter |\n\n---\n\n## Architecture Deep Dive\n\n→ **[Read the full technical write-up](https://github.com/New1Direction/korg/blob/main/ARCHITECTURE.md)**\n\n### Real-World Audit Ledger Example\nYou can inspect a real-world cognitive audit ledger produced by Korg. This NDJSON file records a live session where Claude Code was prompted to call Korg's MCP tools to refactor a function and rename all call sites, capturing the full HLC causal graph and `actor_id` recorder metadata:\n* **[Claude Code Session Causal Ledger (NDJSON)](examples/claude_code_session_ledger.json)**\n\nThe short version:\n\n1. **CapabilityResolver** — the single authority for all runtime state. All reads and writes flow through it. No secondary state stores.\n2. **CapabilityJournal** — the append-only WAL. Every cognitive event is sealed here with an HLC timestamp, causation chain, and cryptographic signature.\n3. **ProjectionEngine** — pure state folds over the journal. Any read model can be rebuilt deterministically from the raw event stream.\n4. **ExecutionCheckpoint** — snapshot of `{ledger_offset, projection_state, lease_map, workspace_tree_hash}`. Restores full runtime state in O(1) without replaying the entire event stream.\n5. **CapabilityExecutor** — executes the physical effect DAG. Failures trigger automatic micro-healing before escalating.\n\n### System overview\n\n```mermaid\nflowchart TD\n    Agent[\"MCP-compatible agent<br/>(Claude Code, Codex, korgex)\"]\n\n    subgraph Ingest[\"Ingestion paths\"]\n        MCP[\"mcp_server.py<br/>(MCP / JSON-RPC stdio sink)\"]\n        Bridge[\"korg-bridge<br/>(PyO3 in-process writer)\"]\n        Server[\"korg-server<br/>(Axum HTTP + SSE)\"]\n    end\n\n    Journal[\"korg-registry · CapabilityJournal<br/>append-only WAL · HLC order · triggered_by DAG\"]\n    Chain[\"korg-ledger@v1<br/>hash-chain: prev_hash to entry_hash<br/>SHA-256 / HMAC + Ed25519\"]\n    Projection[\"ProjectionEngine<br/>pure folds to read models\"]\n    Rewind[\"rewind / rewind_with_seal<br/>truncate to seq + LedgerRewind tip\"]\n    Verify[\"korg-verify (+ Python / JS)<br/>verify_chain · verify_dag · sig · Certificate\"]\n    Runtime[\"korg-runtime<br/>multi-persona swarm · git-worktree sandbox<br/>arena · evaluator · run_once\"]\n\n    Agent --> MCP --> Journal\n    Agent --> Bridge --> Journal\n    Agent --> Server --> Journal\n    Runtime --> Journal\n    Journal --> Chain\n    Journal --> Projection\n    Journal --> Rewind\n    Rewind --> Projection\n    Chain --> Verify\n```\n\n---\n\n## Status\n\nKorg is in active development, built on a **frozen `korg-ledger@v1` spec with cross-language conformance** (Rust + Python + JS). Test footprint: **300+ Rust tests across the workspace plus Python/JS conformance suites**, CI-gated (build · tests · cross-language oracle · differential fuzz) and green on `main`.\n\n**Shipped:**\n- [x] Append-only, hash-chained cognitive ledger with HLC ordering\n- [x] Deterministic replay and projection rebuilds\n- [x] Reversible execution — rewind the ledger to any prior sequence point (tamper-evident `LedgerRewind`)\n- [x] Per-event Ed25519 signatures + structural anchoring (`korg-ledger@v1` §8)\n- [x] **Certificate (`korgcert@v1`)** — a public, independently-verifiable certificate of agent work, with zero-install in-browser verifiers\n- [x] **Honest pipeline** (`korg run-once`) — real patch → real `cargo check` → an attested mutation count that equals the real `git diff`; never fabricates (reports an honest null instead)\n- [x] **Live local model** (`--provider ollama`) — real per-persona work on arbitrary tasks\n- [x] **Multi-agent swarm** (Captain, Harper, Benjamin, Lucas, Evaluator) — genuine worker subprocesses doing real, measured, attested work with DAG data-flow between personas\n- [x] Zero-config Claude Code capture (PostToolUse/Stop hooks → verifiable per-session ledgers)\n- [x] Micro-healing effect layer · TUI dashboard + Web cockpit\n- [x] Cryptographic provenance attestation · single-authority CognitionMode governance\n- [x] Preview / dry-run mode (`--preview`)\n\n**Planned / not yet shipped:**\n- [ ] Speculative branches / fork + execution-checkpoint restore CLI (primitives exist; CLI planned)\n- [ ] `cargo install korg` on crates.io · npm-published verifier\n- [ ] Live network anchoring resolver (trusted-time witness — the remaining honest limit)\n- [ ] Remote swarm workers · WASM backends · IDE language-server integration · distributed checkpoint sync\n- [ ] Fully passive capture without agent cooperation\n\n---\n\n## License\n\nLicensed under either of [MIT](LICENSE-MIT) or [Apache-2.0](LICENSE-APACHE) at your option.\n\n---\n\n<p align=\"center\">\n  <sub>Built with Rust. Governed by invariants. No black boxes.</sub>\n</p>",
  "bytes": 18598,
  "sha": "0502f62d934d77cd4f43bf9e80bad0cda87037fef84f275a9db9057e1fc0f532",
  "repo_slug": "new1direction/korg",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_new1direction_korg_introspect__5d1724e1/readme"
}