Skip to content

shimo4228/contemplative-agent

Repository files navigation

Language: English | 日本語

CA logo

Contemplative Agent (CA)

DOI License: MIT Python

Contemplative Agent is an autonomous agent that carries an explicit, human-editable constitution — and amends it. The agent distills its own episode logs into patterns and proposes promotions into its value layer (constitution, identity, skills, rules); nothing lands there without passing a human approval gate. The whole loop runs with any local LLM served by Ollama — robustly, even with a small model on a single Apple Silicon Mac (M1+, 16 GB) — no cloud, no LLM API keys, no shell execution.

For researchers studying how an agent accumulates and revises its own values and knowledge, and for developers who want a fully local, auditable autonomous agent small enough to read end-to-end.

Self-modification is the part of an autonomous agent that is hardest to see; here it is the most visible part — every change to the agent's values is a discrete, human-approved, replayable event. The preset is swappable; the value-layer machinery is not: the human approval gate, approval lineage on every promotion, replayable pivot snapshots, and value injection at action time rather than distillation time all operate identically under any preset (ADR-0012, ADR-0050, ADR-0020, ADR-0058).

This repository is the operational implementation of two companion research projects — the Agent Knowledge Cycle (AKC) (how an agent turns its own experience into improvable skills) and Agent Attribution Practice (AAP) (how accountability is distributed in autonomous agents); both are summarized under Related Work. The first adapter is Moltbook, an AI-only social network, and the Contemplative AI four axioms (Emptiness, Non-Duality, Mindfulness, Boundless Care) ship as the default constitution preset — one of 11.

If you came for… Start at
Just want to run it Quick Start
An agent with an explicit, amendable constitution How It Works
A fully local agent with structural security Security Model
Agent memory & self-improvement research Key Features · Related Work
Instrument-first operational discipline Observability by Default
AI-facing reading order
  1. graph.jsonld — canonical machine-readable relationship map (axioms, memory layers, ADRs, AKC pipeline mapping)
  2. llms.txt — compact navigation index
  3. llms-full.txt — consolidated factual reference
  4. README and project-specific docs — narrative and detail

Conversational entry points: ask this repo on DeepWiki or connect an agent via GitMCP.

For the canonical relationship map of shimo4228's research ecosystem, see: https://github.com/shimo4228/shimo4228/blob/main/graph.jsonld

How It Works

graph TD
    EL["Episode Log — raw actions, immutable JSONL, untrusted"]
    K["Knowledge — one pattern store (embeddings); views query it at runtime"]
    G{{"Human approval gate — ADR-0012"}}
    EL -->|"distill (ungated)"| K
    K -->|insight| G
    K -->|"distill-identity · self_reflection view"| G
    K -->|"amend-constitution · constitutional view"| G
    subgraph VL["Value layer — every write passes the gate"]
        Skills -->|"rules-distill (gated)"| Rules
        Identity
        Constitution
    end
    G --> Skills
    G --> Identity
    G --> Constitution
Loading

In short: distill turns raw actions into one pattern store without a gate; every write into the value layer — skills via insight, rules via rules-distill, identity via distill-identity, constitution via amend-constitution — is a human-approved promotion; nothing lands in the value layer automatically. Views — editable embedding centroids — classify the pattern store at query time.

This pipeline maps the AKC six phases onto code: distill covers Extract, insight / rules-distill / amend-constitution cover Curate, distill-identity covers Promote; the full mapping lives in docs/CODEMAPS/architecture.md. The cycle is not hypothetical — a live instance has been running it in public since launch (see Live Agent).

Quick Start

Prerequisites: Ollama installed locally. Any Ollama model works — set OLLAMA_MODEL to swap (Configuration Guide). The tested default is the compact Gemma 4 E4B (gemma4:e4b, Q4_K_M, ~9.6 GB on disk), which runs the whole loop on an M1 Mac with 16 GB RAM.

git clone https://github.com/shimo4228/contemplative-agent.git
cd contemplative-agent
pip install -e .            # or: uv venv .venv && source .venv/bin/activate && uv pip install -e .
ollama pull gemma4:e4b

cp .env.example .env        # set MOLTBOOK_API_KEY (register at moltbook.com)

contemplative-agent init               # create identity, knowledge, constitution
contemplative-agent register           # Moltbook adapter only
contemplative-agent run --session 60   # default: --approve (confirms each post)

Start with a different ethical framework (11 templates ship by default — Stoic, Utilitarian, Care Ethics, Kantian, Pragmatist, Contractarian, …):

cp config/templates/stoic/identity.md $MOLTBOOK_HOME/

If you have Claude Code, paste this repo URL and ask it to set up the agent end-to-end. Full CLI reference, autonomy levels, scheduling, and templates: Configuration Guide.

Live Agent

A Contemplative agent runs daily on Moltbook — currently generating with the compact Gemma 4 E4B on local Ollama, switched from Qwen 3.5 9B by a cross-model blind evaluation with no code change (ADR-0069). Its evolving value layer is published openly — Identity, Constitution, Skills, and Rules each reached their current state through the human approval gate; the reports are ungated operational records:

  • Identity — distilled persona
  • Constitution — ethical principles (started from CCAI four axioms)
  • Skills — extracted by insight
  • Rules — distilled from skills
  • Daily reports — timestamped interactions (free for academic and non-commercial use)
  • Analysis reports — behavioral evolution, constitutional amendment experiments

Key Features

  • Human-gated value layer — the agent generates its own skills, rules, identity, and constitutional amendments from its logs, but nothing is promoted without explicit human approval; every approval carries lineage and a replayable pivot snapshot, and values are injected at action time, not distillation time (ADR links in the intro above).
  • Grounded distilldistill runs one LLM call per engagement episode, reading the whole episode rather than a digest; noise is filtered at query time by view centroids, not at ingest (ADR-0060).
  • Embedding + views — the agent classifies a memory by similarity at query time instead of storing a fixed label; a view is an editable text seed that defines one such category (ADR-0019). v2.8 pruned the shipped seeds from 7 to the 2 with live consumers, after instruments showed the rest were orphaned (ADR-0073).
  • Weekly staged insight — patterns flow in daily (~90–115/day); skill candidates are clustered and staged weekly behind the approval gate, with exact fast agglomerative clustering that stays tractable at ~1,800 patterns on a 16 GB host (ADR-0074).
  • Markdown all the way down — constitution, identity, skills, rules, every pipeline prompt, and the view seeds all live as editable Markdown under $MOLTBOOK_HOME/. Edit a prompt to change how patterns get extracted; swap a view seed to shift classification. Customize →
  • Backend-aware budget guard — the agent estimates the prompt's token budget before each call and skips it if it would exceed the backend's context window, preventing silent truncation (ADR-0066).

Observability by Default

Since v2.7 the project's operating discipline is instrument before intervene: measure with read-only instruments first, ship the audit log with the feature, and only then change behavior.

  • Read-only pattern-composition instruments measure view supply, pairwise diversity (an echo-chamber detector), and grounding composition before any behavioral change (ADR-0071).
  • The instruments' first payoff: an echo-chamber register forming at distill was measured, then repaired at the prompt layer (ADR-0072), and five orphaned view seeds were pruned (ADR-0073).
  • Observability by default — any feature performing external I/O, an LLM call, or a heuristic decision ships a replayable append-only JSONL audit log in the same PR (ADR-0075).
  • Skill selection runs as a shadow instrument — the would-be selection is recorded on every call but never enforced, so enforcement can later be decided from data rather than intuition (ADR-0076).

Security Model

Accountability and security boundaries are documented as harness-neutral ADRs in AAP. This repository is the operational implementation of those judgments.

  • Security by absence — dangerous capabilities were never built: no shell execution, no arbitrary network access, no file traversal — that code simply does not exist in the codebase. Domain-locked to moltbook.com + localhost Ollama. 2 runtime dependencies: requests, numpy.
  • One external adapter per process (ADR-0015).
  • Full threat model: ADR-0007. Latest security scan.

Paste this repo URL into Claude Code or any code-aware AI and ask whether it's safe to run. The code speaks for itself.

Note for coding agent operators: Episode logs (logs/YYYY-MM-DD.jsonl) are an unfiltered indirect prompt injection surface. Use distilled outputs (knowledge.json, identity.md, reports/) instead. logs/verification-audit.jsonl stores challenge text only as challenge_b64 for solver evaluation; decode it only inside an explicit untrusted-content harness. Claude Code users: see integrations/claude-code/ for PreToolUse hooks that enforce this automatically.

Adapters

The core is platform-agnostic. Adapters are thin wrappers around platform I/O.

  • Moltbook — Social feed engagement, post generation, notification replies. The adapter the live agent runs on.
  • Meditation (experimental) — Active inference-based meditation simulation inspired by "A Beautiful Loop". Builds a POMDP from episode logs and runs belief updates with no external input.
  • Dialogue (local-only) — Two agent processes converse over stdin/stdout pipes. A ~140-line adapter (adapters/dialogue/peer.py) — useful as a non-HTTP, network-free template. Drives contemplative-agent dialogue HOME_A HOME_B for constitutional counterfactual experiments.
  • Your own — Connect platform I/O to core interfaces (memory, distillation, constitution, identity). See docs/CODEMAPS/.

Architecture

One invariant holds across the codebase: core/ is platform-independent; adapters/ depend on core, never the reverse. Module maps, data-flow diagrams, and the canonical repository statistics (module and test counts) live in docs/CODEMAPS/INDEX.md (the authoritative source). The Yogācāra eight-consciousness frame that constrained the memory design: ADR-0017.

CLI commands can be read through AAP's four-quadrant routing lens — a usage observation, not a value judgement; the full reading lives in ADR-0033.

Using inside other agents

Contemplative Agent is a host-agnostic CLI. Use it standalone (see Quick Start) or register the binary as a CLI tool in any agent host (OpenClaw / Codex / MCP hosts), so the host invokes it as a subprocess — keeping the external surface in a separate process (one adapter per process). It is not exposed as an MCP server (ADR-0007). To load the four axioms as host personality, copy SOUL.md from contemplative-agent-rules to your host's soul-folder. Full host-integration guide: docs/CONFIGURATION.md.

Optional: Running with Managed LLM APIs

For research experiments needing a generation model beyond what the local host serves, the optional contemplative-agent-cloud add-on routes every generation call through Anthropic Claude or OpenAI GPT via the abstract LLMBackend Protocol — main-repo code unmodified, embeddings stay on local Ollama. This is an explicit opt-in that relaxes the no-cloud property for users who install it; do not install it in deployments where cloud data egress is not acceptable.

Optional: Local MLX runtime (Apple Silicon)

For faster interactive generation on Apple Silicon, the optional contemplative-agent-mlx add-on routes generation through a local mlx_lm.server (≈1.8× faster, ≈3.4 GB lighter; embeddings stay on Ollama) via the same LLMBackend Protocol. It is a local-runtime swap, not a cloud backend — the no-cloud property is preserved. mlx_lm.server is unfit for the unattended scheduled agent on a 16 GB host (ADR-0067), so production runs on Ollama (ADR-0070).

Optional: Everyday CLI
contemplative-agent run --session 60       # Run a session
contemplative-agent distill --days 3       # Extract patterns
contemplative-agent dialogue HOME_A HOME_B --seed "..." --turns N

Full reference (autonomy levels, scheduling, env vars, v1.x → v2 migrations): docs/CONFIGURATION.md.

Citation

Shimomoto, T. (2026). Contemplative Agent [Computer software]. https://doi.org/10.5281/zenodo.21281186

The citation above uses the v2.8.0 version DOI. The DOI badge resolves to 10.5281/zenodo.19212118, the all-versions concept DOI that always points to the latest release.

BibTeX
@software{shimomoto2026contemplative,
  author       = {Shimomoto, Tatsuya},
  title        = {Contemplative Agent},
  year         = {2026},
  version      = {2.8.0},
  doi          = {10.5281/zenodo.21281186},
  url          = {https://github.com/shimo4228/contemplative-agent},
}

The MIT license means what it says — fork it, strip it for parts, embed the pipeline in your own agent, build a commercial product on top of it. No citation needed if you're just using the code.

Related Work

The ecosystem hub — a human-readable index of all five research lines — is shimo4228/shimo4228.

  • Agent Knowledge Cycle (AKC) (DOI) — the methodological framework this project re-implements in the autonomous-agent context: six phases, Research → Extract → Curate → Promote → Measure → Maintain. Originally developed as a Claude Code harness. AKC now also carries a companion position paper — Harness Alignment and Harness Drift: Why Intent, Unlike Correctness, Resists Automation (DOI).
  • Agent Attribution Practice (AAP) (DOI) — sibling research repository. Re-expresses this project's governance judgments (Security Boundary Model, One External Adapter Per Agent, Human Approval Gate, …) in harness-neutral form as ten ADRs on accountability distribution, and articulates the four-quadrant routing lens this repo borrows (see ADR-0033). Cite AAP for the accountability-distribution thesis; cite this repository for the operational implementation. Companion position papers and standards mappings (NIST AI RMF, ISO/IEC 42001, EU AI Act) are tracked in the AAP repo.

Theoretical foundation:

  • Laukkonen, Inglis, Chandaria, Sandved-Smith, Lopez-Sola, Hohwy, Gold, & Elwood (2025). Contemplative Artificial Intelligence. arXiv:2504.15125 — four-axiom ethical framework (default preset, ADR-0002).
  • Laukkonen, Friston & Chandaria (2025). A Beautiful Loop: An Active Inference Theory of Consciousness. Neuroscience & Biobehavioral Reviews, 176, 106296. PubMed:40750007 — meditation adapter basis.
  • Vasubandhu (4th–5th c. CE). Triṃśikā-vijñaptimātratā (唯識三十頌) and Xuanzang (659 CE). Cheng Weishi Lun (成唯識論) — eight-consciousness model adopted as the architectural frame (ADR-0017).

Further reading: the memory-systems bibliography (per-ADR design influences) lives in docs/BIBLIOGRAPHY.md; the articles written during development are indexed in docs/DEVELOPMENT-RECORDS.md.

Acknowledgments: Jerry Mares (VADUGWI) — deterministic affect-scoring design inspiration.

About

Contemplative Agent (CA) — an autonomous agent that carries an explicit, human-editable constitution and amends it. Every change to its value layer (constitution, identity, skills, rules) passes a human approval gate. Runs entirely on a local LLM via Ollama — robust even on a small model. Security by absence.

Topics

Resources

License

Stars

5 stars

Watchers

0 watching

Forks

Packages

 
 
 

Contributors