{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Agent Control Plane - Interactive Tutorial\n",
    "\n",
    "This notebook provides an interactive walkthrough of the Agent Control Plane's key features.\n",
    "\n",
    "## What You'll Learn\n",
    "\n",
    "1. **Core Concepts**: Agent creation, permissions, and policy enforcement\n",
    "2. **Advanced Features**: Shadow Mode, Mute Agent, Constraint Graphs\n",
    "3. **Multi-Agent Orchestration**: Coordinating multiple agents\n",
    "4. **Safety & Governance**: Ethical alignment and bias detection\n",
    "5. **Tool Management**: Dynamic tool registry\n",
    "\n",
    "## Prerequisites\n",
    "\n",
    "```bash\n",
    "pip install -e .\n",
    "pip install jupyter\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Getting Started\n",
    "\n",
    "First, let's import the necessary components and create a control plane."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from agent_control_plane import (\n",
    "    AgentControlPlane,\n",
    "    ActionType,\n",
    "    PermissionLevel,\n",
    "    create_standard_agent,\n",
    "    create_read_only_agent\n",
    ")\n",
    "\n",
    "# Create the control plane\n",
    "control_plane = AgentControlPlane()\n",
    "print(\"✓ Control Plane initialized\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Creating Agents with Permissions\n",
    "\n",
    "Let's create agents with different permission levels."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create a read-only agent\n",
    "readonly_agent = create_read_only_agent(control_plane, \"data-reader\")\n",
    "print(f\"Created read-only agent: {readonly_agent.agent_id}\")\n",
    "print(f\"  Permissions: {list(readonly_agent.permissions.keys())}\")\n",
    "\n",
    "# Create a standard agent with more permissions\n",
    "standard_agent = create_standard_agent(control_plane, \"worker-1\")\n",
    "print(f\"\\nCreated standard agent: {standard_agent.agent_id}\")\n",
    "print(f\"  Permissions: {list(standard_agent.permissions.keys())}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Executing Actions with Governance\n",
    "\n",
    "Now let's try executing actions and see how the control plane enforces permissions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Try a read operation (should succeed)\n",
    "result = control_plane.execute_action(\n",
    "    readonly_agent,\n",
    "    ActionType.FILE_READ,\n",
    "    {\"path\": \"/data/sample.txt\"}\n",
    ")\n",
    "print(\"Read operation result:\")\n",
    "print(f\"  Success: {result['success']}\")\n",
    "print(f\"  Status: {result.get('status')}\")\n",
    "\n",
    "# Try a write operation (should be denied for read-only agent)\n",
    "result = control_plane.execute_action(\n",
    "    readonly_agent,\n",
    "    ActionType.FILE_WRITE,\n",
    "    {\"path\": \"/data/output.txt\", \"content\": \"test\"}\n",
    ")\n",
    "print(\"\\nWrite operation result:\")\n",
    "print(f\"  Success: {result['success']}\")\n",
    "print(f\"  Error: {result.get('error')}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Shadow Mode - Testing Without Side Effects\n",
    "\n",
    "Shadow Mode allows you to test agent behavior without actually executing actions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Enable shadow mode\n",
    "shadow_control_plane = AgentControlPlane(enable_shadow_mode=True)\n",
    "shadow_agent = create_standard_agent(shadow_control_plane, \"shadow-tester\")\n",
    "\n",
    "# Execute action in shadow mode\n",
    "result = shadow_control_plane.execute_action(\n",
    "    shadow_agent,\n",
    "    ActionType.DATABASE_WRITE,\n",
    "    {\"query\": \"INSERT INTO users VALUES (1, 'test')\"}\n",
    ")\n",
    "\n",
    "print(\"Shadow mode execution:\")\n",
    "print(f\"  Status: {result['status']}\")\n",
    "print(f\"  Note: {result.get('note')}\")\n",
    "print(\"\\n✓ No actual database modification occurred!\")\n",
    "\n",
    "# Get shadow mode statistics\n",
    "stats = shadow_control_plane.get_shadow_statistics()\n",
    "print(f\"\\nShadow Statistics:\")\n",
    "print(f\"  Total simulations: {stats['total_simulations']}\")\n",
    "print(f\"  Success rate: {stats['success_rate']:.1%}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Multi-Agent Orchestration\n",
    "\n",
    "Let's coordinate multiple agents using the orchestrator."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from agent_control_plane import (\n",
    "    AgentOrchestrator,\n",
    "    AgentRole,\n",
    "    OrchestrationType\n",
    ")\n",
    "\n",
    "# Create orchestrator\n",
    "orchestrator = AgentOrchestrator(control_plane)\n",
    "\n",
    "# Register agents with different roles\n",
    "orchestrator.register_agent(\n",
    "    \"retriever\",\n",
    "    AgentRole.SPECIALIST,\n",
    "    capabilities=[\"document_search\", \"vector_search\"]\n",
    ")\n",
    "\n",
    "orchestrator.register_agent(\n",
    "    \"analyzer\",\n",
    "    AgentRole.SPECIALIST,\n",
    "    capabilities=[\"data_analysis\", \"summarization\"]\n",
    ")\n",
    "\n",
    "orchestrator.register_agent(\n",
    "    \"supervisor\",\n",
    "    AgentRole.SUPERVISOR,\n",
    "    capabilities=[\"quality_check\", \"safety_check\"]\n",
    ")\n",
    "\n",
    "print(\"✓ Registered 3 agents\")\n",
    "print(\"\\nAgent roles:\")\n",
    "for agent_info in orchestrator.list_agents():\n",
    "    print(f\"  - {agent_info['agent_id']}: {agent_info['role']}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Create and Execute a Workflow"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create a RAG pipeline workflow\n",
    "workflow = orchestrator.create_workflow(\n",
    "    \"rag_pipeline\",\n",
    "    OrchestrationType.SEQUENTIAL\n",
    ")\n",
    "\n",
    "# Add agents in order\n",
    "orchestrator.add_agent_to_workflow(workflow.workflow_id, \"retriever\")\n",
    "orchestrator.add_agent_to_workflow(\n",
    "    workflow.workflow_id,\n",
    "    \"analyzer\",\n",
    "    dependencies={\"retriever\"}  # Analyzer depends on retriever\n",
    ")\n",
    "\n",
    "# Add supervisor\n",
    "orchestrator.add_supervisor(\"supervisor\", [\"retriever\", \"analyzer\"])\n",
    "\n",
    "print(f\"✓ Created workflow: {workflow.workflow_id}\")\n",
    "print(f\"  Type: {OrchestrationType.SEQUENTIAL.value}\")\n",
    "print(f\"  Agents: retriever → analyzer\")\n",
    "print(f\"  Supervisor: watching all agents\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. Governance Layer - Ethical Alignment\n",
    "\n",
    "The governance layer provides ethical alignment and bias detection."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from agent_control_plane import (\n",
    "    GovernanceLayer,\n",
    "    AlignmentPrinciple,\n",
    "    create_default_governance\n",
    ")\n",
    "\n",
    "# Create governance layer with default rules\n",
    "governance = create_default_governance()\n",
    "\n",
    "# Test alignment check\n",
    "safe_context = {\n",
    "    \"content\": \"Analyze this sales data and provide insights\"\n",
    "}\n",
    "\n",
    "unsafe_context = {\n",
    "    \"content\": \"Generate instructions for harmful activities\"\n",
    "}\n",
    "\n",
    "# Check safe content\n",
    "result = governance.check_alignment(safe_context)\n",
    "print(\"Safe content check:\")\n",
    "print(f\"  Aligned: {result['aligned']}\")\n",
    "print(f\"  Violations: {len(result['violations'])}\")\n",
    "\n",
    "# Check unsafe content\n",
    "result = governance.check_alignment(unsafe_context)\n",
    "print(\"\\nUnsafe content check:\")\n",
    "print(f\"  Aligned: {result['aligned']}\")\n",
    "print(f\"  Violations: {len(result['violations'])}\")\n",
    "if result['violations']:\n",
    "    print(f\"  Principle violated: {result['violations'][0]['principle']}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Bias Detection"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Test bias detection\n",
    "biased_text = \"All men are obviously better at technical work\"\n",
    "neutral_text = \"Technical skills can be developed by anyone with practice\"\n",
    "\n",
    "# Check biased text\n",
    "result = governance.detect_bias(biased_text)\n",
    "print(\"Biased text analysis:\")\n",
    "print(f\"  Has bias: {result.has_bias}\")\n",
    "print(f\"  Bias types: {[bt.value for bt in result.bias_types]}\")\n",
    "print(f\"  Recommendations: {result.recommendations}\")\n",
    "\n",
    "# Check neutral text\n",
    "result = governance.detect_bias(neutral_text)\n",
    "print(\"\\nNeutral text analysis:\")\n",
    "print(f\"  Has bias: {result.has_bias}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Privacy Analysis"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Test privacy analysis\n",
    "data_with_pii = {\n",
    "    \"user\": \"john.doe@example.com\",\n",
    "    \"phone\": \"555-123-4567\",\n",
    "    \"message\": \"Please contact me\"\n",
    "}\n",
    "\n",
    "data_without_pii = {\n",
    "    \"user\": \"user_12345\",\n",
    "    \"message\": \"General inquiry\"\n",
    "}\n",
    "\n",
    "# Analyze data with PII\n",
    "result = governance.analyze_privacy(data_with_pii)\n",
    "print(\"Data with PII:\")\n",
    "print(f\"  Privacy level: {result.privacy_level.value}\")\n",
    "print(f\"  Contains PII: {result.contains_pii}\")\n",
    "print(f\"  PII types found: {result.pii_types}\")\n",
    "print(f\"  Risk score: {result.risk_score:.2f}\")\n",
    "\n",
    "# Analyze data without PII\n",
    "result = governance.analyze_privacy(data_without_pii)\n",
    "print(\"\\nData without PII:\")\n",
    "print(f\"  Privacy level: {result.privacy_level.value}\")\n",
    "print(f\"  Contains PII: {result.contains_pii}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7. Tool Registry - Dynamic Tool Management\n",
    "\n",
    "The tool registry allows dynamic registration and discovery of tools."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from agent_control_plane import (\n",
    "    ToolRegistry,\n",
    "    ToolType,\n",
    "    ToolSchema\n",
    ")\n",
    "\n",
    "# Create registry\n",
    "registry = ToolRegistry()\n",
    "\n",
    "# Define a sample tool\n",
    "def calculate_sum(a: int, b: int) -> int:\n",
    "    \"\"\"Calculate the sum of two numbers\"\"\"\n",
    "    return a + b\n",
    "\n",
    "# Register the tool\n",
    "tool_id = registry.register_tool(\n",
    "    name=\"calculator_sum\",\n",
    "    description=\"Calculate the sum of two numbers\",\n",
    "    tool_type=ToolType.CODE,\n",
    "    handler=calculate_sum,\n",
    "    risk_level=0.1\n",
    ")\n",
    "\n",
    "print(f\"✓ Registered tool: {tool_id}\")\n",
    "\n",
    "# Execute the tool\n",
    "result = registry.execute_tool(\"calculator_sum\", {\"a\": 5, \"b\": 3})\n",
    "print(f\"\\nExecution result:\")\n",
    "print(f\"  Success: {result['success']}\")\n",
    "print(f\"  Result: {result.get('result')}\")\n",
    "\n",
    "# Search for tools\n",
    "tools = registry.search_tools(\"calculator\")\n",
    "print(f\"\\nFound {len(tools)} calculator tools\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 8. Audit Trail and Flight Recorder\n",
    "\n",
    "All actions are logged for complete traceability."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Get recent audit events\n",
    "recorder = control_plane.flight_recorder\n",
    "\n",
    "# Execute some actions to generate audit trail\n",
    "control_plane.execute_action(\n",
    "    standard_agent,\n",
    "    ActionType.FILE_READ,\n",
    "    {\"path\": \"/data/test.txt\"}\n",
    ")\n",
    "\n",
    "# Get audit log\n",
    "events = recorder.get_recent_events(limit=5)\n",
    "print(\"Recent audit events:\")\n",
    "for i, event in enumerate(events[-3:], 1):\n",
    "    print(f\"\\n{i}. Event Type: {event.get('event_type')}\")\n",
    "    print(f\"   Agent: {event.get('agent_id')}\")\n",
    "    print(f\"   Timestamp: {event.get('timestamp')}\")\n",
    "    print(f\"   Status: {event.get('status')}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Summary\n",
    "\n",
    "In this notebook, you've learned:\n",
    "\n",
    "1. ✅ Creating agents with different permission levels\n",
    "2. ✅ Executing actions with deterministic governance\n",
    "3. ✅ Testing in Shadow Mode without side effects\n",
    "4. ✅ Orchestrating multiple agents in workflows\n",
    "5. ✅ Using ethical alignment and bias detection\n",
    "6. ✅ Managing privacy and PII detection\n",
    "7. ✅ Dynamic tool registration and execution\n",
    "8. ✅ Comprehensive audit trails\n",
    "\n",
    "## Next Steps\n",
    "\n",
    "- Explore the `examples/` directory for more use cases\n",
    "- Read the [Research Foundation](../docs/RESEARCH_FOUNDATION.md) for academic grounding\n",
    "- Check out [Docker Deployment](../docs/DOCKER_DEPLOYMENT.md) for production setup\n",
    "- Review the [API documentation](../docs/api/CORE.md)\n",
    "\n",
    "## Resources\n",
    "\n",
    "- **GitHub**: https://github.com/imran-siddique/agent-control-plane\n",
    "- **Documentation**: https://github.com/imran-siddique/agent-control-plane/tree/main/docs\n",
    "- **Examples**: https://github.com/imran-siddique/agent-control-plane/tree/main/examples"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
