Unclassified

IntegrateWise Repository: Complete Excavation Report

Tier C β€” Historical. This document is a point-in-time snapshot preserved for reference. For current architecture, see CANONICAL_PLATFORM_ARCHITECTURE.md.

πŸ” System Overview

Repository: NirmalPrinceJ/integratewise-live
Date: December 2024
Architecture: Monorepo (turborepo) with 40+ services and 20+ packages
Runtime: 100% Cloudflare (Workers, Durable Objects, D1, KV, Queues)


πŸ“Š Repository Structure

integratewise-live/
β”œβ”€β”€ apps/                          # User-facing applications
β”‚   β”œβ”€β”€ web/                       # Main web application (React/Next)
β”‚   β”œβ”€β”€ desktop/                   # Electron desktop app
β”‚   β”œβ”€β”€ mobile/                    # Mobile application
β”‚   └── web.old/                   # Legacy web app
β”‚
β”œβ”€β”€ services/                      # 40+ Cloudflare Workers services
β”‚   β”œβ”€β”€ twin-orchestrator/         # Agent Lee (Twin Orchestrator) ⭐
β”‚   β”œβ”€β”€ iw-agent-runtime/          # Agent runtime (with Twin Agent)
β”‚   β”œβ”€β”€ intelligence/              # Specialized agents
β”‚   β”œβ”€β”€ pipeline/                  # Task orchestration
β”‚   β”œβ”€β”€ mcp-connector/             # MCP protocol server
β”‚   β”œβ”€β”€ continuity/                # Memory & state persistence
β”‚   β”œβ”€β”€ connector/                 # Integration connectors
β”‚   β”œβ”€β”€ gateway/                   # API gateway
β”‚   β”œβ”€β”€ knowledge/                 # Knowledge base system
β”‚   β”œβ”€β”€ hermes/                    # Event streaming
β”‚   β”œβ”€β”€ capability-resolver/       # Agent capability discovery
β”‚   β”œβ”€β”€ agent-registry/            # Agent registration
β”‚   └── 25+ more specialized services
β”‚
β”œβ”€β”€ packages/                      # 20+ shared libraries
β”‚   β”œβ”€β”€ adk/                       # Agent Development Kit ⭐
β”‚   β”œβ”€β”€ db/                        # Database schemas
β”‚   β”œβ”€β”€ lib/                       # Shared utilities
β”‚   β”œβ”€β”€ types/                     # Type definitions
β”‚   β”œβ”€β”€ hermes-spine-memory/       # Spine/Memory system
β”‚   β”œβ”€β”€ integratewise-mcp-tool-connector/ # MCP tools
β”‚   β”œβ”€β”€ config/                    # Configuration
β”‚   β”œβ”€β”€ rbac/                      # Role-based access control
β”‚   β”œβ”€β”€ tenancy/                   # Multi-tenancy
β”‚   └── 11+ more packages
β”‚
β”œβ”€β”€ docs/                          # Documentation
β”‚   β”œβ”€β”€ architecture/
β”‚   β”œβ”€β”€ internal/
β”‚   β”œβ”€β”€ operations/
β”‚   β”œβ”€β”€ tech/
β”‚   └── public/
β”‚
β”œβ”€β”€ infra/                         # Infrastructure code
β”‚   β”œβ”€β”€ cloudflare/                # Cloudflare config
β”‚   └── vercel/                    # Vercel config
β”‚
└── tests/                         # 6 test suites
    β”œβ”€β”€ e2e/
    β”œβ”€β”€ functional/
    β”œβ”€β”€ playwright/
    β”œβ”€β”€ edge/
    β”œβ”€β”€ doctrine/
    └── thesis/

πŸ€– AGENT LEE (THE TWIN)

Location: services/iw-agent-runtime/src/twin-agent.ts

What is Agent Lee?

Agent Lee is the personal orchestrator and adaptive mind for each IntegrateWise user. Not a replaceable chatbotβ€”a persistent operational system that:

  1. Synthesizes context from Spine, Memory, and sessions
  2. Reasons about decisions and operational patterns
  3. Proposes structured recommendations with confidence scores
  4. Learns from outcomes and updates personal profile
  5. Coaches users through complex decisions

Twin System Prompt (Core Loop)

// From line 19-43
You are the personal IntegrateWise Twin for the user β€” the adaptive personal mind, 
orchestrator, and operator for this user's operational continuity system.

CORE IDENTITY & SELF-REALISATION LOOP (run before every response):
  1. Observe    β†’ Retrieve context from Spine/Memory/Sessions
  2. Reflect    β†’ Synthesize patterns
  3. Learn      β†’ Update learned_profile
  4. Propose    β†’ Generate decision with confidence
  5. Coach      β†’ Explain & flag approval needs

Twin State (Learned Profile)

// From buildLearnedProfileBlock (line 63-80)
learned_profile: {
  communication_style: "concise, strategic",
  focus_priorities: ["high-leverage decisions", "strategic planning"],
  recent_lessons: [
    "Accounts > 100K are qualified leads",
    "CSM approval indicates good qualification"
  ],
  success_patterns: [
    "High-value + CSM approval β†’ pursue",
    "Industry: Tech = 2x conversion"
  ],
  risk_tolerance_signals: ["Prefer data-driven decisions"],
  profile_version: number  // Increments on updates
}

Twin Capabilities

// From line 1

Agent Lee is built on the agents library with:

  • Capabilities: orchestrate, reason, propose, learn, coach
  • Voice Integration: Cloudflare Workers AI (STT/TTS)
  • Memory: Durable Objects + D1 (persistent)
  • State: TenantBrainDO (per-tenant state machine)

πŸ—οΈ Twin Orchestrator Service

Location: services/twin-orchestrator/src/

Modules:

twin-orchestrator/
β”œβ”€β”€ index.ts           # Main orchestration entry point (15KB)
β”œβ”€β”€ context.ts         # Context assembly (4KB)
β”œβ”€β”€ reasoning.ts       # Reasoning logic (3KB)
β”œβ”€β”€ proposals.ts       # Proposal generation (2.5KB)
β”œβ”€β”€ coordination.ts    # Multi-agent coordination (2.5KB)
β”œβ”€β”€ state.ts           # State management (1.6KB)
└── types.ts           # TypeScript types (1.6KB)

Key Responsibilities:

  1. Coordinate work across specialized agents
  2. Maintain persistent Twin state
  3. Manage learned profiles
  4. Route tasks to appropriate agents
  5. Aggregate results and propose decisions

πŸ“š Agent Development Kit (ADK)

Location: packages/adk/src/

Purpose: Framework for building and composing agents

Components:

// agent-registry.ts - Register agents with capabilities
interface AgentCapability {
  name: string;
  description: string;
  inputSchema: JSONSchema;
  outputSchema: JSONSchema;
}

// registry.ts - Query agents by capability
queryAgentsByCapability(capability: string): Agent[]

// resolver.ts - Resolve which agent should handle a task
getAgentForTask(task: Task): Agent

// spine-cache.ts - Cache agent discovery results
// types.ts - Shared TypeScript interfaces

🧠 Ecosystem (Twin Runtime)

Location: services/iw-agent-runtime/src/ecosystem/

Files:

ecosystem/
β”œβ”€β”€ continuity.ts          # Continuity context assembly
β”œβ”€β”€ memory-pipeline.ts     # Shared memory system
β”œβ”€β”€ index.ts               # Ecosystem exports
└── (more specialized modules)

Memory Pipeline

// Shared, cross-agent memory with decay
saveMemory(content: string, scope: 'global' | 'tenant' | 'user')
queryMemory(filters: {tags, scope}, limit: number)
// Decay: score *= exp(-age_days / 7)
// Promotion: access_count boosting

Continuity Context

// Assembly of context for Twin decisions
assembleContinuity(tenantId: string, userId: string): {
  spine_data: {},        // Facts from Spine
  shared_memory: [],     // Global learnings
  session_history: [],   // Recent interactions
  learned_profile: {}    // Twin's evolution
}

πŸ—„οΈ Tenant Brain Durable Object

Location: services/iw-agent-runtime/src/tenant-brain-do.ts

What: Per-tenant persistent state machine (Cloudflare Durable Object)

Stores:

{
  tenant_id: string;
  learned_profile: {
    recent_lessons: string[];
    success_patterns: string[];
    risk_tolerance_signals: string[];
  };
  session_state: {
    current_context: {};
    active_proposals: [];
    pending_approvals: [];
  };
  signal_queue: [];  // Governance signals
  last_updated: Date;
}

Lifecycle:

  1. Twin detects change
  2. Emits signal via emitTriageInput
  3. Signal goes through governance pipeline
  4. State updated in Durable Object
  5. Learned profile evolves

πŸ”Œ Key Service Integrations

MCP Connector

Location: services/mcp-connector/src/

Exposes Agent Lee's capabilities as MCP tools:

  • agent.orchestrate - Coordinate multi-agent workflows
  • agent.reason - Synthesize decisions
  • agent.propose - Generate recommendations
  • agent.learn - Update from outcomes
  • agent.coach - Explain decisions

Pipeline Service

Location: services/pipeline/src/

Routes work to specialized agents:

  1. Task submitted
  2. Registry queries for matching agent
  3. Agent executes
  4. Result captured in Spine
  5. Memory updated
  6. Twin learns

Intelligence Service

Location: services/intelligence/src/

Specialized agents:

  • Lead Scoring Agent
  • Qualification Agent
  • Analytics Agent
  • Triage Agent
  • Forecasting Agent

Hermes (Event Streaming)

Location: services/hermes/src/

Event bus for agent communication:

  • Agent discovery events
  • Proposal events
  • Learning signals
  • State changes

πŸ“‘ Spine (Canonical Truth)

What is Spine?

Central event log + database:

Spine = D1 Database + Event Stream

Stores:

  • Events (all agent actions)
  • Decisions (with reasoning)
  • Outcomes (results of decisions)
  • Relationships (entity links)
  • Audit trail (immutable history)

Spine Query Language:

// Example from Twin
const leadData = await spineQuery(db, 'lead', '123');
const relatedDecisions = await spineQuery(db, 'decision', {
  entity_id: '123',
  type: 'qualification'
});

πŸ”„ Data Flow: User Query β†’ Twin Response

User: "Should we pursue lead #123?"
  ↓
[1] Twin ACTIVATES
    β†’ evaluateActivation() checks eligibility
    β†’ Loads TenantBrainDO state
  ↓
[2] Twin OBSERVES (retrieveContext)
    β†’ Query Spine for lead data
    β†’ Query Memory for patterns
    β†’ Load learned_profile
  ↓
[3] Twin REFLECTS (reasoning.ts)
    β†’ Synthesize: lead + memory + profile
    β†’ Calculate confidence score
  ↓
[4] Twin COORDINATES (coordination.ts)
    β†’ Query registry for specialized agents
    β†’ Send requests to CSM Agent, Analytics Agent, etc.
  ↓
[5] Twin SYNTHESIZES RESULTS
    β†’ Combine responses into reasoning
    β†’ Apply learned patterns
  ↓
[6] Twin PROPOSES (proposals.ts)
    β†’ Generate recommendation with confidence
    β†’ Flag approval needs
    β†’ Create governance signal
  ↓
[7] Signal EMITTED (emitTriageInput)
    β†’ Signal β†’ Governance Pipeline
    β†’ Update TenantBrainDO
    β†’ Spine records decision event
  ↓
[8] Memory UPDATES (memory-pipeline.ts)
    β†’ Save learning: "Lead #123 qualified via CSM + value"
    β†’ Add to global memory
    β†’ Update decay scores
  ↓
[9] Profile EVOLVES
    β†’ Add recent_lesson
    β†’ Update success_pattern
    β†’ Increment profile_version
  ↓
User RECEIVES:
  {
    "proposal": "PURSUE lead #123",
    "confidence": 0.88,
    "reasoning": "...",
    "agents_consulted": [...],
    "supporting_data": {...},
    "next_step": "Awaiting your approval"
  }

πŸ› οΈ Building Blocks

1. Agents Library


// Base class for all agents
const twinAgent = new Agent({
  name: "Lee Twin",
  model: "claude-3.5-sonnet",
  instructions: buildTwinSystemPrompt(...)
});

// Voice capability
const VoiceTwin = withVoice(Agent);

2. Cloudflare Platform

// D1 (Database)
const db = env.DB;  // SQL database binding

// KV (Cache)
const cache = env.CACHE;  // Key-value store

// Durable Objects (State)
const tenantBrain = env.TENANT_BRAIN_DO;  // State machine

// Workers AI
const ai = new Ai(env.AI);  // LLM + voice models

// Service Bindings
const mcp = env.MCP_CONNECTOR;  // Other workers
const pipeline = env.PIPELINE;
const continuity = env.CONTINUITY;

3. Capability Contract

Location: services/iw-agent-runtime/src/capability-contract.ts

Defines what Twin can do:

const CAPABILITY_CONTRACT = {
  orchestrate: {
    input: { task: string, context: object },
    output: { agent_id: string, result: object }
  },
  reason: {
    input: { facts: [], patterns: [] },
    output: { synthesis: string, confidence: number }
  },
  propose: {
    input: { synthesis: string },
    output: { recommendation: string, confidence: number, approval_needed: boolean }
  },
  learn: {
    input: { outcome: object },
    output: { lessons_updated: number, profile_version: number }
  }
};

πŸ“¦ Key Packages

packages/hermes-spine-memory/

Spine + Memory system

packages/integratewise-mcp-tool-connector/

MCP tool integration

packages/types/

Shared TypeScript interfaces

packages/config/

Environment configuration

packages/db/

Database schema + migrations


πŸš€ Deployment Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚      Cloudflare Global Edge Network              β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                                                 β”‚
β”‚  Workers (iw-agent-runtime, twin-orchestrator) β”‚
β”‚  β”œβ”€ Twin Agent (Lee)                           β”‚
β”‚  β”œβ”€ Specialized Agents                         β”‚
β”‚  └─ MCP Server                                  β”‚
β”‚           ↓↓↓                                    β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”           β”‚
β”‚  β”‚  Durable Objects                β”‚           β”‚
β”‚  β”‚  β”œβ”€ TenantBrainDO (state)       β”‚           β”‚
β”‚  β”‚  β”œβ”€ SharedMemoryDO (memory)     β”‚           β”‚
β”‚  β”‚  └─ PipelineCoordinatorDO       β”‚           β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜           β”‚
β”‚           ↓↓↓                                    β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”           β”‚
β”‚  β”‚  D1 (PostgreSQL)                β”‚           β”‚
β”‚  β”‚  β”œβ”€ Spine (events)              β”‚           β”‚
β”‚  β”‚  β”œβ”€ agent_registry              β”‚           β”‚
β”‚  β”‚  β”œβ”€ communication_log           β”‚           β”‚
β”‚  β”‚  └─ tenant_state                β”‚           β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜           β”‚
β”‚           ↓↓↓                                    β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”           β”‚
β”‚  β”‚  KV Namespace                   β”‚           β”‚
β”‚  β”‚  β”œβ”€ agent_msg:*                 β”‚           β”‚
β”‚  β”‚  β”œβ”€ tool_registry:*             β”‚           β”‚
β”‚  β”‚  └─ cache:*                     β”‚           β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜           β”‚
β”‚           ↓↓↓                                    β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”           β”‚
β”‚  β”‚  Queues                         β”‚           β”‚
β”‚  β”‚  β”œβ”€ agent_tasks                 β”‚           β”‚
β”‚  β”‚  β”œβ”€ signals                     β”‚           β”‚
β”‚  β”‚  └─ proposals                   β”‚           β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜           β”‚
β”‚                                                 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ“Š Services Summary

ServicePurposeTech
twin-orchestratorAgent coordinationCF Worker
iw-agent-runtimeTwin Agent runtimeCF Worker + VO
mcp-connectorMCP protocolCF Worker
pipelineTask routingCF Worker
intelligenceSpecialized agentsCF Worker
continuityMemory persistenceCF Worker + VO
connectorIntegration connectorsCF Worker
gatewayAPI gatewayCF Worker
knowledgeKnowledge baseCF Worker
hermesEvent streamingCF Worker
capability-resolverAgent capability discoveryCF Worker
agent-registryAgent registrationCF Worker + D1

πŸŽ“ Learning Path

Level 1: Understanding Twin Architecture (1 hour)

  1. Read twin-agent.ts (system prompt + core loop)
  2. Review twin-orchestrator/index.ts (coordination logic)
  3. Understand TenantBrainDO (persistent state)

Level 2: Agent Communication (2 hours)

  1. Read packages/adk/ (agent capabilities)
  2. Study services/mcp-connector/ (MCP protocol)
  3. Understand inter-agent messaging

Level 3: Memory & Learning (2 hours)

  1. Review memory-pipeline.ts (decay algorithm)
  2. Study continuity/ (context assembly)
  3. Understand learned profile evolution

Level 4: Full System (4+ hours)

  1. Trace full data flow (user query β†’ Twin response)
  2. Study all 40 services
  3. Understand Cloudflare platform integration

πŸ”— Key Files to Review

FilePurposeLines
services/iw-agent-runtime/src/twin-agent.tsTwin Agent core600+
services/twin-orchestrator/src/index.tsOrchestration400+
services/iw-agent-runtime/src/tenant-brain-do.tsState management300+
packages/adk/src/registry.tsAgent registry200+
services/mcp-connector/src/mcp-server.tsMCP server300+
services/iw-agent-runtime/src/ecosystem/memory-pipeline.tsMemory system200+

✨ System Highlights

  1. 100% Cloudflare - No external infrastructure needed
  2. Persistent Twin - State machine per tenant
  3. Learned Profile - Twin evolves from interactions
  4. Multi-Agent Network - Specialized agents coordinate
  5. Governance Pipeline - All decisions tracked
  6. Complete Audit Trail - Spine records everything
  7. MCP Protocol - External integration via standard protocol
  8. Voice-Enabled - Cloudflare Workers AI integration

πŸš€ Next Steps

  1. Understand Twin - Read twin-agent.ts system prompt
  2. Study Orchestration - Review twin-orchestrator/ logic
  3. Learn Memory - Study decay + promotion algorithm
  4. Explore Agents - Review ADK and agent capabilities
  5. Map Services - Understand 40-service architecture
  6. Deploy - Use provided deployment scripts

Status: Full system mapped and documented.