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:
- Synthesizes context from Spine, Memory, and sessions
- Reasons about decisions and operational patterns
- Proposes structured recommendations with confidence scores
- Learns from outcomes and updates personal profile
- 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:
- Coordinate work across specialized agents
- Maintain persistent Twin state
- Manage learned profiles
- Route tasks to appropriate agents
- 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:
- Twin detects change
- Emits signal via
emitTriageInput - Signal goes through governance pipeline
- State updated in Durable Object
- 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 workflowsagent.reason- Synthesize decisionsagent.propose- Generate recommendationsagent.learn- Update from outcomesagent.coach- Explain decisions
Pipeline Service
Location: services/pipeline/src/
Routes work to specialized agents:
- Task submitted
- Registry queries for matching agent
- Agent executes
- Result captured in Spine
- Memory updated
- 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
| Service | Purpose | Tech |
|---|---|---|
| twin-orchestrator | Agent coordination | CF Worker |
| iw-agent-runtime | Twin Agent runtime | CF Worker + VO |
| mcp-connector | MCP protocol | CF Worker |
| pipeline | Task routing | CF Worker |
| intelligence | Specialized agents | CF Worker |
| continuity | Memory persistence | CF Worker + VO |
| connector | Integration connectors | CF Worker |
| gateway | API gateway | CF Worker |
| knowledge | Knowledge base | CF Worker |
| hermes | Event streaming | CF Worker |
| capability-resolver | Agent capability discovery | CF Worker |
| agent-registry | Agent registration | CF Worker + D1 |
π Learning Path
Level 1: Understanding Twin Architecture (1 hour)
- Read
twin-agent.ts(system prompt + core loop) - Review
twin-orchestrator/index.ts(coordination logic) - Understand
TenantBrainDO(persistent state)
Level 2: Agent Communication (2 hours)
- Read
packages/adk/(agent capabilities) - Study
services/mcp-connector/(MCP protocol) - Understand inter-agent messaging
Level 3: Memory & Learning (2 hours)
- Review
memory-pipeline.ts(decay algorithm) - Study
continuity/(context assembly) - Understand learned profile evolution
Level 4: Full System (4+ hours)
- Trace full data flow (user query β Twin response)
- Study all 40 services
- Understand Cloudflare platform integration
π Key Files to Review
| File | Purpose | Lines |
|---|---|---|
services/iw-agent-runtime/src/twin-agent.ts | Twin Agent core | 600+ |
services/twin-orchestrator/src/index.ts | Orchestration | 400+ |
services/iw-agent-runtime/src/tenant-brain-do.ts | State management | 300+ |
packages/adk/src/registry.ts | Agent registry | 200+ |
services/mcp-connector/src/mcp-server.ts | MCP server | 300+ |
services/iw-agent-runtime/src/ecosystem/memory-pipeline.ts | Memory system | 200+ |
β¨ System Highlights
- 100% Cloudflare - No external infrastructure needed
- Persistent Twin - State machine per tenant
- Learned Profile - Twin evolves from interactions
- Multi-Agent Network - Specialized agents coordinate
- Governance Pipeline - All decisions tracked
- Complete Audit Trail - Spine records everything
- MCP Protocol - External integration via standard protocol
- Voice-Enabled - Cloudflare Workers AI integration
π Next Steps
- Understand Twin - Read
twin-agent.tssystem prompt - Study Orchestration - Review
twin-orchestrator/logic - Learn Memory - Study decay + promotion algorithm
- Explore Agents - Review ADK and agent capabilities
- Map Services - Understand 40-service architecture
- Deploy - Use provided deployment scripts
Status: Full system mapped and documented.