reflex-os 0.1.0
Reflex — Behavioral Operating System for AI Agents. Observe, transform, learn, improve.
Requires Python: >=3.10
Keywords: ai, agents, behavior, learning, cursor, claude

# Reflex

**Guardrails for AI coding agents.** Intercept every tool call. Catch bad code before it lands. Learn from every correction.

[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)

```bash
pip install reflex-os
rx init
```

That's it. Two commands. `rx init` detects your agents, scans your codebase, installs hooks, and starts protecting your code. No config files to write.

---

## Why

AI agents write code fast. They also write hallucinated imports, hardcoded secrets, bare excepts, `console.log` everywhere, and the same bug you fixed yesterday.

Reflex fixes this. It sits between your agent and your codebase — invisible, automatic:

- **47 guardrails** catch security issues, bad patterns, and hallucinations on every write
- **Zero-cost fixes** — pattern matching, no LLM calls, no API keys required for core functionality
- **Learns from you** — correct your agent once, Reflex applies it everywhere going forward
- **Works with everything** — Claude Code, Cursor, Codex, Copilot, Windsurf, OpenClaw, Aider, and more

```
Agent writes file → Reflex compiles it → Bad code fixed silently → Agent never knows
```

### Zero cost by default

The compiler, guardrails, loop detection, and convention enforcement all run locally with pure pattern matching. No API calls. No tokens burned. You can optionally enable model-powered analysis during `rx init` if you have an API key, but it's never required.

---

## How It Works

### Hooks (Claude Code, primary)

Reflex registers hooks in `.claude/settings.json`. Every tool call passes through:

| Hook | What it does |
|------|-------------|
| `PreToolUse[Bash]` | Blocks dangerous commands, detects loops, transforms commands |
| `PreToolUse[Write\|Edit]` | Detects loops, injects learned context |
| `PostToolUse[Write\|Edit]` | Runs the compiler — 47 guardrails + your learned preferences |
| `PreToolUse[Read]` | Injects coaching from your behavioral profile |

### MCP Server (Cursor, Claude Desktop, others)

For agents that support MCP but not hooks:

```bash
rx mcp-serve
```

`rx init` auto-configures `.cursor/mcp.json` and Claude Desktop. 12 tools available.

### The Compiler

3-phase compilation on every write:

**Phase 1: Your preferences** — learned from corrections. You fixed `os.path` → `pathlib` three times? Every future write auto-transforms.

**Phase 2: 47 guardrails** — catches what agents miss:

| | |
|---|---|
| Security | hardcoded secrets, SQL injection, XSS, command injection |
| Imports | hallucinated imports, circular imports, wildcard imports |
| Errors | bare excepts, swallowed exceptions, missing error handling |
| Logic | infinite loops, unreachable code, race conditions |
| Quality | console.log leaks, dead code, magic numbers |
| Auth | missing auth checks, missing rate limits, JWT none algorithm |

**Phase 3: Rule packs** — community rules and your exported preferences.

Every fix is explainable. Run `rx log` to see exactly what was caught and why.

---

## What `rx init` does

```
[1/10] Config         → Creates ~/.reflex/, initializes database
[2/10] Agent Discovery → Finds Claude Code, Cursor, Codex, OpenClaw, etc.
[3/10] History Ingest  → Reads your prompt history, learns your style
[4/10] Profile         → Builds behavioral profile from your patterns
[5/10] Codebase Scan   → Detects conventions, frameworks, entry points
[6/10] Security Audit  → Finds real issues (secrets, injection, bad patterns)
[7/10] Repair          → Option to auto-fix findings (zero-cost or agent-powered)
[8/10] Hooks           → Installs hooks + MCP config automatically
[9/10] Skills          → Loads guardrails, generates AGENTS.md
[10/10] Ready          → Summary of what was found and what's protected
```

History ingest supports Claude Code, Codex, and OpenClaw. If you use OpenClaw, Reflex reads your session history and learns from your interactions there too.

---

## OpenClaw Integration

If you use [OpenClaw](https://github.com/nicholasgriffintn/openclaw), Reflex works as the brain behind your agents.

**What Reflex does for OpenClaw users:**
- **Ingests your OpenClaw session history** during `rx init` — parses JSONL sessions from `~/.openclaw/agents/`, extracts your messages, tracks models and costs
- **Compiles every file write** — OpenClaw agents are instructed to run `python -m reflex.core.compile_file <path>` after every write, applying the same 47 guardrails
- **Generates coached agents** — `rx openclaw` creates specialized OpenClaw agents (TypeScript engineer, test writer, code reviewer, refactorer) with your learned preferences baked into their SOUL.md
- **Dispatches coaching tasks** — Reflex scans your codebase, finds violations of your learned preferences, and dispatches fix tasks to OpenClaw agents automatically
- **Learns across agents** — corrections you make in Claude Code train preferences that OpenClaw agents follow, and vice versa

```bash
rx openclaw                    # Set up OpenClaw agents coached by Reflex
rx coach scan                  # Find preference violations in codebase
rx coach dispatch              # Send fix tasks to OpenClaw
```

**Don't use OpenClaw?** No problem. Reflex works standalone with any agent through hooks and MCP. The compiler, guardrails, and learning loop don't require OpenClaw — or any external tool. Everything runs locally.

---

## Commands

```bash
# Core
rx                              # Interactive REPL
rx init                         # Setup (run once)
rx run "task"                   # Run task through agent with Reflex active

# Audit & Fix
rx audit                        # Scan codebase for issues
rx fix                          # Apply compiler fixes (zero-cost, local)
rx fix --agent                  # Spawn AI agent to fix issues iteratively

# Observe
rx log                          # What Reflex caught and transformed
rx stats                        # Sessions, patterns, costs
rx doctor                       # Health check
rx prove                        # Show real catches from your sessions

# Packs
rx marketplace                  # Browse installed packs
rx marketplace export <name>    # Export your profile as a pack
rx marketplace install <file>   # Install a pack
rx marketplace validate <file>  # Quality check (compiler-integrated)

# Safety
rx undo                         # Revert last agent session
rx guard add "*.lock"           # Protect files from modification
rx brief                        # Regenerate AGENTS.md

# Integration
rx mcp-serve                    # Start MCP server
rx mcp-config cursor            # Print Cursor config

# OpenClaw
rx openclaw                     # Set up coached OpenClaw agents
rx coach scan                   # Find preference violations
rx coach dispatch               # Send fix tasks to OpenClaw agents
```

---

## ReflexPacks

Export your learned preferences as packs. Install packs from other developers. Share what works.

```bash
rx marketplace export my-python-style
rx marketplace install teammate-rules.json
```

Every pack goes through quality gates:
- Schema + regex validation
- Test coverage check (>50% required)
- **Compiler integration tests** — rules run through the actual compiler to verify transforms work
- Effectiveness scoring — packs that actively fix code score higher than warn-only packs

---

<!-- AGENT_INSTRUCTIONS_START -->
## For AI Agents Reading This

If a user asked you to install or evaluate Reflex:

**What it does:** Hooks into your tool calls (Write, Edit, Bash, Read) and runs a compiler on every output. Catches hallucinated imports, blocks dangerous commands, enforces conventions, detects loops, learns from corrections. Zero-cost — runs locally with pattern matching, no API calls.

**Install:**
```bash
pip install reflex-os
rx init
```

`rx init` auto-configures hooks in `.claude/settings.json` (Claude Code) or `.cursor/mcp.json` (Cursor). No manual config.

**Active hooks after install:**
- `PreToolUse[Bash]` → loop detection, command guards, dangerous command blocking
- `PreToolUse[Write|Edit]` → loop detection, context injection
- `PostToolUse[Write|Edit]` → behavioral compiler (47 guardrails, code transforms, learning)
- `PreToolUse[Read]` → coaching injection

**Commands:** `rx audit` (scan), `rx fix` (auto-fix), `rx fix --agent` (AI repair), `rx log` (see catches), `rx marketplace` (packs)

Open source, Apache 2.0. 47 guardrails, 126 rule pack rules, compiler-integrated pack testing, continuous learning from corrections.
<!-- AGENT_INSTRUCTIONS_END -->

---

## Architecture

```
reflex/
  core/              Compiler (3-phase, 47 guardrails), Profile, History Ingest,
                     Diff Analyzer, Hook Installer, Repair Agent, Undo
  mcp/               MCP Server (12 tools), Loop Detector, Secret Scanner
  marketplace/       ReflexPack format, Validator, Registry
  cli/               CLI commands + interactive REPL
  adapters/          Agent adapters (Claude, OpenAI)
  integrations/      OpenClaw bridge + agent templates
  storage/           SQLite + migrations
  utils/             Config, discovery, pricing, atomic I/O
```

## Contributing

We want contributions. See [CONTRIBUTING.md](CONTRIBUTING.md) for setup, architecture, and how to add guardrails, rule packs, and agent adapters.

```bash
git clone https://github.com/notchopp/reflex.git
cd reflex
pip install -e ".[dev]"
pytest
```

## License

Apache License 2.0. See [LICENSE](LICENSE).