πŸ‘₯

CrewAI Integration

Govern entire crews with kernel-level policy enforcement. Every agent, every task, every delegationβ€”controlled by your policies.

$ pip install agent-os-kernel[crewai]

Overview

The Agent OS CrewAI integration provides comprehensive governance for multi-agent crews, enabling enterprise-grade safety controls without sacrificing the power of autonomous agent collaboration.

πŸ›‘οΈ

Crew-Wide Governance

Wrap an entire crew with a single line. All agents automatically inherit kernel protection with consistent policy enforcement.

πŸ”

Per-Agent Policies

Define granular policies for each agent role. Researchers get read access, writers get create access, reviewers get approval rights.

πŸ”—

IATP Trust Protocol

Inter-Agent Trust Protocol ensures agents verify each other's identity and permissions before sharing data or delegating tasks.

πŸ“‹

Task Delegation Rules

Control which agents can delegate to whom, what tasks can be delegated, and enforce approval workflows for sensitive operations.

πŸ“Š

Unified Audit Trail

Every agent action, every delegation, every tool call recorded in a single audit log with full crew context and correlation IDs.

πŸ”„

Process Isolation

Optional process-level isolation for each agent. Prevent one compromised agent from affecting others in the crew.

Installation

Install Agent OS with CrewAI support in one command.

1

Install the Package

# Install with CrewAI support
pip install agent-os-kernel[crewai]

# Or install with all integrations
pip install agent-os-kernel[all]

# Verify installation
python -c "from agent_os.integrations import crewai_kernel; print('βœ“ CrewAI integration ready')"
2

Requirements

# requirements.txt
agent-os-kernel[crewai]>=0.1.0
crewai>=0.28.0
langchain>=0.1.0

# Optional: for process isolation
psutil>=5.9.0
multiprocessing-logging>=0.3.0
3

Environment Setup

# .env file
OPENAI_API_KEY=sk-...
AGENT_OS_LOG_LEVEL=INFO
AGENT_OS_AUDIT_PATH=./audit_logs

# Optional: Enable flight recorder
AGENT_OS_FLIGHT_RECORDER=true
AGENT_OS_FLIGHT_RECORDER_PATH=./flight_records

Basic Usage

Wrap your existing CrewAI setup with one line. No rewrites required.

from crewai import Crew, Agent, Task
from agent_os.integrations import crewai_kernel

# Define your agents as usual
researcher = Agent(
    role="Senior Research Analyst",
    goal="Discover groundbreaking insights about the topic",
    backstory="You are an expert researcher with deep analytical skills.",
    verbose=True,
    allow_delegation=True
)

writer = Agent(
    role="Content Writer",
    goal="Create engaging content based on research findings",
    backstory="You are a skilled writer who transforms research into compelling narratives.",
    verbose=True,
    allow_delegation=False
)

# Define tasks as usual
research_task = Task(
    description="Research the latest trends in {topic}",
    expected_output="A comprehensive research report with key findings",
    agent=researcher
)

writing_task = Task(
    description="Write an article based on the research findings",
    expected_output="A well-structured article ready for publication",
    agent=writer
)

# Create your crew as usual
crew = Crew(
    agents=[researcher, writer],
    tasks=[research_task, writing_task],
    verbose=True
)

# ✨ Wrap with Agent OS governance - ONE LINE
governed_crew = crewai_kernel.wrap(crew)

# Execute with full kernel protection
result = governed_crew.kickoff(inputs={"topic": "AI Safety"})
print(result)

What Happens Under the Hood

  • Each agent is registered with the Agent OS kernel
  • All tool calls are intercepted and validated against policies
  • Inter-agent communications are logged and governed
  • Task delegations require authorization checks
  • A unified audit trail captures all crew activity

Per-Agent Policies

Define granular policies for each agent based on their role and responsibilities.

from crewai import Crew, Agent, Task
from agent_os.integrations import crewai_kernel
from agent_os.policies import Policy, ResourcePolicy, ActionPolicy

# Define role-specific policies
researcher_policy = Policy(
    name="researcher_policy",
    resources=ResourcePolicy(
        file_access=["read"],
        network_access=["api.example.com", "arxiv.org", "scholar.google.com"],
        memory_limit_mb=512
    ),
    actions=ActionPolicy(
        allowed_tools=["search", "scrape", "summarize", "analyze"],
        blocked_tools=["write_file", "delete", "execute_code"],
        max_tool_calls_per_task=50
    ),
    data=DataPolicy(
        pii_handling="redact",
        data_classification_required=True
    )
)

writer_policy = Policy(
    name="writer_policy",
    resources=ResourcePolicy(
        file_access=["read", "write"],
        network_access=[],  # No network access for writer
        memory_limit_mb=256
    ),
    actions=ActionPolicy(
        allowed_tools=["write_file", "format", "grammar_check"],
        blocked_tools=["search", "scrape", "execute_code", "delete"],
        max_tool_calls_per_task=30
    )
)

reviewer_policy = Policy(
    name="reviewer_policy",
    resources=ResourcePolicy(
        file_access=["read"],
        network_access=[]
    ),
    actions=ActionPolicy(
        allowed_tools=["review", "approve", "request_changes"],
        require_human_approval=["approve"]  # Human must confirm approvals
    )
)

# Create agents
researcher = Agent(role="Researcher", ...)
writer = Agent(role="Writer", ...)
reviewer = Agent(role="Reviewer", ...)

# Create crew
crew = Crew(agents=[researcher, writer, reviewer], tasks=[...])

# Wrap with per-agent policies
governed_crew = crewai_kernel.wrap(
    crew,
    agent_policies={
        "Researcher": researcher_policy,
        "Writer": writer_policy,
        "Reviewer": reviewer_policy
    },
    default_policy="strict"  # Fallback for any unspecified agents
)

result = governed_crew.kickoff()
πŸ“

Resource Policies

Control file system access, network endpoints, memory limits, and compute resources per agent.

ResourcePolicy(
    file_access=["read", "write"],
    allowed_paths=["/data/*", "/output/*"],
    blocked_paths=["/secrets/*", "/system/*"],
    network_access=["*.company.com"],
    memory_limit_mb=1024,
    cpu_limit_percent=50
)
⚑

Action Policies

Define allowed and blocked tools, rate limits, and human approval requirements.

ActionPolicy(
    allowed_tools=["search", "analyze"],
    blocked_tools=["execute_code"],
    max_tool_calls_per_task=100,
    max_tool_calls_per_minute=20,
    require_human_approval=["deploy"],
    timeout_seconds=300
)
πŸ”’

Data Policies

Control PII handling, data classification, and information flow between agents.

DataPolicy(
    pii_handling="redact",  # or "block", "allow"
    data_classification_required=True,
    allowed_classifications=["public", "internal"],
    blocked_classifications=["confidential"],
    output_sanitization=True
)

Inter-Agent Communication Governance

Control how agents communicate, share data, and collaborate with the Inter-Agent Trust Protocol (IATP).

from agent_os.integrations import crewai_kernel
from agent_os.protocols import IATPConfig, TrustLevel, CommunicationPolicy

# Configure Inter-Agent Trust Protocol
iatp_config = IATPConfig(
    # Trust levels between agent roles
    trust_matrix={
        ("Researcher", "Writer"): TrustLevel.HIGH,      # Researcher can share all findings
        ("Writer", "Researcher"): TrustLevel.MEDIUM,    # Writer can request clarifications
        ("Reviewer", "Writer"): TrustLevel.HIGH,        # Reviewer can send feedback
        ("Writer", "Reviewer"): TrustLevel.HIGH,        # Writer can submit for review
        ("Researcher", "Reviewer"): TrustLevel.LOW,     # Limited direct communication
    },
    
    # Default trust for unspecified pairs
    default_trust=TrustLevel.NONE,
    
    # Communication policies
    communication=CommunicationPolicy(
        # Message validation
        validate_messages=True,
        max_message_size_kb=100,
        
        # Content filtering
        filter_pii=True,
        filter_secrets=True,
        
        # Logging
        log_all_messages=True,
        log_destination="./logs/agent_comms.jsonl"
    )
)

# Configure what data can flow between agents
data_flow_rules = {
    # Researcher -> Writer: can share research, not raw data
    ("Researcher", "Writer"): {
        "allowed": ["summary", "findings", "citations"],
        "blocked": ["raw_data", "api_keys", "credentials"],
        "transform": {
            "pii": "redact",
            "numbers": "round_to_thousands"
        }
    },
    
    # Writer -> Reviewer: can share drafts
    ("Writer", "Reviewer"): {
        "allowed": ["draft", "outline", "metadata"],
        "blocked": ["internal_notes"]
    },
    
    # Reviewer -> Writer: can share feedback
    ("Reviewer", "Writer"): {
        "allowed": ["feedback", "approval_status", "revision_requests"],
        "blocked": ["other_submissions"]
    }
}

# Wrap crew with IATP
governed_crew = crewai_kernel.wrap(
    crew,
    trust_protocol="iatp",
    iatp_config=iatp_config,
    data_flow_rules=data_flow_rules,
    
    # Require mutual authentication before communication
    require_agent_auth=True,
    
    # Enable message signing for integrity
    sign_messages=True
)

Trust Levels Explained

Level Description Capabilities
FULL Complete trust All data, direct delegation, shared memory
HIGH Trusted collaborator Filtered data, supervised delegation
MEDIUM Limited trust Summaries only, no delegation
LOW Minimal trust Status messages only
NONE No trust No direct communication allowed

Task Delegation Rules

Control which agents can delegate tasks, to whom, and under what conditions.

from agent_os.integrations import crewai_kernel
from agent_os.governance import DelegationPolicy, DelegationRule, ApprovalWorkflow

# Define delegation rules
delegation_policy = DelegationPolicy(
    # Global delegation settings
    allow_delegation=True,
    max_delegation_depth=3,  # Prevent infinite delegation chains
    
    rules=[
        # Rule 1: Researcher can delegate data gathering
        DelegationRule(
            delegator="Researcher",
            delegatee=["DataCollector", "WebScraper"],
            allowed_task_types=["data_collection", "web_search"],
            conditions={
                "max_concurrent_delegations": 5,
                "timeout_minutes": 30
            }
        ),
        
        # Rule 2: Manager can delegate to anyone
        DelegationRule(
            delegator="Manager",
            delegatee="*",  # Any agent
            allowed_task_types="*",  # Any task type
            require_approval=False
        ),
        
        # Rule 3: Writer cannot delegate (enforce in policy)
        DelegationRule(
            delegator="Writer",
            delegatee=[],  # No one
            allowed_task_types=[]
        ),
        
        # Rule 4: Sensitive tasks require approval
        DelegationRule(
            delegator="*",
            delegatee="*",
            allowed_task_types=["deploy", "publish", "delete"],
            require_approval=True,
            approval_workflow=ApprovalWorkflow(
                approvers=["Manager", "human"],
                min_approvals=1,
                timeout_minutes=60
            )
        )
    ],
    
    # What happens when delegation is denied
    on_denied="block_and_log",  # or "allow_with_warning", "escalate"
    
    # Logging
    log_all_delegations=True
)

# Wrap with delegation governance
governed_crew = crewai_kernel.wrap(
    crew,
    delegation_policy=delegation_policy,
    
    # Track delegation chains
    track_delegation_chain=True,
    
    # Callback for delegation events
    on_delegation=lambda event: print(f"Delegation: {event.delegator} -> {event.delegatee}")
)
πŸ”€

Delegation Chains

Track and limit delegation depth to prevent runaway task chains.

# Delegation chain tracking
Manager -> Researcher -> DataCollector
  └── Chain depth: 2 (limit: 3) βœ“

# Chain too deep - blocked
A -> B -> C -> D -> E
  └── Chain depth: 4 (limit: 3) βœ—
βœ…

Approval Workflows

Require human or manager approval for sensitive delegations.

ApprovalWorkflow(
    # Who can approve
    approvers=["Manager", "human"],
    
    # How many approvals needed
    min_approvals=1,
    
    # Timeout handling
    timeout_minutes=60,
    on_timeout="deny"  # or "escalate"
)
πŸ“ˆ

Delegation Metrics

Monitor delegation patterns and identify bottlenecks.

# Get delegation metrics
metrics = governed_crew.get_delegation_metrics()

print(metrics)
# {
#   "total_delegations": 47,
#   "successful": 42,
#   "denied": 3,
#   "pending_approval": 2,
#   "avg_chain_depth": 1.8
# }

Example: Governed Research Crew

A complete example of a research crew with full governanceβ€”per-agent policies, IATP communication, delegation rules, and audit logging.

"""
Governed Research Crew Example
==============================
A fully governed multi-agent research team with:
- Per-agent policies based on role
- Inter-agent trust protocol
- Task delegation governance
- Comprehensive audit logging
"""

from crewai import Crew, Agent, Task, Process
from crewai_tools import SerperDevTool, ScrapeWebsiteTool

from agent_os.integrations import crewai_kernel
from agent_os.policies import Policy, ResourcePolicy, ActionPolicy, DataPolicy
from agent_os.protocols import IATPConfig, TrustLevel, CommunicationPolicy
from agent_os.governance import DelegationPolicy, DelegationRule
from agent_os.audit import AuditConfig

# ============================================================
# 1. DEFINE AGENT POLICIES
# ============================================================

lead_researcher_policy = Policy(
    name="lead_researcher",
    resources=ResourcePolicy(
        file_access=["read"],
        network_access=["*.google.com", "*.arxiv.org", "*.github.com"],
        memory_limit_mb=1024
    ),
    actions=ActionPolicy(
        allowed_tools=["SerperDevTool", "ScrapeWebsiteTool", "analyze", "summarize"],
        max_tool_calls_per_task=100,
        max_tool_calls_per_minute=30
    ),
    data=DataPolicy(
        pii_handling="redact",
        output_sanitization=True
    )
)

data_analyst_policy = Policy(
    name="data_analyst",
    resources=ResourcePolicy(
        file_access=["read"],
        network_access=[],  # No external network access
        memory_limit_mb=2048  # More memory for analysis
    ),
    actions=ActionPolicy(
        allowed_tools=["analyze", "compute", "visualize"],
        blocked_tools=["search", "scrape"],  # Cannot fetch new data
        max_tool_calls_per_task=200
    )
)

writer_policy = Policy(
    name="writer",
    resources=ResourcePolicy(
        file_access=["read", "write"],
        allowed_paths=["./output/*", "./drafts/*"],
        network_access=[]
    ),
    actions=ActionPolicy(
        allowed_tools=["write_file", "format_markdown", "grammar_check"],
        blocked_tools=["search", "scrape", "execute_code"]
    )
)

reviewer_policy = Policy(
    name="reviewer",
    resources=ResourcePolicy(
        file_access=["read"],
        network_access=[]
    ),
    actions=ActionPolicy(
        allowed_tools=["review", "comment", "approve", "request_changes"],
        require_human_approval=["approve"]  # Final approval needs human
    )
)

# ============================================================
# 2. CONFIGURE INTER-AGENT TRUST
# ============================================================

iatp_config = IATPConfig(
    trust_matrix={
        ("Lead Researcher", "Data Analyst"): TrustLevel.HIGH,
        ("Data Analyst", "Lead Researcher"): TrustLevel.HIGH,
        ("Lead Researcher", "Technical Writer"): TrustLevel.HIGH,
        ("Data Analyst", "Technical Writer"): TrustLevel.MEDIUM,
        ("Technical Writer", "Quality Reviewer"): TrustLevel.HIGH,
        ("Quality Reviewer", "Technical Writer"): TrustLevel.HIGH,
    },
    default_trust=TrustLevel.LOW,
    communication=CommunicationPolicy(
        validate_messages=True,
        filter_pii=True,
        log_all_messages=True
    )
)

# ============================================================
# 3. CONFIGURE DELEGATION RULES
# ============================================================

delegation_policy = DelegationPolicy(
    allow_delegation=True,
    max_delegation_depth=2,
    rules=[
        DelegationRule(
            delegator="Lead Researcher",
            delegatee=["Data Analyst"],
            allowed_task_types=["analysis", "computation"]
        ),
        DelegationRule(
            delegator="Technical Writer",
            delegatee=[],  # Writer cannot delegate
            allowed_task_types=[]
        )
    ]
)

# ============================================================
# 4. CONFIGURE AUDIT LOGGING
# ============================================================

audit_config = AuditConfig(
    enabled=True,
    log_path="./audit_logs/research_crew.jsonl",
    log_level="INFO",
    include_timestamps=True,
    include_agent_context=True,
    include_tool_inputs=True,
    include_tool_outputs=True,
    redact_sensitive=True,  # Redact PII from logs
    rotation="daily",
    retention_days=90
)

# ============================================================
# 5. CREATE AGENTS
# ============================================================

search_tool = SerperDevTool()
scrape_tool = ScrapeWebsiteTool()

lead_researcher = Agent(
    role="Lead Researcher",
    goal="Conduct comprehensive research and coordinate the research team",
    backstory="""You are a senior research scientist with expertise in AI and ML.
    You lead research projects and coordinate with analysts and writers.""",
    tools=[search_tool, scrape_tool],
    allow_delegation=True,
    verbose=True
)

data_analyst = Agent(
    role="Data Analyst",
    goal="Analyze research data and extract meaningful insights",
    backstory="""You are an expert data analyst who transforms raw research 
    into actionable insights through statistical analysis.""",
    tools=[],
    allow_delegation=False,
    verbose=True
)

writer = Agent(
    role="Technical Writer",
    goal="Create clear, engaging technical content from research findings",
    backstory="""You are a skilled technical writer who makes complex topics
    accessible to a broad audience.""",
    tools=[],
    allow_delegation=False,
    verbose=True
)

reviewer = Agent(
    role="Quality Reviewer",
    goal="Ensure all content meets quality standards before publication",
    backstory="""You are a meticulous editor who ensures accuracy, clarity,
    and adherence to style guidelines.""",
    tools=[],
    allow_delegation=False,
    verbose=True
)

# ============================================================
# 6. DEFINE TASKS
# ============================================================

research_task = Task(
    description="""Research the topic: {topic}
    
    Requirements:
    1. Search for the latest developments and trends
    2. Identify key players and technologies
    3. Find relevant statistics and data points
    4. Compile a comprehensive research brief""",
    expected_output="A detailed research brief with sources and key findings",
    agent=lead_researcher
)

analysis_task = Task(
    description="""Analyze the research findings:
    
    1. Identify patterns and trends in the data
    2. Compare with historical context
    3. Provide statistical insights
    4. Highlight key takeaways""",
    expected_output="An analysis report with insights and visualizations",
    agent=data_analyst,
    context=[research_task]
)

writing_task = Task(
    description="""Write a comprehensive article:
    
    1. Create an engaging introduction
    2. Structure the content logically
    3. Include data visualizations
    4. Write a compelling conclusion""",
    expected_output="A polished article ready for review",
    agent=writer,
    context=[research_task, analysis_task]
)

review_task = Task(
    description="""Review the article for:
    
    1. Technical accuracy
    2. Clarity and readability
    3. Proper citations
    4. Grammar and style""",
    expected_output="A reviewed article with approval status",
    agent=reviewer,
    context=[writing_task]
)

# ============================================================
# 7. CREATE AND WRAP CREW
# ============================================================

crew = Crew(
    agents=[lead_researcher, data_analyst, writer, reviewer],
    tasks=[research_task, analysis_task, writing_task, review_task],
    process=Process.sequential,
    verbose=True
)

# ✨ Wrap with full governance
governed_crew = crewai_kernel.wrap(
    crew,
    
    # Per-agent policies
    agent_policies={
        "Lead Researcher": lead_researcher_policy,
        "Data Analyst": data_analyst_policy,
        "Technical Writer": writer_policy,
        "Quality Reviewer": reviewer_policy
    },
    
    # Inter-agent trust
    trust_protocol="iatp",
    iatp_config=iatp_config,
    
    # Delegation governance
    delegation_policy=delegation_policy,
    
    # Audit logging
    audit_config=audit_config,
    
    # Process isolation (optional - for high security)
    isolation="thread",  # or "process" for full isolation
    
    # Flight recorder for debugging
    flight_recorder=True
)

# ============================================================
# 8. EXECUTE
# ============================================================

if __name__ == "__main__":
    print("Starting governed research crew...")
    
    result = governed_crew.kickoff(
        inputs={"topic": "The Future of AI Agents in Enterprise"}
    )
    
    print("\n" + "="*60)
    print("FINAL OUTPUT")
    print("="*60)
    print(result)
    
    # Get governance metrics
    metrics = governed_crew.get_metrics()
    print("\n" + "="*60)
    print("GOVERNANCE METRICS")
    print("="*60)
    print(f"Total tool calls: {metrics['total_tool_calls']}")
    print(f"Blocked actions: {metrics['blocked_actions']}")
    print(f"Delegations: {metrics['total_delegations']}")
    print(f"Policy violations: {metrics['policy_violations']}")
    print(f"Audit entries: {metrics['audit_entries']}")

Advanced Configuration

Fine-tune governance behavior for your specific requirements.

πŸ”„

Process Isolation Modes

Choose the right isolation level for your security requirements.

# No isolation (fastest, shared memory)
governed_crew = crewai_kernel.wrap(
    crew,
    isolation="none"
)

# Thread isolation (moderate security)
governed_crew = crewai_kernel.wrap(
    crew,
    isolation="thread"
)

# Process isolation (highest security)
governed_crew = crewai_kernel.wrap(
    crew,
    isolation="process",
    process_config={
        "spawn_method": "fork",  # or "spawn"
        "shared_memory": False,
        "ipc_encryption": True
    }
)
πŸŽ›οΈ

Custom Policy Enforcement

Implement custom policy checks for domain-specific requirements.

from agent_os.policies import PolicyEnforcer

class FinancialComplianceEnforcer(PolicyEnforcer):
    """Custom enforcer for financial regulations."""
    
    def check_action(self, action):
        # Check for financial data access
        if self.contains_financial_data(action):
            if not self.agent_has_clearance():
                return PolicyDecision.DENY
            
            # Log for compliance
            self.audit_financial_access(action)
        
        return PolicyDecision.ALLOW

governed_crew = crewai_kernel.wrap(
    crew,
    custom_enforcers=[FinancialComplianceEnforcer()]
)
πŸ“‘

Event Hooks

React to governance events in real-time.

def on_policy_violation(event):
    """Handle policy violations."""
    alert_security_team(event)
    log_to_siem(event)

def on_task_complete(event):
    """Track task completion."""
    metrics.record(event)

governed_crew = crewai_kernel.wrap(
    crew,
    hooks={
        "policy_violation": on_policy_violation,
        "task_complete": on_task_complete,
        "delegation_request": on_delegation,
        "agent_start": on_agent_start,
        "agent_stop": on_agent_stop
    }
)
πŸ’Ύ

Flight Recorder

Capture detailed execution traces for debugging and compliance.

from agent_os.flight_recorder import FlightRecorder

governed_crew = crewai_kernel.wrap(
    crew,
    flight_recorder=True,
    flight_recorder_config={
        "path": "./flight_records",
        "format": "jsonl",  # or "parquet"
        "capture_level": "full",
        "include_llm_calls": True,
        "include_memory_snapshots": True,
        "retention_days": 30
    }
)

# Later: replay for debugging
recorder = FlightRecorder("./flight_records")
recorder.replay(
    run_id="abc123",
    playback_speed=1.0,
    pause_on_error=True
)

Troubleshooting

Common issues and solutions when working with governed CrewAI crews.

!

Agent Tool Calls Being Blocked

# Error: PolicyViolation: Tool 'search' blocked by policy

# Solution 1: Add tool to allowed list
policy = Policy(
    actions=ActionPolicy(
        allowed_tools=["search", "scrape", "analyze"]  # Add missing tool
    )
)

# Solution 2: Check policy inheritance
governed_crew = crewai_kernel.wrap(
    crew,
    default_policy="permissive",  # Start permissive, then restrict
    agent_policies={"Researcher": restrictive_policy}
)

# Solution 3: Debug policy evaluation
governed_crew = crewai_kernel.wrap(
    crew,
    debug_policy=True  # Logs all policy decisions
)
!

IATP Communication Failures

# Error: IATPError: Agent 'Writer' cannot communicate with 'Researcher'

# Solution 1: Check trust matrix
iatp_config = IATPConfig(
    trust_matrix={
        ("Writer", "Researcher"): TrustLevel.MEDIUM,  # Add missing trust
        ("Researcher", "Writer"): TrustLevel.HIGH,
    },
    default_trust=TrustLevel.LOW  # Consider raising default
)

# Solution 2: Enable trust debugging
governed_crew = crewai_kernel.wrap(
    crew,
    iatp_config=iatp_config,
    debug_iatp=True  # Logs trust decisions
)

# Solution 3: Check message size limits
communication=CommunicationPolicy(
    max_message_size_kb=1000  # Increase if messages are large
)
!

Delegation Chain Errors

# Error: DelegationError: Delegation chain depth exceeded (4 > 3)

# Solution 1: Increase max depth
delegation_policy = DelegationPolicy(
    max_delegation_depth=5  # Increase limit
)

# Solution 2: Restructure task flow
# Instead of: Manager -> Lead -> Analyst -> Junior -> Intern
# Use: Manager -> [Lead, Analyst] (parallel, depth=1)

# Solution 3: Debug delegation chains
governed_crew = crewai_kernel.wrap(
    crew,
    delegation_policy=delegation_policy,
    track_delegation_chain=True,
    debug_delegation=True  # Logs chain details
)
!

Process Isolation Issues

# Error: ProcessIsolationError: Failed to spawn agent process

# Solution 1: Check multiprocessing support
import multiprocessing
print(multiprocessing.get_start_method())  # Should be 'fork' or 'spawn'

# Solution 2: Use thread isolation instead
governed_crew = crewai_kernel.wrap(
    crew,
    isolation="thread"  # Fallback to threads
)

# Solution 3: Configure spawn method explicitly
governed_crew = crewai_kernel.wrap(
    crew,
    isolation="process",
    process_config={
        "spawn_method": "spawn",  # More compatible than 'fork'
        "timeout_seconds": 60
    }
)

# Solution 4: Check resource limits
# Ensure sufficient memory and file descriptors
import resource
resource.setrlimit(resource.RLIMIT_NOFILE, (4096, 4096))
!

Audit Log Not Writing

# Issue: Audit logs are empty or not being created

# Solution 1: Check file permissions
import os
audit_path = "./audit_logs"
os.makedirs(audit_path, exist_ok=True)
os.chmod(audit_path, 0o755)

# Solution 2: Verify audit config
audit_config = AuditConfig(
    enabled=True,  # Make sure it's enabled
    log_path="./audit_logs/crew.jsonl",
    log_level="DEBUG",  # Lower level for more output
    flush_interval=1  # Flush every second
)

# Solution 3: Check for async issues
# Audit writes are async by default; ensure proper shutdown
try:
    result = governed_crew.kickoff()
finally:
    governed_crew.flush_audit()  # Force flush on exit
    governed_crew.close()  # Clean shutdown
!

Performance Issues

# Issue: Governed crew is significantly slower than ungoverned

# Solution 1: Reduce logging verbosity
governed_crew = crewai_kernel.wrap(
    crew,
    audit_config=AuditConfig(
        log_level="WARNING",  # Only log warnings+
        include_tool_inputs=False,
        include_tool_outputs=False
    )
)

# Solution 2: Disable unnecessary features
governed_crew = crewai_kernel.wrap(
    crew,
    flight_recorder=False,
    debug_policy=False,
    debug_iatp=False,
    isolation="none"  # No isolation overhead
)

# Solution 3: Use async policy evaluation
governed_crew = crewai_kernel.wrap(
    crew,
    async_policy_eval=True,  # Non-blocking policy checks
    policy_cache_ttl=60  # Cache policy decisions
)

# Solution 4: Profile to find bottlenecks
with governed_crew.profiler():
    result = governed_crew.kickoff()
print(governed_crew.profiler.report())

πŸ’‘ Need More Help?

Ready to Govern Your Crews?

Start with full governance in minutes. Your agents, your rules.