{"slug":"architecture/TWIN_AS_COGNITIVE_ORCHESTRATOR","title":"The Twin as Cognitive Orchestrator","section":"architecture","sectionLabel":"Architecture","status":"unclassified","type":"document","path":"architecture/TWIN_AS_COGNITIVE_ORCHESTRATOR.mdx","bytes":11723,"description":null,"updated":null,"source":"integratewise/Integratewise-docs-wiki","content":"\n> **Date:** 2026-06-09  \n> **Version:** 1.0.0  \n> **Authority:** Nirmal (Founder)  \n> **Status:** CANONICAL ARCHITECTURE\n\n---\n\n## The Fundamental Distinction\n\n### ❌ What The Twin Is NOT\n\nThe Twin is **NOT:**\n\n- An AI router\n- A model gateway\n- An inference service\n- A RAG engine\n- An execution worker\n\n**Those belong in the Intelligence infrastructure layer.**\n\n### ✅ What The Twin IS\n\nThe Twin is the **Cognitive Orchestrator** — the reasoning layer that:\n\n- Observes Memory (Spine)\n- Observes Objectives\n- Observes Governance state\n- Observes Operations\n- Observes Time\n- Triggers Playbooks\n- Creates Proposals\n- Requests Approval\n- Monitors Outcomes\n- Updates Memory (via Triage Bot)\n\n---\n\n## The Two Orchestration Layers\n\n### Layer 1: Infrastructure Orchestration\n\n**Handled by Workers:**\n\n```\nIntelligence Worker = AI Infrastructure\n├─ AI Router (Workers AI → OpenRouter → Fusion)\n├─ AI Gateway (caching, logging, rate limits)\n├─ RAG Engine (AI Search integration)\n├─ Model fallback chains\n└─ Token management\n\nPipeline Worker = Data Infrastructure\n├─ 8-stage normalizer\n├─ Entity resolution\n├─ Spine writes\n└─ Queue management\n\nKnowledge Worker = Content Infrastructure\n├─ Document ingestion\n├─ Embedding generation\n├─ Search indexing\n└─ Publication pipeline\n```\n\n**These are TOOLS. They do not make decisions.**\n\n---\n\n### Layer 2: Cognitive Orchestration\n\n**Handled by Twin:**\n\n```\nTWIN (Cognitive Orchestrator)\n│\n├─ OBSERVE\n│  ├─ Memory (Spine state)\n│  ├─ Objectives (goals, commitments, deadlines)\n│  ├─ Governance (pending approvals, policy violations)\n│  ├─ Operations (queue health, worker status, errors)\n│  └─ Time (schedules, recurring reviews, staleness)\n│\n├─ REASON\n│  ├─ What should happen next?\n│  ├─ What objective is at risk?\n│  ├─ What review is overdue?\n│  ├─ What commitment is pending?\n│  └─ What governance action is required?\n│\n├─ PROPOSE\n│  ├─ Create proposals (not decisions)\n│  ├─ Attach reasoning + evidence\n│  ├─ Estimate impact + risk\n│  └─ Route to appropriate approver\n│\n├─ REQUEST\n│  ├─ Human-in-the-loop approval\n│  ├─ Governance validation\n│  └─ Policy compliance check\n│\n├─ COORDINATE\n│  ├─ Trigger playbooks (NOT execute)\n│  ├─ Dispatch actions (via Act service)\n│  ├─ Monitor outcomes\n│  └─ Handle failures\n│\n└─ LEARN\n   ├─ Propose memory updates\n   ├─ Route to Triage Bot\n   └─ Wait for governance approval\n```\n\n**The Twin orchestrates. It does not execute.**\n\n---\n\n## Architectural Separation\n\n### Old Mental Model (Chat Agent)\n\n```\nUser\n ↓\nChat\n ↓\nTwin\n ↓\nResponse\n```\n\n**Problem:** Twin is just a conversational interface.\n\n---\n\n### New Model (Cognitive Orchestrator)\n\n```\n            TWIN\n             │\n   ┌─────────┼─────────┐\n   │         │         │\n   ▼         ▼         ▼\nMemory   Governance  Operations\n(Spine)      │         │\n   │         │         │\n   └─────────┼─────────┘\n             │\n             ▼\n         Execution\n```\n\n**The Twin observes, reasons, proposes, and coordinates.**\n\n**The Twin does NOT:**\n\n- Approve (Governance does)\n- Execute (Act + Workers do)\n- Store (Pipeline writes to Spine, Triage Bot writes to Memory)\n- Infer (Intelligence worker runs AI models)\n\n---\n\n## Terminology Consistency\n\n| Term                    | Role                   | Owner                                 |\n| ----------------------- | ---------------------- | ------------------------------------- |\n| **Intelligence Worker** | AI Infrastructure      | CloudFlare Workers                    |\n| **Twin**                | Cognitive Orchestrator | Runs via MCP/Continuity Bridge        |\n| **Governance**          | Decision Authority     | HITL + Policy Engine                  |\n| **Act**                 | Action Dispatcher      | Intelligence worker (act module)      |\n| **Execution**           | Action Performer       | Connector workers (via Act)           |\n| **Spine**               | Persistent Memory      | Pipeline worker (sole writer)         |\n| **Triage Bot**          | Memory Writer          | Governance-gated writer to org_memory |\n\n---\n\n## The Continuity Bridge\n\n**The Continuity Bridge transforms the Twin from a chat interface into an always-on orchestrator.**\n\n### Components\n\n1. **Session Continuity** (continuity worker)\n   - Persistent session state\n   - Checkpoint/resume\n   - Cross-session memory\n\n2. **Scheduled Triggers** (cron + queues)\n   - Morning brief (7am)\n   - Signal sweep (every 6h)\n   - Staleness checks\n   - Commitment reviews\n\n3. **Event-Driven Triggers** (queues)\n   - Spine changes → signal analysis\n   - Queue failures → error review\n   - Governance decisions → action dispatch\n\n4. **State Machines** (workflows)\n   - TriageWorkflow (memory governance)\n   - SignalWorkflow (change detection)\n   - ActWorkflow (action execution)\n\n5. **MCP Tools** (twin-to-infrastructure interface)\n   - memory.\\* (read/propose)\n   - spine.\\* (read entities/relationships)\n   - signal.\\* (read pending signals)\n   - proposal.\\* (create/read proposals)\n\n---\n\n## Twin Runtime Architecture\n\n### Current State (Chat Only)\n\n```\nUser opens chat\n  ↓\nTwin session starts\n  ↓\nUser asks question\n  ↓\nTwin queries MCP tools\n  ↓\nTwin generates response\n  ↓\nUser closes chat\n  ↓\nTwin session ends ❌ (memory lost)\n```\n\n**Problem:** Twin has no persistence, no agency, no continuity.\n\n---\n\n### Target State (Always-On Orchestrator)\n\n```\nSystem starts\n  ↓\nTwin runtime initializes\n  ↓\n┌─────────────────────────┐\n│   TWIN OBSERVE LOOP     │\n│  (runs every 5 minutes) │\n│                         │\n│  1. Check Spine changes │\n│  2. Check pending items │\n│  3. Check time triggers │\n│  4. Reason about state  │\n│  5. Create proposals    │\n│  6. Dispatch actions    │\n└─────────────────────────┘\n  ↓\nHuman opens chat (optional)\n  ↓\nTwin resumes from checkpoint\n  ↓\nHuman reviews proposals\n  ↓\nHuman approves/rejects\n  ↓\nTwin dispatches actions\n  ↓\nTwin monitors outcomes\n  ↓\nTwin proposes memory update\n  ↓\nTriage Bot governs + writes\n  ↓\nLoop continues ✅\n```\n\n**The Twin operates continuously, with or without a human in the chat.**\n\n---\n\n## Implementation Status\n\n### ✅ Infrastructure Layer (Phase 1-2)\n\n- ✅ Intelligence worker (AI router + RAG)\n- ✅ Pipeline worker (normalizer + Spine writer)\n- ✅ Continuity worker (session state)\n- ✅ MCP connector (18 tools)\n- ✅ Queue infrastructure\n- ✅ Cron triggers (code ready, manual wiring pending)\n\n### ⏳ Cognitive Orchestrator Layer (Phase 3-4)\n\n- ⏳ Twin runtime (always-on loop)\n- ⏳ Observe loop (5-minute checks)\n- ⏳ Reasoning engine (what's next?)\n- ⏳ Proposal generation (structured suggestions)\n- ⏳ Action coordination (dispatch → monitor → learn)\n- ⏳ MorningBriefWorkflow (durable execution)\n- ⏳ SignalWorkflow (change detection → proposal)\n- ⏳ ActWorkflow (approved proposal → execution)\n\n---\n\n## Phase 3: Wire The Twin Runtime\n\n### Step 1: Create Twin Orchestrator Worker\n\n**NOT a new AI infrastructure worker.**\n\n**This is a state machine that:**\n\n1. Runs on a schedule (every 5 minutes)\n2. Queries MCP tools (memory, spine, signals, proposals)\n3. Reasons about what should happen next\n4. Creates structured proposals\n5. Routes proposals to governance\n6. Monitors action outcomes\n7. Proposes memory updates\n\n**File:** `services/twin-orchestrator/src/index.ts`\n\n```typescript\n  async scheduled(event: ScheduledEvent, env: Env) {\n    // Every 5 minutes: Twin observe loop\n    const context = await buildTwinContext(env);\n    const reasoning = await reasonAboutContext(context, env);\n    const proposals = await generateProposals(reasoning, env);\n    const dispatched = await dispatchApproved(proposals, env);\n    await monitorOutcomes(dispatched, env);\n  },\n};\n```\n\n---\n\n### Step 2: Twin Context Builder\n\n```typescript\nasync function buildTwinContext(env: Env) {\n  // Query MCP tools via service bindings\n  const memory = await env.MCP_CONNECTOR.fetch(\"/tools/memory.search_org\");\n  const signals = await env.MCP_CONNECTOR.fetch(\"/tools/signal.list\");\n  const proposals = await env.MCP_CONNECTOR.fetch(\"/tools/proposal.list\");\n  const spineChanges = await env.PIPELINE.fetch(\"/v1/spine/recent-changes\");\n\n  return {\n    memory: await memory.json(),\n    signals: await signals.json(),\n    proposals: await proposals.json(),\n    spineChanges: await spineChanges.json(),\n    timestamp: new Date().toISOString(),\n  };\n}\n```\n\n---\n\n### Step 3: Reasoning Engine\n\n```typescript\nasync function reasonAboutContext(context: TwinContext, env: Env) {\n  // Use Intelligence worker's AI router for reasoning\n  const response = await env.INTELLIGENCE.fetch(\"/v1/ai/reason\", {\n    method: \"POST\",\n    body: JSON.stringify({\n      systemPrompt: \"You are the Twin orchestrator. Reason about what should happen next.\",\n      context,\n      tier: \"balanced\", // Use OpenRouter or Workers AI\n    }),\n  });\n\n  return await response.json();\n}\n```\n\n---\n\n### Step 4: Proposal Generation\n\n```typescript\nasync function generateProposals(reasoning: Reasoning, env: Env) {\n  // Twin creates proposals, does NOT execute\n  const proposals = [];\n\n  for (const action of reasoning.suggestedActions) {\n    const proposal = {\n      type: action.type,\n      target: action.target,\n      reasoning: action.reasoning,\n      impact: action.impact,\n      risk: action.risk,\n      requires_approval: true,\n    };\n\n    // Submit to governance via MCP\n    const res = await env.MCP_CONNECTOR.fetch(\"/tools/proposal.create\", {\n      method: \"POST\",\n      body: JSON.stringify(proposal),\n    });\n\n    proposals.push(await res.json());\n  }\n\n  return proposals;\n}\n```\n\n---\n\n## The Key Insight\n\n**The Twin is NOT competing with the Intelligence worker.**\n\n**The Intelligence worker provides:**\n\n- AI inference (Workers AI, OpenRouter)\n- RAG search (AI Search)\n- Model routing\n- Token management\n\n**The Twin provides:**\n\n- Strategic reasoning (what should happen next?)\n- Continuity (persistent state across sessions)\n- Coordination (trigger → approve → dispatch → monitor)\n- Learning (propose memory updates)\n\n**They are complementary, not redundant.**\n\n---\n\n## Success Criteria\n\n### Twin is a Cognitive Orchestrator When:\n\n- ✅ Runs on schedule (not just in chat)\n- ✅ Observes system state continuously\n- ✅ Reasons about what should happen next\n- ✅ Creates proposals (not decisions)\n- ✅ Routes to appropriate approvers\n- ✅ Coordinates actions (via Act service)\n- ✅ Monitors outcomes\n- ✅ Proposes memory updates (via Triage Bot)\n- ✅ Maintains continuity across sessions\n\n---\n\n## Next Steps\n\n### Phase 3: Twin Runtime\n\n1. Create `services/twin-orchestrator` worker\n2. Implement observe loop (5-minute schedule)\n3. Wire to MCP tools (memory, spine, signals, proposals)\n4. Implement reasoning engine (via Intelligence AI router)\n5. Implement proposal generation\n6. Implement action coordination\n7. Test end-to-end: observe → reason → propose → approve → dispatch → monitor\n\n### Phase 4: Workflows\n\n1. MorningBriefWorkflow (7am trigger)\n2. SignalWorkflow (spine change → signal → proposal)\n3. ActWorkflow (approved proposal → execution)\n\n---\n\n**Document Status:** CANONICAL ARCHITECTURE  \n**Last Updated:** 2026-06-09  \n**Authority:** Nirmal (Founder)  \n**Implementation:** Phase 3\n"}