{"slug":"internal/architecture/SYSTEM_ARCHITECTURE","title":"IntegrateWise System Architecture","section":"internal","sectionLabel":"Internal","status":"unclassified","type":"document","path":"internal/architecture/SYSTEM_ARCHITECTURE.mdx","bytes":27936,"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> ⚠️ **TIER C — HISTORICAL SNAPSHOT (Pre-DECISION 22)**\n> This document was written before DECISION 22 (June 12, 2026) locked the product plane\n> as **100% Cloudflare** (D1/KV/R2/Vectorize/AI Search/Durable Objects). It references\n> Supabase as the SSOT and \"Supabase Fortress\" — both retired by DECISION 22.\n> It also uses \"unified intelligence operating system\" which is superseded by DECISION 23\n> (product name = **IW Continuity Bridge**; \"knowledge workspace\" is the plain-language descriptor).\n>\n> **Do not trust this file as current architecture. For authoritative state, read:**\n> - `docs/CANON.md` — canonical doc index\n> - `AGENTS.md` (v3.8.0) — locked decisions 18–27\n> - `docs/architecture/PRODUCT_ARCHITECTURE.md` — product source of truth\n> - `CLAUDE.md` — code-derived guide\n\n\n**Status:** Production v3.8.0  \n**Last Updated:** June 25, 2026  \n**Authority:** Nirmal Prince J (Founder/CEO) + Engineering Team  \n\n---\n\n## I. EXECUTIVE OVERVIEW\n\nIntegrateWise is a **unified intelligence operating system** that connects fragmented enterprise tools into one coherent, governed, reasoning workspace. The system has three core layers:\n\n1. **User Facing (L1-L4):** Domain workbenches, cognitive overlays, twin reasoning, and memory management\n2. **Intelligence Engine (Backend):** 28 Cloudflare Workers orchestrating data ingestion, normalization, analysis, governance, and execution\n3. **Data Foundation (Spine):** Normalized canonical entities, relationships, signals, and organizational memory\n\n**Core Axiom:** One Spine. Many projections. The Spine is the source of truth; every surface is a view of it.\n\n---\n\n## II. MONOREPO STRUCTURE\n\n```\nintegratewise/\n├── apps/                          # User-facing applications\n│   ├── web/                       # Next.js 16 SPA (auth, workbenches, onboarding)\n│   ├── desktop/                   # Electron desktop app\n│   ├── mobile/                    # React Native mobile\n│   └── local-monitor/             # Local folder watcher\n│\n├── services/                      # Cloudflare Workers (28 total)\n│   ├── gateway/                   # Public ingress, routing, auth\n│   ├── connector/                 # External tool integrations\n│   ├── connector-sync/            # Scheduled syncs + webhooks\n│   ├── loader/                    # Universal intake membrane (MCP-native)\n│   ├── normalizer/                # 8-stage LLM-in-the-loop pipeline\n│   ├── pipeline/                  # Entity resolution + Spine writes\n│   ├── continuity/                # Memory consolidation + lifecycle\n│   ├── intelligence/              # Signal analysis + insights\n│   ├── think/                     # Synchronous reasoning service\n│   ├── iw-agent-runtime/          # Twin orchestration + LLM dispatch\n│   ├── knowledge/                 # Semantic search + embeddings\n│   ├── govern/                    # Approval gate + governance\n│   ├── admin/                     # Internal operations\n│   ├── billing/                   # Usage tracking + SaaS management\n│   ├── tenants/                   # Tenant provisioning + isolation\n│   ├── workflow/                  # Async execution orchestration\n│   └── [15+ other workers]        # Hermes, Telemetry, ACT, MCP, etc.\n│\n├── packages/                      # Shared libraries\n│   ├── types/                     # Canonical schemas + type definitions\n│   ├── db/                        # Database client abstractions\n│   ├── api/                       # HTTP client utilities\n│   ├── connector-contracts/       # Integration contracts\n│   ├── connector-utils/           # Shared connector logic\n│   ├── hermes-spine-memory/       # Memory operations library\n│   ├── rbac/                      # Role-based access control\n│   ├── tenancy/                   # Multi-tenant utilities\n│   ├── lib/                       # General utilities\n│   └── [8+ other packages]\n│\n├── docs/                          # Comprehensive documentation\n│   ├── architecture/              # Canonical design docs\n│   ├── tech/                      # Technical specifications\n│   ├── operations/                # Deployment + monitoring\n│   └── migrations/                # Database schemas\n│\n├── scripts/                       # Deployment + ops scripts\n├── configs/                       # Shared configuration\n├── migrations/                    # Database migrations\n└── pnpm-workspace.yaml            # Monorepo workspace config\n```\n\n**Package Manager:** pnpm v9.0.0  \n**Build Tool:** Turbo (2.0.0) — orchestrates 28 services + apps in parallel  \n**Node Overseer:** Next.js 16 app router for web frontend  \n\n---\n\n## III. THE THREE-SPINE ARCHITECTURE\n\nIntegrateWise implements a unique **three-spine lifecycle** where all signals (human decisions, AI reasoning, and joint approvals) flow through a unified state machine:\n\n### A. Human Spine (L1 - Ground Truth)\n\n**Purpose:** Record human goals, decisions, and outcomes as canonical ground truth.\n\n**Data Storage:** D1/Supabase SPINE table  \n**Lifecycle Flow:** INTAKE → PROMOTION → MEMORY → DECAY → CONTINUITY\n\n**Example:** User creates quarterly revenue goal → validated → stored in MEMORY phase → triggers continuity compounding\n\n**Key Entities:**\n- Goals\n- Outcomes  \n- Decisions\n- Approvals\n\n---\n\n### B. AI Spine (L3 - Intelligence Layer)\n\n**Purpose:** Generate reasoning traces, proposals, and signals with confidence scores.\n\n**Data Storage:** D1/Supabase AI_SPINE table  \n**Lifecycle Flow:** Same as Human Spine (INTAKE through CONTINUITY)\n\n**Example:** Twin analyzes customer churn signal → generates proposal → reasoning trace stored → confidence scored\n\n**Key Entities:**\n- REASONING_TRACE: Chain-of-thought + evidence\n- PROPOSAL: Recommended actions with success criteria\n- SIGNAL: Pattern detection + anomalies\n- CONFIDENCE: Probability/reliability metrics\n\n---\n\n### C. Collaboration Spine (L2 - Joint Decision Making)\n\n**Purpose:** Record approvals, feedback, and compounded outcomes from human-AI collaboration.\n\n**Data Storage:** D1/Supabase COLLABORATION_SPINE table  \n**Lifecycle Flow:** Same as Human Spine (INTAKE through CONTINUITY)\n\n**Example:** Human approves AI proposal → joint outcome recorded → memory compounds for next cycle\n\n**Key Entities:**\n- APPROVAL: Human approval decisions\n- FEEDBACK: Human course corrections\n- COMPOUND_OUTCOME: Joint decision + outcome\n- COLLABORATION_TRACE: Interaction history\n\n---\n\n### D. Unified Lifecycle (All Three Spines)\n\n```\nINTAKE\n  ↓ (Signal enters the system)\nPROMOTION\n  ↓ (Validates, resolves, ready to act)\nMEMORY\n  ↓ (Stored as ground truth)\nDECAY\n  ↓ (Aged signals archived)\nCONTINUITY\n  ↓ (Outcome stored in continuity graph for future learning)\n```\n\n**Every signal** (human, AI, or collaborative) flows through these five phases. The system guarantees:\n- No action without approval (governance gate)\n- Full audit trail (all phases logged)\n- Learning loop (outcomes feed back into system memory)\n- Tenant isolation (all operations scoped to `tenant_id`)\n\n---\n\n## IV. BACKEND SERVICES ARCHITECTURE (28 Workers)\n\n### 4.1 Data Ingestion Pipeline (S1-S4)\n\n#### LOADER (`services/loader/`)\n- **Purpose:** Universal intake membrane for all connected tools\n- **Protocol:** MCP-native (Model Context Protocol)\n- **Responsibility:**\n  - Receives webhooks from HubSpot, Salesforce, Slack, etc.\n  - Enqueues raw events **without transformation**\n  - Tracks provenance (source system, timestamp, version)\n  - Routes to normalizer queue\n- **Database:** D1 `loader_events` table\n- **Key Invariant:** Never reasons. Just intake + provenance.\n\n#### CONNECTOR (`services/connector/`) + CONNECTOR-SYNC (`services/connector-sync/`)\n- **Purpose:** Tool integration and scheduled polling\n- **Responsibility:**\n  - OAuth/API auth to external systems\n  - Webhook receiver for push-based integrations\n  - Scheduled polling for pull-based integrations\n  - Rate limiting + retry logic\n- **Supported Tools:** HubSpot, Salesforce, Slack, Gmail, Jira, Linear, Notion, Zendesk, Stripe, etc.\n- **Output:** Enqueued raw events to NORMALIZER\n\n#### NORMALIZER (`services/normalizer/`)\n- **Purpose:** 8-stage LLM-in-the-loop cognitive pipeline\n- **Stages:**\n  1. **Intake:** Deserialize raw event\n  2. **Classification:** Identify entity type (Contact, Account, Opportunity, etc.)\n  3. **Entity Resolution:** LLM stage — match to canonical ID\n  4. **Field Mapping:** LLM stage — map tool fields to canonical schema\n  5. **Validation:** Check schema compliance\n  6. **Enrichment:** LLM stage — detect missing fields, suggest defaults\n  7. **Deduplication:** Check if entity already exists\n  8. **Emission:** Output as MCP tool call (not JSON)\n- **Cost Model:** LLM inference paid **once per entity**, not per tool instance\n- **Database:** D1 `normalized_events` table\n- **Output:** Enqueued normalized MCP calls to PIPELINE\n\n#### PIPELINE (`services/pipeline/`)\n- **Purpose:** Entity resolution, Spine writes, relationship building\n- **Responsibility:**\n  - Consumes normalized MCP calls\n  - Resolves entity to canonical ID (creates new if needed)\n  - Writes to D1 domain partitions (`person_data`, `account_data`, etc.)\n  - Builds relationship graph\n  - Triggers signal analysis\n  - Enqueues to CONTINUITY for memory consolidation\n- **Database:** D1 (domain partitions) + Supabase Fortress (SSOT)\n- **Key Invariant:** All Spine writes proxied through pipeline. Downstream workers cannot write directly.\n\n---\n\n### 4.2 Intelligence & Reasoning (S5-S8)\n\n#### INTELLIGENCE (`services/intelligence/`)\n- **Purpose:** Signal analysis, anomaly detection, insights\n- **Responsibility:**\n  - Analyzes entity changes\n  - Detects anomalies (churn risk, opportunity patterns, etc.)\n  - Generates signals with confidence scores\n  - Enriches with historical context\n  - Emits to L2 Cognitive Overlay\n- **Storage:** D1 `signal_cache` + AI Search (vector embeddings)\n- **Output:** Signals → Cognitive Overlay, Triage Inbox\n\n#### THINK (`services/think/`)\n- **Purpose:** Synchronous reasoning endpoint for L2/L3 surfaces\n- **Responsibility:**\n  - Receives reasoning requests from Twin or Cognitive Overlay\n  - Calls LLM with assembled context (Entity 360, signals, memory)\n  - Returns chain-of-thought + confidence\n  - No execution authority\n- **Database:** Reads from Spine, no writes\n- **Output:** Reasoning trace → Twin interface\n\n#### IW-AGENT-RUNTIME (`services/iw-agent-runtime/`)\n- **Purpose:** Twin orchestration and LLM dispatch\n- **Responsibility:**\n  - Manages conversational state\n  - Assembles context from Spine for each turn\n  - Calls LLM (Claude, GPT, etc. via CF AI Gateway)\n  - Generates structured proposals\n  - No execution authority; pushes proposals to GOVERN\n- **Database:** D1 `twin_sessions`, `ai_conversations`\n- **Output:** Proposals → Governance queue\n\n#### CONTINUITY (`services/continuity/`)\n- **Purpose:** Memory consolidation and lifecycle management\n- **Responsibility:**\n  - Implements 5-phase lifecycle (INTAKE → PROMOTION → MEMORY → DECAY → CONTINUITY)\n  - Triages signals (TriageBot MCP decision)\n  - Promotes signals to active memory\n  - Ages out stale signals\n  - Compounds outcomes (human + AI collaborations)\n  - Maintains org_memory, personal_memory, conversational_memory\n- **Storage:** D1 `continuity_graph` + Supabase memory tables\n- **Output:** Compounded outcomes → Intelligence, Twin context\n\n---\n\n### 4.3 Governance & Execution (S9-S10)\n\n#### GOVERN (`services/govern/`)\n- **Purpose:** Approval gate and governance\n- **Responsibility:**\n  - Receives proposals from Twin, Think, Workflow\n  - Routes to approver (human or policy-based)\n  - Logs approval decision\n  - Marks proposal as `APPROVED` or `REJECTED`\n  - **Never executes** — hands off to Workflow\n- **Database:** D1 `governance_queue`, `approval_logs`\n- **Output:** Approved proposals → Workflow executor\n\n#### WORKFLOW (`services/workflow/`)\n- **Purpose:** Async execution orchestration\n- **Responsibility:**\n  - Receives approved proposals from GOVERN\n  - Resolves execution target (Slack, HubSpot, Gmail, etc.)\n  - Prepares handoff (canonical JSON contract)\n  - Stages in execution queue\n  - Tracks execution state\n  - Receives execution feedback (via signals)\n- **Database:** D1 `execution_queue`, `execution_state`\n- **Output:** Handoff contracts → client execution or adapter dispatch\n\n---\n\n### 4.4 Memory & Knowledge (S11-S12 equivalent)\n\n#### KNOWLEDGE (`services/knowledge/`)\n- **Purpose:** Semantic search and retrieval augmented generation\n- **Responsibility:**\n  - Maintains vector embeddings of Spine entities\n  - Powers full-text + semantic search\n  - Retrieves context for Twin + Think\n  - Ingests documents, conversation history\n- **Storage:** CF AI Search (vector DB)\n- **Output:** Search results → Twin context, L2 Cognitive Overlay\n\n#### HERMES (via `packages/hermes-spine-memory/`)\n- **Purpose:** Memory operations and recall\n- **Responsibility:**\n  - Exposes org_memory, personal_memory APIs\n  - Manages memory lifecycle\n  - Handles memory eviction + decay\n  - Integrates with Continuity\n- **Storage:** D1 memory tables + Supabase\n- **Output:** Memory objects → Twin, Intelligence, Think\n\n---\n\n### 4.5 Access & Gateway (S0 - Ingress)\n\n#### GATEWAY (`services/gateway/`)\n- **Purpose:** Single public ingress, auth, routing\n- **Responsibility:**\n  - SSL/TLS termination\n  - Request authentication (Supabase auth)\n  - Route authorization (RBAC from `@integratewise/rbac`)\n  - Request routing to downstream workers\n  - Rate limiting + DDoS protection\n  - Logging + telemetry\n- **Storage:** Reads RBAC tables\n- **Key Invariant:** All traffic enters via Gateway. No worker is exposed to the public internet.\n\n#### TENANTS (`services/tenants/`)\n- **Purpose:** Tenant provisioning and isolation\n- **Responsibility:**\n  - Provisions new tenant (workspace)\n  - Initializes D1 partitions, Supabase schemas\n  - Sets up initial RBAC rules\n  - Manages domain assignments\n  - Enforces row-level security (RLS)\n- **Database:** D1 `tenants` table + Supabase `tenant_isolation` policies\n- **Output:** Tenant configs → all workers\n\n#### ADMIN (`services/admin/`)\n- **Purpose:** Internal operations interface\n- **Responsibility:**\n  - Tenant management\n  - User management\n  - Config overrides\n  - Manual signal injection (for testing)\n  - Emergency governance bypasses (audit-logged)\n- **Access:** Internal only, never exposed\n- **Output:** Admin commands → pipeline/governance\n\n---\n\n### 4.6 Integrations & Adapters\n\n#### MCP-CONNECTOR (`services/mcp-connector/`)\n- **Purpose:** Model Context Protocol for external AI tools\n- **Responsibility:**\n  - Exposes Spine as MCP tools (read-only for ChatGPT, Claude, etc.)\n  - Allows external AIs to query Spine\n  - Tracks external AI actions (audit trail)\n  - Returns paginated, tenant-filtered results\n- **Output:** MCP tools → ChatGPT, Claude, Perplexity, OpenRouter\n\n#### WEBHOOK-INGRESS (`services/webhook-ingress/`)\n- **Purpose:** Secure webhook receivers for all connectors\n- **Responsibility:**\n  - HMAC verification of webhook signatures\n  - Enqueues events to Loader\n  - Retry logic with exponential backoff\n  - Webhook delivery status tracking\n- **Database:** D1 `webhook_deliveries`\n\n---\n\n### 4.7 Operations & Support\n\n#### BILLING (`services/billing/`)\n- **Purpose:** Usage tracking and SaaS management\n- **Responsibility:**\n  - Tracks API calls, workers invoked, storage used\n  - Computes monthly usage + billing\n  - Manages subscription plans\n  - Enforces usage limits\n- **Database:** Supabase `usage_logs`, `subscriptions`\n\n#### TELEMETRY (`services/telemetry/`)\n- **Purpose:** Observability and monitoring\n- **Responsibility:**\n  - Collects performance metrics\n  - Logs errors to Sentry\n  - Tracks service health\n  - Emits to monitoring dashboard\n- **Output:** Grafana dashboards, Sentry alerts\n\n#### FOLDER-WATCHER (`services/folder-watcher/`)\n- **Purpose:** Local filesystem monitoring\n- **Responsibility:**\n  - Monitors local folders for new files\n  - Sends file metadata to Loader\n  - Triggers document indexing\n- **Integration:** `apps/local-monitor` (Node.js app)\n\n---\n\n## V. FRONTEND ARCHITECTURE (Next.js 16)\n\n### 5.1 Application Structure\n\n```\napps/web/\n├── app/                           # Next.js App Router\n│   ├── layout.tsx                 # Root layout + providers\n│   ├── page.tsx                   # Home/login\n│   ├── onboarding/                # Onboarding flow\n│   ├── workspace/                 # Main authenticated workspace\n│   │   ├── layout.tsx             # Workspace shell\n│   │   ├── [domain]/              # Domain-scoped workbench\n│   │   ├── settings/              # User settings\n│   │   └── memory/                # Memory + search\n│   ├── twin/                      # Twin chat interface\n│   ├── api/                       # API routes\n│   │   ├── auth/                  # Authentication\n│   │   ├── spine/                 # Spine queries\n│   │   └── sync/                  # Data sync\n│   └── public-demo/               # Public demo (no auth)\n│\n├── components/                    # React components\n│   ├── workbench/                 # Domain-specific workbenches\n│   ├── twin/                      # Twin reasoning UI\n│   ├── cognitive-overlay/         # L2 signals + insights\n│   ├── domain-sidebar/            # Layer switcher (L1-L4)\n│   ├── entities/                  # Entity 360 views\n│   ├── approval/                  # Approval center\n│   └── ui/                        # shadcn/ui components\n│\n├── lib/\n│   ├── spine/                     # Spine API client\n│   ├── supabase/                  # Supabase client + auth\n│   ├── twin/                      # Twin client\n│   ├── types/                     # Frontend types\n│   └── hooks/                     # Custom React hooks\n│\n├── middleware.ts                  # Supabase auth middleware\n├── vercel.json                    # Vercel config (Next.js)\n└── package.json\n```\n\n### 5.2 Layer Switcher (Sidebar Navigation)\n\nThe **Layer Switcher** is the core navigation metaphor. Four buttons in the sidebar allow users to switch between spines:\n\n1. **Human (Blue)** - L1: Personal goals and decisions\n2. **AI (Purple)** - L3: Twin reasoning and proposals\n3. **Collaborate (Amber)** - L2: Joint approvals and memory\n4. **Approve (Green)** - L4: Governance and audit\n\n**All four layers exist in the same app.** Switching between them changes the data projection without a page reload.\n\n### 5.3 Domain Sidebar\n\nWorkbenches are scoped by **domain** (Customer Success, Sales, Marketing, etc.). The domain sidebar includes:\n\n- Active domain indicator\n- Domain switcher (if user has multiple domains)\n- Spine layer selector (Human/AI/Collaborate/Approve)\n- Quick actions (create goal, search, settings)\n- Integration status\n\n### 5.4 Key Surfaces\n\n| Surface | Purpose | Data Source | Interaction |\n|---------|---------|-------------|-------------|\n| **L1 Workbench** | Primary operational interface | Spine (domain partition) | Read/create goals, view entities |\n| **L2 Cognitive Overlay** | Intelligence layer (`⌘J`) | Intelligence service signals | Read-only, promote to proposal |\n| **L3 Twin Chat** | Reasoning and planning | IW-Agent-Runtime | Chat, ask Twin, get proposals |\n| **L4 Memory** | Search + documents | Knowledge service + Hermes | Full-text + semantic search |\n| **Approval Center** | Governance | GOVERN service queue | Review, approve, reject proposals |\n| **Public Demo** | Non-authenticated demo | Hard-coded sample data | Read-only visualization |\n\n---\n\n## VI. DATA LAYER ARCHITECTURE\n\n### 6.1 Dual Storage Strategy\n\n**D1 (Edge, Hot):**\n- Domain partitions (`person_data`, `account_data`, `opportunity_data`, etc.)\n- Signal cache\n- Twin sessions\n- Execution queue\n- Continuity graph\n\n**Supabase Fortress (SSOT, Authoritative):**\n- Source of truth for all entities\n- Audit logs\n- Memory tables (org_memory, personal_memory)\n- Billing + usage logs\n- Row-level security (RLS) for multi-tenancy\n\n### 6.2 Spine Entity Model\n\n**Canonical Entity Types:** 18 core types resolved from any tool\n\n```\nPERSON, ACCOUNT, OPPORTUNITY, TICKET, ACTIVITY,\nMESSAGE, DOCUMENT, GOAL, WORKFLOW, SIGNAL,\nDECISION, APPROVAL, EXECUTION, OUTCOME,\nORGANIZATION, TEAM, RESOURCE, CUSTOM\n```\n\n**Canonical Traits:** 18 core attributes common across all entities\n\n```\nexternal_id, name, email, phone, status, owner_id,\ncreated_at, updated_at, source_system, confidence,\ntags, custom_fields, relationships, signals\n```\n\n**Domain Partitions:** 12 logical domains, each with entity-specific tables\n\n```\nCUSTOMER_SUCCESS: person, account, ticket, health_score\nSALES: opportunity, activity, deal_stage, forecast\nMARKETING: campaign, contact, engagement, lead_score\nREVOPS: forecast, quota, territory, pipeline\nFINANCE: invoice, expense, budget, forecast\n[8+ more]\n```\n\n### 6.3 Relationships & Entity 360\n\n**Relationship Graph:**\n- Stores: `person` ← works-for → `account`, `person` ← owns → `opportunity`, etc.\n- Assembled on read from Spine (no materialized `relationships` table; expensive reads are cached in KV)\n- Enables Entity 360: Single view of a person across all connected systems\n\n---\n\n## VII. DEPLOYMENT & OPERATIONS\n\n### 7.1 Environments\n\n```\ndev  → localhost (pnpm dev)\ntest → staging.integratewise.ai (pre-production)\nprod → app.integratewise.ai (live)\n```\n\n### 7.2 Deployment Targets\n\n**Cloudflare Workers:**\n- Deploy with `pnpm deploy:prod` (all 28 workers)\n- Staging: `pnpm deploy:test`\n- Each worker has own `wrangler.toml`\n\n**Next.js Frontend:**\n- Deployed to Vercel (automatic on Git push to main)\n- Environment variables via Vercel dashboard\n- Staging branch → staging-web.integratewise.ai\n\n**Database:**\n- D1: Cloudflare-managed SQLite (auto-replicated)\n- Supabase: Direct SQL + managed auth\n\n### 7.3 Monitoring & Alerts\n\n**Observability Stack:**\n- Sentry (error tracking)\n- Grafana (metrics)\n- Cloudflare Analytics\n- Custom telemetry service\n\n**Key Metrics:**\n- P95 latency per worker\n- Error rate (5xx, 4xx)\n- Database query time\n- Memory usage (continuity lifecycle)\n- Approval SLA (target: <1min human review time)\n\n---\n\n## VIII. SECURITY MODEL\n\n### 8.1 Authentication & Authorization\n\n**Auth Layer:** Supabase Auth (email + password, OAuth via Google/GitHub)  \n**Session Management:** JWT tokens stored in secure httpOnly cookies  \n**RBAC:** Role-based access control per tenant + domain  \n**MFA:** Optional per organization (SSO for enterprise)\n\n### 8.2 Data Isolation\n\n**Row-Level Security (RLS):** Supabase enforces `tenant_id` filtering at DB layer  \n**Worker Bindings:** Zero-trust internal routing; no worker exposed to public  \n**Encryption:** TLS in transit, at-rest encryption for sensitive data (vault)  \n**Audit Trail:** Every action logged (actor, timestamp, approval status, outcome)\n\n### 8.3 Third-Party Integration Security\n\n**OAuth Tokens:** Stored encrypted in Supabase, never transmitted to client  \n**Webhook HMAC:** All webhooks verified with provider signatures  \n**Rate Limiting:** Per-tenant + per-tool rate limits enforced at Gateway  \n**Secrets Management:** Doppler for env vars, Cloudflare Workers Secrets for service credentials\n\n---\n\n## IX. OBSERVABILITY & LOGGING\n\n### 9.1 Logging Strategy\n\n**No local logging.** 100% cloud audit trail:\n\n- **Direct writes:** Workers write to D1 + Supabase\n- **Queue-mediated:** Normalizer, Pipeline, Continuity enqueue → process → commit\n- **Audit logs:** `audit_logs` table (actor, action, timestamp, result)\n- **Governance logs:** `governance_audit_log` (approval chain)\n- **Spine logs:** `spine_audit_log` (entity writes)\n\n### 9.2 Observability Points\n\n| System | Metrics | Logs | Traces |\n|--------|---------|------|--------|\n| **Gateway** | Requests/sec, error rate, latency P95 | Auth failures, rate limits | Request → downstream |\n| **Normalizer** | Events processed, LLM cost, errors | Classification, mapping errors | Entity resolution |\n| **Pipeline** | Entities written, relationships added | Duplicates, conflicts | Spine write path |\n| **Continuity** | Signals triaged, promoted, decayed | Lifecycle transitions | Memory consolidation |\n| **Twin** | Conversations, proposals generated | Reasoning traces | Chat turns |\n| **Govern** | Approvals/rejections, SLA | Governance decisions | Approval path |\n\n---\n\n## X. SCALABILITY & PERFORMANCE\n\n### 10.1 Architecture for Scale\n\n**Cloudflare Workers:** Auto-scales horizontally, no cold starts  \n**D1 Database:** SQLite with auto-replication, sub-10ms reads  \n**AI Search:** Vector embeddings in Cloudflare, <50ms semantic search  \n**Queue Pattern:** Durable Objects for singleton work (one continuity processor per tenant)  \n**Caching:** KV for entity 360 (5min TTL), signal cache (1min TTL)\n\n### 10.2 Bottlenecks & Mitigations\n\n| Bottleneck | Current | Mitigation |\n|-----------|---------|-----------|\n| LLM inference cost | Paid once per entity (normalizer) | Batch inference, cache schema |\n| Continuity processing | Single Durable Object per tenant | Sharded processor for large orgs |\n| Entity 360 assembly | Materialized in KV | Read-through cache with TTL |\n| Vector search latency | Sub-50ms | Index pruning per tenant |\n\n---\n\n## XI. DEPLOYMENT CHECKLIST\n\n### Pre-Launch\n\n- [ ] Verify Supabase Fortress is provisioned (RLS policies active)\n- [ ] Verify D1 schemas applied (all 12 domain partitions)\n- [ ] Verify Cloudflare API tokens set in Doppler\n- [ ] Verify service bindings (gateway → pipeline → continuity, etc.)\n- [ ] Run preflight: `pnpm preflight` (install, typecheck, lint, test, build)\n\n### Launch\n\n- [ ] Deploy Cloudflare Workers: `pnpm deploy:prod`\n- [ ] Deploy Next.js frontend: Git push to main (Vercel auto-deploys)\n- [ ] Verify health endpoints: `curl https://gateway.integratewise.ai/health`\n- [ ] Run smoke tests: `scripts/e2e-check.sh`\n\n### Post-Launch\n\n- [ ] Monitor error rates in Sentry\n- [ ] Monitor latency in Grafana\n- [ ] Monitor billing in Cloudflare dashboard\n- [ ] Customer Zero test run (internal user)\n\n---\n\n## XII. KEY INVARIANTS & PRINCIPLES\n\n1. **One Spine, Many Projections:** All UI surfaces are views of the same Spine. No duplication.\n2. **Never Reason at Intake:** Loader never transforms data. Transformation paid once per entity.\n3. **No Execution Without Approval:** Every action is governance-gated.\n4. **Tenant Isolation:** Every query includes `tenant_id` scoping.\n5. **Audit Everything:** All actions logged with actor, timestamp, reasoning, outcome.\n6. **Cloud-First Memory:** No local agent state. All memory in cloud (D1/Supabase).\n7. **Zero-Trust Routing:** Workers never exposed publicly. All traffic via Gateway.\n8. **Continuous Learning:** Outcomes feed back into system memory for future signal generation.\n\n---\n\n## XIII. CONTACT & GOVERNANCE\n\n**Founder/CEO:** Nirmal Prince J  \n**Engineering Lead:** [To be assigned]  \n**Architecture Authority:** Nirmal + Engineering Team  \n**Last Review:** June 25, 2026  \n\n**For questions about architecture decisions, see:**\n- `AGENTS.md` (locked decisions)\n- `docs/architecture/PRODUCT_ARCHITECTURE.md` (product design)\n- `docs/architecture/SPINE_MODEL.md` (data model)\n- `docs/architecture/USER_SYSTEM_JOURNEY_BLUEPRINT.md` (layers & stages)\n"}