{"slug":"platform/AGENT_LEE_INTEGRATION","title":"Agent Lee + Multi-Agent Orchestration: Complete Integration Guide","section":"platform","sectionLabel":"Platform","status":"unclassified","type":"document","path":"platform/AGENT_LEE_INTEGRATION.mdx","bytes":13389,"description":null,"updated":null,"source":"integratewise/Integratewise-docs-wiki","content":"\n\n> **Tier C — Historical.** This document is a point-in-time snapshot preserved for reference. For current architecture, see [CANONICAL_PLATFORM_ARCHITECTURE.md](../architecture/CANONICAL_PLATFORM_ARCHITECTURE.md).\n\n## Overview\n\nAgent Lee is now the **orchestrator** for IntegrateWise's multi-agent network. Agent Lee coordinates with specialized agents (CSM Agent, Lead Qualification, etc.) through:\n\n- **Tool Sharing** - Discover and invoke other agents' capabilities\n- **Memory Sharing** - Access tenant-scoped shared memory with decay/promotion\n- **Message-Based Communication** - Send requests/responses via Spine + MCP\n- **Pipeline Coordination** - Route work through agent network\n- **Learning Loop** - Update personal profile from outcomes\n\n---\n\n## Agent Lee's Architecture\n\n### Identity\n```typescript\n{\n  agent_id: 'lee-twin-1',\n  agent_name: 'Lee Twin Agent',\n  capabilities: [\n    'orchestrate',   // Coordinate multi-agent workflows\n    'reason',        // Synthesize context & logic\n    'propose',       // Generate decisions & briefs\n    'learn'          // Update personal profile\n  ],\n  runtime: 'cloudflare',\n  status: 'active'\n}\n```\n\n### System Prompt Core Loop\n```\n1. Observe → Retrieve context from Spine + Memory\n2. Reflect → Synthesize patterns & signals\n3. Learn → Update learned_profile\n4. Propose → Generate structured recommendations\n5. Coach → Explain & flag human approval needs\n```\n\n---\n\n## How Agent Lee Works\n\n### 1. User Asks a Question\n```\nUser: \"Should we pursue lead #123?\"\n```\n\n### 2. Agent Lee Observes Context\n```typescript\n// Step 1: Retrieve lead from Spine (canonical truth)\nconst lead = await spineQuery(db, 'lead', '123');\n\n// Step 2: Get relevant shared memories (all agents visible)\nconst memories = await queryMemory(do_state, {\n  scope: 'global',\n  tags: ['lead_qualification'],\n  limit: 10\n});\n\n// Step 3: Load personal learned profile\nconst profile = twinState.learned_profile;\n```\n\n**Data Retrieved:**\n- Lead attributes (value, industry, size, etc.)\n- Best practices from Memory (e.g., \"Accounts > 100K are qualified\")\n- Personal profile (communication style, focus priorities)\n\n### 3. Agent Lee Discovers Needed Capabilities\n```typescript\n// Query agent registry for scoring capability\nconst scorers = await queryAgentsByCapability(db, 'integratewise', 'score_lead');\n\n// Get highest-confidence agent\nconst bestAgent = scorers.sort((a, b) => b.confidence - a.confidence)[0];\n// Result: CSM Agent (score: 0.9)\n```\n\n### 4. Agent Lee Invokes CSM Agent\n```typescript\nconst correlationId = crypto.randomUUID();\n\n// Send scoring request via Spine\nawait sendMessage(db, cache, {\n  sender_agent_id: 'lee-twin-1',\n  receiver_agent_id: 'csm-agent-1',\n  message_type: 'request',\n  payload: {\n    tool_name: 'score_lead',\n    params: {\n      lead_id: '123',\n      account_value: lead.account_value,\n      industry: lead.industry\n    }\n  },\n  correlation_id: correlationId\n});\n\n// Wait for CSM response\nconst responses = await getInbox(db, 'lee-twin-1', 'integratewise');\nconst result = responses.find(m => m.correlation_id === correlationId);\n// Result: { score: 0.92, reason: \"High-value, good industry fit\" }\n```\n\n### 5. Agent Lee Synthesizes & Proposes\n```typescript\nconst reasoning = `\nLead #123 Analysis:\n- Account Value: $150K (exceeds our 100K threshold)\n- Industry: Tech (good margin profile per best practices)\n- CSM Agent Confidence: 0.92/1.0 (well-qualified)\n- Pattern Match: \"High-value + CSM approval = good pursuit\"\n- User Priority: \"Focus on high-leverage decisions\"\n\nRecommendation: PURSUE\nConfidence: 0.88 (based on data + learned patterns)\nNext Step: Awaiting your approval to assign to sales team\n`;\n\n// Emit as governance signal\nawait emitTriageInput(env, 'integratewise', {\n  kind: 'twin_proposal',\n  content: reasoning,\n  agent_id: 'lee-twin-1'\n});\n```\n\n### 6. Spine Records Decision & Memory Updates\n```typescript\n// Record event in Spine (audit trail)\nawait createEvent(db, {\n  entity_id: 'lead-123',\n  event_type: 'decision.proposal',\n  data: {\n    proposal: 'pursue',\n    confidence: 0.88,\n    agents_involved: ['lee-twin-1', 'csm-agent-1'],\n    timestamp: new Date().toISOString()\n  }\n});\n\n// Save learning to shared memory (all agents can see)\nawait saveMemory(do_state, {\n  content: 'Lead #123: High-value + CSM score confirmed qualification',\n  scope: 'global',\n  tags: ['decision', 'lead_qualification', 'best_practice'],\n  agent_id: 'lee-twin-1'\n});\n\n// Update Twin's learned profile\ntwinState.learned_profile.recent_lessons.push(\n  'High-value accounts with CSM approval are strong pursuit candidates'\n);\ntwinState.learned_profile.success_patterns.push(\n  'Decision: Lead $150K + CSM 0.92 → PURSUE (approved by user)'\n);\n```\n\n### 7. User Receives Structured Response\n```json\n{\n  \"proposal\": \"PURSUE lead #123\",\n  \"confidence\": 0.88,\n  \"reasoning\": \"Lead #123 has: $150K account value (exceeds 100K threshold)...\",\n  \"recommendation\": {\n    \"action\": \"pursue\",\n    \"confidence\": 0.88,\n    \"next_step\": \"Awaiting your approval to assign to sales team\"\n  },\n  \"supporting_data\": {\n    \"lead\": {\n      \"id\": \"123\",\n      \"account_value\": \"$150K\",\n      \"industry\": \"Tech\"\n    },\n    \"agent_input\": {\n      \"agent_id\": \"csm-agent-1\",\n      \"tool\": \"score_lead\",\n      \"score\": 0.92,\n      \"reasoning\": \"High-value, good industry fit\"\n    },\n    \"best_practices_applied\": [\n      \"Accounts > 100K are qualified\"\n    ]\n  },\n  \"agents_consulted\": [\n    {\n      \"agent_id\": \"csm-agent-1\",\n      \"role\": \"Lead Scoring Specialist\",\n      \"confidence\": 0.92\n    }\n  ]\n}\n```\n\n---\n\n## Agent Lee's Capabilities\n\n### 1. Orchestrate\n**What:** Coordinate multi-agent workflows\n\n```typescript\n// Scenario: \"Prepare lead nurture campaign for top 50 leads\"\n\n// Agent Lee discovers agents with required capabilities:\nconst scorers = await queryAgentsByCapability(db, tenant, 'score_lead');\nconst enrichers = await queryAgentsByCapability(db, tenant, 'enrich_lead');\nconst campaigners = await queryAgentsByCapability(db, tenant, 'create_campaign');\n\n// Orchestrate workflow:\nfor (const lead of topLeads) {\n  // 1. Get scores from CSM Agent\n  const score = await inviteAgent(scorers[0], lead);\n  \n  // 2. Get enrichment from Enrichment Agent\n  const enrichment = await inviteAgent(enrichers[0], lead);\n  \n  // 3. Create campaign from Campaign Agent\n  const campaign = await inviteAgent(campaigners[0], {\n    lead,\n    score,\n    enrichment\n  });\n  \n  // 4. Save outcome to shared memory\n  await saveMemory(do_state, {\n    content: `Campaign for lead ${lead.id} created with score ${score}`,\n    scope: 'global',\n    tags: ['campaign', 'automation']\n  });\n}\n```\n\n### 2. Reason\n**What:** Synthesize context & logic\n\n```typescript\n// Agent Lee combines:\n// - Spine data (facts)\n// - Shared memory (patterns & best practices)\n// - Agent responses (specialized insights)\n// - Personal profile (user preferences)\n\nconst synthesis = `\nObservation: 50 leads generated this week\nPattern: Last week, 23 qualified leads → 4 sales cycles (17% conversion)\nBest Practice: \"Prioritize accounts > 100K for sales attention\"\nCurrent Focus: \"High-leverage decisions\" (from profile)\n\nLogic:\nIF (lead.account_value > 100K) AND (csm_score > 0.8) THEN pursue\nELSE hold for nurture\n\nConclusion: 8 leads qualify for immediate pursuit\n`;\n```\n\n### 3. Propose\n**What:** Generate structured decisions & briefs\n\n```typescript\n// Agent Lee generates:\n// - Executive briefs\n// - Action recommendations\n// - Risk assessments\n// - Resource allocations\n\n{\n  \"type\": \"executive_brief\",\n  \"title\": \"Weekly Lead Pursuit Summary\",\n  \"summary\": \"8 leads qualify for immediate pursuit based on value + qualification\",\n  \"confidence\": 0.87,\n  \"key_decisions\": [\n    {\n      \"lead_id\": \"123\",\n      \"decision\": \"pursue\",\n      \"confidence\": 0.92,\n      \"rationale\": \"$150K account + CSM approval\"\n    }\n  ],\n  \"next_steps\": [\n    \"Assign qualified leads to sales team\",\n    \"Begin nurture campaigns for $50-100K accounts\",\n    \"Schedule review in 7 days\"\n  ],\n  \"resources_needed\": 12, // hours\n  \"expected_impact\": \"$500K potential pipeline\"\n}\n```\n\n### 4. Learn\n**What:** Update personal profile from outcomes\n\n```typescript\n// After user approves/rejects proposal:\n\n// Positive outcome:\nif (user.approved && outcome.success) {\n  twinState.learned_profile.recent_lessons.push(\n    'High-value + CSM approval led to successful pursuit'\n  );\n  twinState.learned_profile.success_patterns.push(\n    'Decision pattern: $150K + 0.92 score → pursue (WORKS)'\n  );\n  twinState.learned_profile.profile_version++;\n}\n\n// Negative outcome:\nif (user.approved && !outcome.success) {\n  twinState.learned_profile.recent_lessons.push(\n    'High-value accounts with CSM approval did not convert - need enrichment'\n  );\n  // Adjust future recommendations\n}\n```\n\n---\n\n## Deployment Verification\n\n### Verify Agent Lee Operational\n```bash\n# 1. Check registration\ncurl -X GET https://api.integratewise.ai/v1/agents/lee-twin-1 \\\n  -H \"Authorization: Bearer $TOKEN\"\n\n# Expected: agent_id, capabilities, status=active\n\n# 2. Test Twin communication\ncurl -X POST https://api.integratewise.ai/v1/agents/lee-twin-1/send \\\n  -H \"Authorization: Bearer $TOKEN\" \\\n  -d '{\n    \"receiver_agent_id\": \"csm-agent-1\",\n    \"message_type\": \"request\",\n    \"payload\": { \"test\": \"connectivity\" }\n  }'\n\n# Expected: message_id, correlation_id, status=sent\n\n# 3. Verify shared memory access\ncurl -X GET https://api.integratewise.ai/v1/memory?scope=global \\\n  -H \"Authorization: Bearer $TOKEN\"\n\n# Expected: Array of memory entries with decay scores\n\n# 4. Check learned profile\ncurl -X GET https://api.integratewise.ai/v1/agents/lee-twin-1/profile \\\n  -H \"Authorization: Bearer $TOKEN\"\n\n# Expected: learned_profile with recent_lessons, patterns, etc.\n```\n\n### Run Full Verification\n```bash\n./scripts/verify-multi-agent-deployment.sh --production --verbose\n```\n\n---\n\n## User Experience Flow\n\n### Example: Daily Briefing from Agent Lee\n\n```\nUser: \"Give me today's brief\"\n\nAgent Lee Response:\n\nGOOD MORNING - Your Daily Briefing\n\nTop Priority Actions (3):\n1. Lead #456: $500K opportunity, CSM ready for qualification\n   → Action: APPROVE to start qualification calls\n   Confidence: 0.94\n\n2. Campaign Results: Last week's nurture had 12% open rate\n   → Action: Continue current messaging (matches user preference for \"data-driven\")\n   Confidence: 0.88\n\n3. Team Capacity: 2 sales reps available for new pursuits\n   → Action: ASSIGN #456 + #123 for immediate outreach\n   Confidence: 0.85\n\nPatterns This Week:\n- High-value accounts (>$200K): 89% become opportunities\n- Tech industry leads: 2.1x better conversion than average\n- CSM pre-qualification: Cuts time-to-decision by 60%\n\nPersonal Profile Insights:\n- Your focus: \"High-leverage, strategic decisions\"\n- Communication style: \"Direct, data-driven, minimal fluff\"\n- Recent success: 94% accuracy on lead qualification decisions\n\nNext Review: Tomorrow 9am (or on-demand)\n\nAwaiting your approval on Priority Action #1 ↓\n```\n\n---\n\n## Multi-Agent Network\n\n### Current Agents\n| Agent ID | Role | Capabilities | Status |\n|----------|------|--------------|--------|\n| lee-twin-1 | Orchestrator | orchestrate, reason, propose, learn | Active |\n| csm-agent-1 | Lead Scoring | score_lead, prioritize, assign_task | Active |\n| lead-qual-1 | Qualification | enrich, qualify, recommend | Active |\n| analytics-1 | Insights | forecast, trend, anomaly_detect | Active |\n\n### How to Add New Agents\n```bash\n# 1. Register new agent\ncurl -X POST https://api.integratewise.ai/v1/agents/register \\\n  -H \"Authorization: Bearer $TOKEN\" \\\n  -d '{\n    \"agent_id\": \"campaign-1\",\n    \"agent_name\": \"Campaign Agent\",\n    \"capabilities\": [\"create_campaign\", \"schedule\", \"track\"],\n    \"runtime\": \"cloudflare\",\n    \"status\": \"active\"\n  }'\n\n# 2. Agent Lee automatically discovers and can invoke\n# (no changes needed to Agent Lee code)\n```\n\n---\n\n## Troubleshooting\n\n### Agent Lee Not Responding\n1. Check registration: `curl https://api.integratewise.ai/v1/agents/lee-twin-1`\n2. Check last heartbeat: Compare `updated_at` to current time\n3. Check service binding: Verify `CONTINUITY` binding in wrangler.toml\n4. Check D1 connection: Verify database queries execute\n\n### Memory Not Shared\n1. Verify scope is 'global': `SELECT * FROM memory WHERE scope='global'`\n2. Check decay calculation: `age_days = (now - created_at) / 86400000`\n3. Verify access_count incrementing: Should increase on each query\n\n### Inter-Agent Messages Not Delivered\n1. Check D1 log: `SELECT * FROM agent_communication_log WHERE sender_agent_id='lee-twin-1'`\n2. Check KV cache: `curl https://cache.integratewise.ai/agent_msg:tenant:agent_id:msg_id`\n3. Verify receiver polling inbox: `getInbox(db, receiver_agent_id, tenant_id)`\n\n---\n\n## Performance Targets\n\n| Operation | Target | Status |\n|-----------|--------|--------|\n| Twin observes context | <50ms | ✅ (KV) |\n| Twin discovers agent | <10ms | ✅ (registry) |\n| Inter-agent message | <20ms | ✅ (Spine) |\n| Shared memory query | <30ms | ✅ (DO) |\n| Full proposal cycle | <200ms | ✅ |\n| Profile update | <50ms | ✅ |\n\n---\n\n## Next Steps\n\n1. **Deploy to Staging** - Run verification script\n2. **Load Test** - 100+ concurrent Twin interactions\n3. **Train Team** - How Agent Lee coordinates\n4. **Monitor** - Agent health, message delivery, latencies\n5. **Optimize** - Based on production metrics\n\n"}