CSL-Core (Chimera Specification Language) is a deterministic safety layer for AI agents. Write rules in .csl files, verify them mathematically with Z3, enforce them at runtime — outside the model. The LLM never sees the rules. It simply cannot violate them. Originally built for Project Chimera, now open-source for any AI system. This doesn't work. LLMs can be prompt-injected, rules are probabilist
Add this skill
npx mdskills install Chimera-Protocol/csl-coreDeterministic AI safety layer with Z3 formal verification, CLI tools, and framework integrations for policy enforcement
1# CSL-Core23[](https://pypi.org/project/csl-core/)4[](https://pepy.tech/projects/csl-core)5[](https://pypi.org/project/csl-core/)6[](LICENSE)7[](https://github.com/Z3Prover/z3)89**CSL-Core** (Chimera Specification Language) is a deterministic safety layer for AI agents. Write rules in `.csl` files, verify them mathematically with Z3, enforce them at runtime — outside the model. The LLM never sees the rules. It simply cannot violate them.1011```bash12pip install csl-core13```1415Originally built for [**Project Chimera**](https://github.com/Chimera-Protocol/Project-Chimera), now open-source for any AI system.1617---1819## Why?2021```python22prompt = """You are a helpful assistant. IMPORTANT RULES:23- Never transfer more than $1000 for junior users24- Never send PII to external emails25- Never query the secrets table"""26```2728This doesn't work. LLMs can be prompt-injected, rules are probabilistic (99% ≠ 100%), and there's no audit trail when something goes wrong.2930**CSL-Core flips this**: rules live outside the model in compiled, Z3-verified policy files. Enforcement is deterministic — not a suggestion.3132---3334## Quick Start (60 Seconds)3536### 1. Write a Policy3738Create `my_policy.csl`:3940```js41CONFIG {42 ENFORCEMENT_MODE: BLOCK43 CHECK_LOGICAL_CONSISTENCY: TRUE44}4546DOMAIN MyGuard {47 VARIABLES {48 action: {"READ", "WRITE", "DELETE"}49 user_level: 0..550 }5152 STATE_CONSTRAINT strict_delete {53 WHEN action == "DELETE"54 THEN user_level >= 455 }56}57```5859### 2. Verify & Test (CLI)6061```bash62# Compile + Z3 formal verification63cslcore verify my_policy.csl6465# Test a scenario66cslcore simulate my_policy.csl --input '{"action": "DELETE", "user_level": 2}'67# → BLOCKED: Constraint 'strict_delete' violated.6869# Interactive REPL70cslcore repl my_policy.csl71```7273### 3. Use in Python7475```python76from chimera_core import load_guard7778guard = load_guard("my_policy.csl")7980result = guard.verify({"action": "READ", "user_level": 1})81print(result.allowed) # True8283result = guard.verify({"action": "DELETE", "user_level": 2})84print(result.allowed) # False85```8687---8889## Benchmark: Adversarial Attack Resistance9091We tested prompt-based safety rules vs CSL-Core enforcement across 4 frontier LLMs with 22 adversarial attacks and 15 legitimate operations:9293| Approach | Attacks Blocked | Bypass Rate | Legit Ops Passed | Latency |94|----------|----------------|-------------|------------------|---------|95| GPT-4.1 (prompt rules) | 10/22 (45%) | 55% | 15/15 (100%) | ~850ms |96| GPT-4o (prompt rules) | 15/22 (68%) | 32% | 15/15 (100%) | ~620ms |97| Claude Sonnet 4 (prompt rules) | 19/22 (86%) | 14% | 15/15 (100%) | ~480ms |98| Gemini 2.0 Flash (prompt rules) | 11/22 (50%) | 50% | 15/15 (100%) | ~410ms |99| **CSL-Core (deterministic)** | **22/22 (100%)** | **0%** | **15/15 (100%)** | **~0.84ms** |100101102**Why 100%?** Enforcement happens outside the model. Prompt injection is irrelevant because there's nothing to inject against. Attack categories: direct instruction override, role-play jailbreaks, encoding tricks, multi-turn escalation, tool-name spoofing, and more.103104> Full methodology: [`benchmarks/`](benchmarks/)105106---107108## LangChain Integration109110Protect any LangChain agent with 3 lines — no prompt changes, no fine-tuning:111112```python113from chimera_core import load_guard114from chimera_core.plugins.langchain import guard_tools115from langchain_classic.agents import AgentExecutor, create_tool_calling_agent116117guard = load_guard("agent_policy.csl")118119# Wrap tools — enforcement is automatic120safe_tools = guard_tools(121 tools=[search_tool, transfer_tool, delete_tool],122 guard=guard,123 inject={"user_role": "JUNIOR", "environment": "prod"}, # LLM can't override these124 tool_field="tool" # Auto-inject tool name125)126127agent = create_tool_calling_agent(llm, safe_tools, prompt)128executor = AgentExecutor(agent=agent, tools=safe_tools)129```130131Every tool call is intercepted before execution. If the policy says no, the tool doesn't run. Period.132133### Context Injection134135Pass runtime context that the LLM **cannot override** — user roles, environment, rate limits:136137```python138safe_tools = guard_tools(139 tools=tools,140 guard=guard,141 inject={142 "user_role": current_user.role, # From your auth system143 "environment": os.getenv("ENV"), # prod/dev/staging144 "rate_limit_remaining": quota.remaining # Dynamic limits145 }146)147```148149### LCEL Chain Protection150151```python152from chimera_core.plugins.langchain import gate153154chain = (155 {"query": RunnablePassthrough()}156 | gate(guard, inject={"user_role": "USER"}) # Policy checkpoint157 | prompt | llm | StrOutputParser()158)159```160161---162163## CLI Tools164165The CLI is a complete development environment for policies — test, debug, and deploy without writing Python.166167### `verify` — Compile + Z3 Proof168169```bash170cslcore verify my_policy.csl171172# ⚙️ Compiling Domain: MyGuard173# • Validating Syntax... ✅ OK174# ├── Verifying Logic Model (Z3 Engine)... ✅ Mathematically Consistent175# • Generating IR... ✅ OK176```177178### `simulate` — Test Scenarios179180```bash181# Single input182cslcore simulate policy.csl --input '{"action": "DELETE", "user_level": 2}'183184# Batch testing from file185cslcore simulate policy.csl --input-file test_cases.json --dashboard186187# CI/CD: JSON output188cslcore simulate policy.csl --input-file tests.json --json --quiet189```190191### `repl` — Interactive Development192193```bash194cslcore repl my_policy.csl --dashboard195196cslcore> {"action": "DELETE", "user_level": 2}197🛡️ BLOCKED: Constraint 'strict_delete' violated.198199cslcore> {"action": "DELETE", "user_level": 5}200✅ ALLOWED201```202203### CI/CD Pipeline204205```yaml206# GitHub Actions207- name: Verify policies208 run: |209 for policy in policies/*.csl; do210 cslcore verify "$policy" || exit 1211 done212```213214---215216## MCP Server (Claude Desktop / Cursor / VS Code)217218Write, verify, and enforce safety policies directly from your AI assistant — no code required.219220```bash221pip install "csl-core[mcp]"222```223224Add to Claude Desktop config (`~/Library/Application Support/Claude/claude_desktop_config.json`):225```json226{227 "mcpServers": {228 "csl-core": {229 "command": "uv",230 "args": ["run", "--with", "csl-core[mcp]", "csl-core-mcp"]231 }232 }233}234```235236| Tool | What It Does |237|---|---|238| `verify_policy` | Z3 formal verification — catches contradictions at compile time |239| `simulate_policy` | Test policies against JSON inputs — ALLOWED/BLOCKED |240| `explain_policy` | Human-readable summary of any CSL policy |241| `scaffold_policy` | Generate a CSL template from plain-English description |242243> **You:** "Write me a safety policy that prevents transfers over $5000 without admin approval"244>245> **Claude:** *scaffold_policy → you edit → verify_policy catches a contradiction → you fix → simulate_policy confirms it works*246247---248249## Architecture250251```252┌──────────────────────────────────────────────────────────┐253│ 1. COMPILER .csl → AST → IR → Compiled Artifact │254│ Syntax validation, semantic checks, functor gen │255├──────────────────────────────────────────────────────────┤256│ 2. VERIFIER Z3 Theorem Prover — Static Analysis │257│ Contradiction detection, reachability, rule shadowing │258│ ⚠️ If verification fails → policy will NOT compile │259├──────────────────────────────────────────────────────────┤260│ 3. RUNTIME Deterministic Policy Enforcement │261│ Fail-closed, zero dependencies, <1ms latency │262└──────────────────────────────────────────────────────────┘263```264265Heavy computation happens once at compile-time. Runtime is pure evaluation.266267---268269## Used in Production270271<table>272 <tr>273 <td width="80" align="center">274 <a href="https://github.com/Chimera-Protocol/Project-Chimera">🏛️</a>275 </td>276 <td>277 <a href="https://github.com/Chimera-Protocol/Project-Chimera"><b>Project Chimera</b></a> — Neuro-Symbolic AI Agent<br/>278 CSL-Core powers all safety policies across e-commerce and quantitative trading domains. Both are Z3-verified at startup.279 </td>280 </tr>281</table>282283*Using CSL-Core? [Let us know](https://github.com/Chimera-Protocol/csl-core/discussions) and we'll add you here.*284285---286287## Example Policies288289| Example | Domain | Key Features |290|---------|--------|--------------|291| [`agent_tool_guard.csl`](examples/agent_tool_guard.csl) | AI Safety | RBAC, PII protection, tool permissions |292| [`chimera_banking_case_study.csl`](examples/chimera_banking_case_study.csl) | Finance | Risk scoring, VIP tiers, sanctions |293| [`dao_treasury_guard.csl`](examples/dao_treasury_guard.csl) | Web3 | Multi-sig, timelocks, emergency bypass |294295```bash296python examples/run_examples.py # Run all with test suites297python examples/run_examples.py banking # Run specific example298```299300---301302## API Reference303304```python305from chimera_core import load_guard, RuntimeConfig306307# Load + compile + verify308guard = load_guard("policy.csl")309310# With custom config311guard = load_guard("policy.csl", config=RuntimeConfig(312 raise_on_block=False, # Return result instead of raising313 collect_all_violations=True, # Report all violations, not just first314 missing_key_behavior="block" # "block", "warn", or "ignore"315))316317# Verify318result = guard.verify({"action": "DELETE", "user_level": 2})319print(result.allowed) # False320print(result.violations) # ['strict_delete']321```322323Full docs: [**Getting Started**](docs/getting-started.md) · [**Syntax Spec**](docs/syntax-spec.md) · [**CLI Reference**](docs/cli-reference.md) · [**Philosophy**](docs/philosophy.md)324325---326327## Roadmap328329**✅ Done:** Core language & parser · Z3 verification · Fail-closed runtime · LangChain integration · CLI (verify, simulate, repl) · MCP Server · Production deployment in Chimera v1.7.0330331**🚧 In Progress:** Policy versioning · LangGraph integration332333**🔮 Planned:** LlamaIndex & AutoGen · Multi-policy composition · Hot-reload · Policy marketplace · Cloud templates334335**🔒 Enterprise (Research):** TLA+ temporal logic · Causal inference · Multi-tenancy336337---338339## Contributing340341We welcome contributions! Start with [`good first issue`](https://github.com/Chimera-Protocol/csl-core/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) or check [`CONTRIBUTING.md`](CONTRIBUTING.md).342343**High-impact areas:** Real-world example policies · Framework integrations · Web-based policy editor · Test coverage344345---346347## License348349**Apache 2.0** (open-core model). The complete language, compiler, Z3 verifier, runtime, CLI, MCP server, and all examples are open-source. See [LICENSE](LICENSE).350351---352353**Built with ❤️ by [Chimera Protocol](https://github.com/Chimera-Protocol)** · [Issues](https://github.com/Chimera-Protocol/csl-core/issues) · [Discussions](https://github.com/Chimera-Protocol/csl-core/discussions) · [Email](mailto:akarlaraytu@gmail.com)
Full transparency — inspect the skill content before installing.