{"slug":"internal/business/INTEGRATEWISE_PRODUCT_ARCHITECTURE","title":"IntegrateWise — Product Architecture & Requirements","section":"internal","sectionLabel":"Internal","status":"unclassified","type":"document","path":"internal/business/INTEGRATEWISE_PRODUCT_ARCHITECTURE.mdx","bytes":67747,"description":null,"updated":null,"source":"integratewise/Integratewise-docs-wiki","content":"\n> **Date:** June 4, 2026 | **Authority:** Nirmal (Founder) | **Version:** FINAL\n> **This is one document. It is complete. It contains everything.**\n\n---\n\n---\n\n# SECTION A — SYSTEMS ARCHITECTURE\n\n---\n\n## A1. What IntegrateWise Is\n\nA governed operational continuity and intelligence layer for organizations.\nIt solves tool fragmentation (M×N integration) and vanishing reasoning (AI sessions that evaporate).\n\n**Architectural thesis:** Normalize everything. Hold one truth. Let the LLM reason over that truth.\n\nIntegrateWise owns memory. The user owns execution. MCP connects the two.\n\n---\n\n## A2. The System Components\n\n```\nCOMPONENT       WHAT IT IS                              WHAT IT IS NOT\n────────────────────────────────────────────────────────────────────────────\nTWIN            The only agent. Model-agnostic.         Not Hermes. Not Claw.\n                Persistent. 6-layer memory.             Not a multi-agent swarm.\n                Runs on any LLM (parameter,             Not locked to any model.\n                not dependency).\n\nSPINE           Canonical operational truth.            Not memory. Not reasoning.\n                Supabase (fortress).                    Not accessed by agents directly.\n                Mirrored to D1 (edge, read-only).\n\nMCP             The protocol. Internal bus +            Not just external access.\n                external access. Unified.               Not a connector wrapper.\n                Gateway + MCP combined.\n\nADK             Registry + cache.                       Not an orchestrator.\n                What agents/tools exist.                Not stateful. No memory.\n                \"This call → this service.\"             No logs. No reasoning.\n                KV-speed TTL lookup.\n\nCF WORKFLOWS    Durable multi-step execution.           Not n8n. Not external.\n                step.do(). step.sleep().                Not a separate system.\n                waitForEvent(). Retry + backoff.\n\nPIPELINE        8-stage Normalizer.                     Not readable by users.\n                SOLE Supabase credential holder.        Not bypassed for writes.\n                Writes Spine. Nothing else does.\n\nTRIAGE BOT     CF Workflow. Scores proposals.           Not a Spine writer.\n                Sole writer to org_memory.              Not an executor.\n                Routes: approve / HITL / reject.\n\nACT SERVICE     Executes approved actions.              Not a proposer.\n                Calls target tools. Reports result.     Not a reasoner.\n                Feeds back to Pipeline.\n\nNANGO           OAuth token management.                 Not business logic.\n                200+ providers. Auto-refresh.           Not accessed by Twin directly.\n                Connection UI for users.\n```\n\n---\n\n## A3. What Does NOT Exist\n\n```\n✗ Hermes           (removed — Twin replaces)\n✗ Claw             (removed — CF Workflows replaces)\n✗ n8n              (removed — CF native replaces)\n✗ Python           (zero, anywhere, no exceptions)\n✗ CouchDB          (removed — Supabase only)\n✗ Neon Postgres    (removed — D1 + Supabase)\n✗ Multi-agent swarm(one Twin only)\n✗ Direct Supabase access by agents (pipeline db-proxy only)\n✗ Insights floating in UI (Entity 360 only)\n✗ Memory in ADK    (ADK is stateless registry + cache)\n```\n\n---\n\n## A4. Storage Architecture\n\n### The CF Edge Stack (Complete — Runs Full Product Without Supabase)\n\n```\nPRIMITIVE    TECHNOLOGY           PURPOSE                         ROLE\n──────────────────────────────────────────────────────────────────────────────\nD1           CF SQLite (edge)     Structured data at edge         Spine entities, signals,\n                                                                  tenant/user records, metadata,\n                                                                  memory governance metadata.\n\nR2           CF Object Storage    Raw content (cold)              Documents, memory content,\n                                                                  file uploads. Source of truth\n                                                                  for all raw content.\n\nVectorize    CF AI Search         Embeddings + semantic index     THE ONLY memory retrieval\n                                                                  path for agents/Twin.\n\nKV           CF KV                Hot cache (60-300s TTL)         Session state, connector status,\n                                                                  ADK routing, subscription tier,\n                                                                  entity cache.\n\nQueues       CF Queues            Async processing                pipeline-process, sync,\n                                                                  intelligence-events, knowledge.\n\nDOs          Durable Objects      Stateful long-lived sessions    HITL gate, folder watcher,\n                                                                  stream gateway.\n```\n\n### Two Operational Modes\n\n```\nINITIAL USERS (Full CF Edge Stack — no Supabase):\n  Spine:       D1 (entities, relationships, signals)\n  Memory:      R2 (content) + Vectorize (retrieval) + D1 (metadata)\n  Auth:        D1 (tenant/user records) + KV (session cache)\n  Sync:        Queues + KV (status tracking)\n  Files:       R2 (uploads, documents)\n  State:       DOs (HITL, sessions)\n\n  This IS the full product. Nothing missing.\n  No external database. All Cloudflare-native.\n\nPROMOTED USERS (CF Edge Stack + Supabase fortress):\n  Same edge stack for speed (D1 + KV + R2 + Vectorize + Queues + DOs)\n  PLUS: Supabase as canonical backup + durability layer\n  Pipeline writes to BOTH: D1 (edge) + Supabase (fortress)\n  If D1 is lost: rebuild from Supabase. Nothing lost.\n  Promotion: manual decision by Nirmal after reviewing usage patterns.\n```\n\n### Access Rules\n\n```\nLAYER       WHO READS                    WHO WRITES\n──────────────────────────────────────────────────────────────────────────────\nD1          Twin (Spine data)            Pipeline only (Spine writes)\n            Human (browse metadata)      Tenants service (user/tenant records)\n            Gateway (tenant resolution)  Triage Bot (memory metadata)\n\nR2          Never directly by Twin       Triage Bot (approved memory content)\n            Knowledge service (embed)    Knowledge service (document uploads)\n\nVectorize   Twin (memory retrieval)      Triage Bot (after R2 write, indexes)\n            ONLY retrieval path for      Knowledge service (embeddings)\n            agent memory access\n\nKV          Gateway (session, tier)      Any service (ephemeral cache)\n            ADK (routing lookup)         Auto-expires (TTL-based)\n            Connector-sync (status)\n\nQueues      Consumer workers             Producer workers (any service)\n\nDOs         HITL consumers               HITL producers\n            Stream clients               Webhook processors\n```\n\n---\n\n## A5. Memory Architecture\n\n### Two Distinct Paths\n\n```\nPATH 1 — RETRIEVAL (how Twin reads memory)\n  Vectorize (AI Search) ONLY.\n  Twin → semantic query → top K relevant entries → insight generation.\n  NOT from D1. NOT from Supabase. AI Search is the ONLY retrieval path for agents.\n\nPATH 2 — GOVERNANCE + BROWSE (how humans manage memory)\n  Supabase org_memory → governance_state, category, entity_refs, lineage_id\n  D1 metadata mirror → human browse UI (/memory route)\n  This path is for HUMANS, not the Twin.\n```\n\n### Write Path (Governed)\n\n```\nSource (file change / Twin proposal / document upload)\n  → Worker detects change (SHA-256 hash)\n  → Triage Bot scores (confidence + relevance + risk + conflict + quality)\n    ≥ 0.85 → auto-approve\n    0.60–0.84 → HITL (human review)\n    < 0.60 → reject\n  → R2 (raw content stored)\n  → Vectorize (chunks embedded, indexed)\n  → Supabase org_memory metadata (via pipeline db-proxy)\n  → D1 metadata mirror\n  All written on every approved entry. Atomic.\n```\n\n### Memory Types\n\n```\nPERSONAL MEMORY    Private to user. Behavioral patterns, preferences.\n                   Auto-promoted from conversational after 5+ sessions.\n                   Hard RLS boundary — no cross-user access.\n\nCONVERSATIONAL     Session logs. Auto-written every Twin session.\n                   Scratchpad. No governance needed.\n                   Promotion candidates surface from here.\n\nORG MEMORY         Institutional knowledge. 8 categories:\n                   doctrine | decision | workflow | policy |\n                   insight | pattern | commitment | learning\n                   ONLY written by Triage Bot. Nothing else. Ever.\n                   Governed. Versioned. Append-only. Never deleted.\n```\n\n---\n\n## A6. Spine Architecture\n\n```\nSPINE IS OPERATIONAL TRUTH.\n  What is the health score of Acme right now? → Spine (D1).\n  What deals are closing this month? → Spine (D1).\n  What tasks are overdue? → Spine (D1).\n\nSPINE IS NOT MEMORY.\n  What did we learn from the Acme escalation? → Memory (Vectorize).\n  What patterns have we seen? → Memory (Vectorize).\n\nWRITE PATH:\n  Source tool → Nango token → Connector → SPINE SCHEMA HYDRATION\n  → Loader (8 stages) → Normalizer (8 stages) → Pipeline writes to D1.\n  For promoted users: Pipeline also writes to Supabase (dual-write).\n  NOTHING ELSE WRITES TO SPINE. Pipeline is the sole writer.\n\nREAD PATH (for Twin):\n  D1 only. Structured. Exact. Fast. Sub-10ms.\n  Twin NEVER reads from Supabase. D1 IS the Spine for agents.\n\nSCHEMA:\n  12 domains × 11 industry overlays = adaptive.\n  Spine Selector at onboarding determines which schema activates.\n  tenant_spine_config (D1) controls everything downstream.\n```\n\n---\n\n## A7. Security & Auth\n\n```\nCF Zero Trust:\n  4 public domains: gateway, ingress, pipeline, watcher\n  All downstream workers: service bindings only, zero internet exposure\n  MCP external: CF-Access-Client-Id + CF-Access-Client-Secret + x-tenant-id\n  Gateway validates Service Token ↔ tenant mapping (cross-tenant impersonation blocked)\n\nAuth (unified — Cloudflare; supersedes the two-stage Supabase model):\n  ALL USERS:\n    Identity: Cloudflare Access SSO (Google + GitHub). No password.\n    Session:  Gateway validates CF Access JWT, resolves tenant from D1,\n              issues/propagates Gateway JWT (RS256).\n    Injects:  x-tenant-id, x-user-id, x-user-role\n    Zero Supabase auth. (Supabase is the fortress DATA record only — never auth.)\n\n  DATA TIER (separate concern from auth — usage-gated, NOT chosen at signup):\n    Initial users:  D1-edge ONLY. No Supabase. Every user starts here.\n    Allocation:     Supabase fortress is ALLOTTED based on usage (data volume /\n                    durability need / tier), never provisioned at signup.\n    Promoted users: + Supabase fortress backup (DATA durability + RLS) once allotted.\n    Auth is IDENTICAL across both tiers — downstream workers don't know the difference.\n\n  Internal workers: trust cf-worker header via service bindings\n```\n\n---\n\n## A8. The Complete Operational Loop\n\n```\nENTITY 360 ASSEMBLED\n  D1 (Spine — operational truth)\n  + Vectorize (Memory — AI Search, semantic)\n  + D1 (Signals — recent, time-ordered)\n         │\n    TWIN REASONS\n    Generates insight. Proposes action.\n         │\n    ┌────┴────┐\n  PATH A    PATH B\n  Auto-     Human approves\n  execute   or updates directly\n    │         │\n    └────┬────┘\n         │\n  OPS EXECUTED\n  Act service → target tool (HubSpot, Jira, Salesforce, calendar)\n         │\n  SPINE UPDATED\n  Tool webhook → ingress → Normalizer → D1 + Supabase\n         │\n  MEMORY UPDATED (if learning generated)\n  Triage Bot → R2 → Vectorize → Supabase metadata → D1 mirror\n         │\n  NEXT ENTITY 360 ASSEMBLY REFLECTS CHANGES\n  Loop never breaks. Both paths close.\n```\n\n---\n\n## A9. Data Pipelines\n\n```\nFLOW A — Structured Truth (Repeat Loop)\n  Source tool → Nango → Connector → Loader → Normalizer → Spine\n  → D1 mirror → THINK_QUEUE → Twin reads\n  → Approved action → Act → tool updated → webhook → BACK TO START\n\nFLOW B — Context (No Repeat Loop)\n  Gmail/Slack/Drive/Docs → Connector → Loader → Knowledge service\n  → context_extractions → linked to entities → D1 → Twin reads via Entity 360\n  One-way enrichment. No loop back.\n\nFLOW C — Memory (Governed Write)\n  Twin session / proposal / document insight\n  → proposal_queue → Triage Bot → R2 → Vectorize → Supabase → D1\n  Never writes to Spine. Memory and Spine are permanently separate.\n\nSIGNAL GENERATION\n  Spine entity changes → SignalAnalyzer → D1 cross_data\n  → evaluateTriggers() → insight generated → visible at Entity 360\n```\n\n---\n\n## A10. The Twin\n\n```\nWHAT:     The only agent. Model-agnostic. Persistent.\nWHERE:    Conceptually lives at Entity 360 (Spine ∩ Memory intersection).\nHOW:      Reads assembled context. Reasons. Proposes. Never writes.\n\n6 MEMORY LAYERS (assembled at session start):\n  Layer 1: Skills — what Twin can do for this user's domain\n  Layer 2: Knowledge — org memory refs, KB entries (read via Vectorize)\n  Layer 3: Lineage — prior proposals, approvals, rejections\n  Layer 4: Doctrine — constitutional laws (hard-injected, non-negotiable)\n  Layer 5: Conversational — recent session turns\n  Layer 6: Evolutionary — personal behavioral patterns\n\nGOVERNANCE RULES:\n  1. Propose, never write\n  2. Evidence before opinion\n  3. Lineage immutable (proposals never deleted)\n  4. Memory boundary absolute (personal = user only, org = Triage Bot only)\n  5. Gateway policy (email/legal/financial/HR = always human_review)\n  6. No silent execution (auto-approve ONLY: ≥0.80 + personal + no conflict)\n\n10 TRIGGERS (evaluated against Entity 360):\n  1. health_drop (15+ points)\n  2. renewal_approaching (≤90 days)\n  3. engagement_drop (30+ days silence)\n  4. arr_change (±10%)\n  5. goal_at_risk (status = at_risk)\n  6. support_escalation (5+ open tickets)\n  7. stale_data (entity not updated)\n  8. memory_conflict (conflicting low-confidence decisions)\n  9. context_gap ($50k+ ARR with zero context)\n  10. signal_cluster (3+ critical/high firing together)\n```\n\n---\n\n## A11. Separation of Concerns (Hard Walls)\n\n```\nSpine ↔ Memory:        NEVER merge. Meet at Entity 360 (read-only assembly only).\nAgents ↔ Supabase:     NEVER direct. D1 for Spine. Vectorize for memory.\nTwin ↔ Writes:         NEVER direct. Always proposes. Governance decides.\nTriage Bot ↔ Spine:    NEVER. Triage Bot writes to Memory only. Pipeline writes to Spine.\nADK ↔ State:           NEVER. Registry + cache. Stateless.\nR2 ↔ Twin:             NEVER. Twin reads Vectorize. R2 is cold storage.\nD1 ↔ Memory retrieval: NEVER for Twin. D1 metadata is for human browse only.\n                        Twin reads memory from Vectorize. Period.\n\nCF Edge stack IS the product for initial users.\nSupabase IS the fortress backup for promoted users.\nBoth paths: downstream workers see the same data.\n```\n\n---\n\n## A12. Known Gaps & Mitigations\n\n### Concern 1 — Vectorize Cold-Start\n\nUntil WIRE 8 (Vectorize pipeline) is live, Entity 360 serves Spine data only.\nTwin memory layers 2 and 6 are empty. The system functions but is significantly\nless useful without semantic memory retrieval. WIRE 8 is the highest-value wire\nafter the memory loop capture path (C2 stages 1-5).\n\n### Concern 2 — D1 Recovery for Initial Users\n\nFor initial users (no Supabase), D1 is the only copy. If D1 is corrupted or lost,\ndata is gone. Mitigation: Pipeline writes a lightweight R2 backup of every Spine\nwrite as a JSON line file per tenant per day. This is not Supabase-level durability,\nbut provides a recovery path.\n\n```\nPipeline write to D1 → also appends to R2: spine-backup/{tenant_id}/{date}.jsonl\nRecovery: replay JSONL into D1 from R2 backup.\nCost: ~$0. R2 writes are free. Storage is pennies.\n```\n\n### Concern 3 — R2 → Vectorize Non-Atomic Write\n\nTrue atomicity across R2 + Vectorize + D1 is not achievable in one transaction.\nIf Vectorize indexing fails after R2 write, content exists but is invisible to Twin.\n\nMitigation: reindex job.\n\n```\nScheduled (daily or on-demand):\n  Scan R2 memory/{tenant_id}/ keys\n  Compare against Vectorize metadata (memory_id index)\n  Any R2 key missing from Vectorize → re-chunk, re-embed, re-index\n  Idempotent. Safe to run repeatedly.\n```\n\n### Concern 4 — Gateway as Single Point\n\nGateway handles: auth, rate limiting, MCP routing, Zero Trust, tenant resolution.\nIf Gateway fails, nothing works. Mitigations:\n\n- CF Workers have built-in global redundancy (deployed to 300+ edge locations)\n- Gateway is stateless — no single-instance failure mode\n- Circuit breaker: if downstream service binding times out, gateway returns\n  503 with retry-after header (not a hang)\n- Health probes on all downstream services (/health endpoints)\n- Fallback: critical D1 reads (tenant resolution) can be cached in KV with\n  30-second TTL — survives brief D1 hiccups\n\n### Concern 5 — Initial Memory Load Backpressure\n\n1,017+ documents proposed simultaneously could overwhelm the live governance queue.\nMitigation: separate queue + rate limiting.\n\n```\nInitial load uses: BULK_MEMORY_QUEUE (separate from live pipeline-process queue)\nRate: max 10 concurrent proposals (step.do() concurrency limit in CF Workflow)\nPriority: lower than live operations (live queue always processed first)\nIsolation: bulk load never blocks real-time signals or user proposals\n```\n\n### Concern 6 — Intelligence Worker Think vs Act Isolation\n\nThink (proposal generation) and Act (execution) have inverse failure modes.\nBoth live in the same worker but consume from different queues:\n\n```\nintelligence-events queue → Think (proposal generation)\nintelligence-act queue    → Act (execution)\n\nSeparate queue consumers = separate CPU budgets.\nAct spike doesn't starve Think. Think failure doesn't block Act.\nAlready architected this way via CF Queue consumer bindings.\n```\n\n---\n\n---\n\n# SECTION B — PRODUCT REQUIREMENTS & TRAJECTORIES (PRT)\n\n---\n\n## B1. User Persona\n\n### Who the User Is\n\n```\nPRIMARY PERSONA: Operations Leader\n  Title: Founder / CEO / COO / VP Ops / CS Lead / RevOps Manager\n  Company: 10–500 employees, SaaS or services business\n  Tools: 5–30 SaaS tools connected (CRM, billing, project, support, comms)\n  Pain: opens 4 tabs to answer one question. Copies data between tools.\n        Starts every day not knowing what matters most.\n        AI conversations evaporate — same questions re-answered weekly.\n  Desire: open ONE thing. See what matters. Act. Move on.\n\nSECONDARY PERSONA: Account Manager / CSM / TAM\n  Title: Customer Success Manager / Technical Account Manager\n  Company: Managing 10–50 accounts\n  Pain: renewal surprises. Silent accounts churn. No prep for meetings.\n        Health scores in CRM are stale. Context is in email, not visible.\n  Desire: know which accounts need attention NOW. Get pre-briefed for meetings.\n          Never miss a renewal window. Never lose institutional memory about a client.\n```\n\n### How the User Behaves\n\n```\nMORNING (08:30):\n  Opens the app. Needs to know in 10 seconds:\n  - What's on fire (critical signals, overdue items)\n  - What's today (meetings, tasks, deadlines)\n  - What's ahead (commitments this week, renewals approaching)\n  Does NOT want: dashboards full of charts. Detailed reports. Configuration screens.\n  WANTS: a briefing. Like a chief of staff prepared it overnight.\n\nMID-MORNING (09:00–11:00):\n  Working through items. Responding to communications.\n  Needs: unified queue (emails + Slack + proposals in one place)\n  Needs: context when opening an account (full Entity 360 — what we know + what's happening)\n  Needs: AI that says \"this is the same pattern as last year, escalate now\" (not just scores)\n\nAFTERNOON (14:00–16:00):\n  Strategy + planning mode.\n  Needs: what's blocked? What needs a decision? What's the pipeline looking like?\n  Needs: week view. Department context. Metrics.\n\nEND OF DAY (17:00):\n  Wrapping up. Logging outcomes.\n  Needs: meeting notes go somewhere useful (not lost in email)\n  Needs: next day's prep already staged\n  Needs: memory promoted (what was learned today becomes institutional knowledge)\n```\n\n### How the User Travels Through the System\n\n```\n/desk         → Morning briefing (MorningContext API)\n  ↓ taps signal\n/entity360    → Full account view (Spine + Memory + Signals assembled)\n  ↓ Twin proposes\n/twin (Mode A)→ Approves action (or opens full Mode B for deep work)\n  ↓ back to work\n/inbox        → Communications + proposals queue\n/build        → Blockers, priorities\n/run          → Approve playbooks, execute automations\n/grow         → Check metrics, ARR, pipeline\n/memory       → Browse what the system knows (org + personal)\n\nThe user does NOT:\n  - Configure the system (system configures itself from Spine Selector)\n  - Edit raw data tables (entities are managed by connectors + normalizer)\n  - Train the AI (Twin learns from approvals/rejections automatically)\n  - Switch between multiple apps (one surface, one login, one left panel)\n```\n\n---\n\n## B2. How the System Gets Hydrated\n\n### First Hydration (Onboarding)\n\n```\nStage 0   User visits integratewise.ai → books demo\nStage 1   Nirmal demos live system (real data, not slides)\nStage 2   User signs up (Google OAuth or email)\nStage 3   Context questions:\n          - Use case: Personal / Work / Business\n          - Industry: SaaS, Healthcare, Retail, etc. (11 overlays)\n          - Department: Sales, CS, Marketing, Finance, etc.\n          - Company size: 1–10, 11–50, 51–200, 200+\n          - Primary goal: free text\n          - Workspace name\nStage 4   Spine Selector (backend, invisible to user):\n          - Resolves domain key + industry overlay + context seed\n          - Creates tenant + workspace + RBAC + free subscription\n          - Writes tenant_spine_config (controls everything downstream)\nStage 5   Connector Projection:\n          - Nango Connect UI shows domain-ranked connectors\n          - User selects tools → OAuth flow → connection established\nStage 6   Creamy Layer (first data load):\n          - SPINE SCHEMA HYDRATION (validate entity types against tenant_spine_config)\n          - Source tool API → Nango token → Connector → Loader (8 stages)\n          - → Normalizer (8 stages) → Spine D1 (edge cache)\n          - User sees domain-specific progress messages\n          - Entity resolution, relationship graph forming in background\n          - NO SUPABASE for initial users — D1 only (per D-011)\nStage 7   L1 Dashboard loads with REAL Spine data from D1\n          - Schema-matched workbench\n          - Domain projection applied\n          - No mock data. Ever.\n```\n\n### Continuous Hydration (After Onboarding)\n\n```\nDAILY SYNC:\n  Cron trigger (every 5 min) → Connector polls delta from tools\n  → Normalizer processes → Spine updated\n  → D1 mirror updated → KV invalidated\n  → Signals generated if entity state changed\n\nWEBHOOK SYNC:\n  Tool fires webhook → ingress.integratewise.ai (signature verified)\n  → Normalizer → Spine updated (near real-time)\n\nMANUAL ENTRY:\n  User creates entity in UI → via gateway → pipeline db-proxy → Spine\n\nDOCUMENT INGESTION:\n  User uploads file → knowledge service → context_extractions\n  → Linked to entities → available at Entity 360 (Vectorize retrieval)\n\nMEMORY INGESTION:\n  Filesystem vault (1,017+ docs) → memory-repo connector\n  → Triage Bot → R2 → Vectorize → Supabase → D1\n  Twin sessions → conversational_memory (auto)\n  Promotions → personal_memory or org_memory (governed)\n```\n\n---\n\n## B3. The Surfaces (Frontend)\n\n### Left Panel Navigation (The \"One Surface\" Doctrine)\n\n```\nHOME         /desk             What today looks like. Plan. Direction.\nCATCH-UP     /inbox            Alerts, decisions, system-drafted items.\n\nWORK:\nRUNWAY       /build            Blockers, roadmaps, priorities.\nWARM         /decide           Context prep. 12/14 department views.\nACT          /run              Automations, playbooks, approvals, checklists.\nREACT        /react            Live system alerts, incident queues.\nREPEAT       /schedule         Templates, recurring automation schedules.\nREPORT       /grow             ARR, pipeline, strategic metrics.\nOVERDUES     /tasks            Overdue actions.\nHORIZON      /horizon          Week-in-a-view planner.\n\nENTITY 360   /entity360        First-class view. Spine ∩ Memory. Insights live here.\n                               Twin's conceptual home. Not a drawer tab.\n\nASSETS:\nYOUR ASSETS  /memory/personal  Personal + Conversational. Work/Personal toggle.\nTEAM ASSETS  /memory/org       Org memory. Templates. Lineages.\n\nTWIN         /twin             Full OpenWebUI hub. Model-agnostic. Two modes.\nINTEGRATIONS /connectors       Tool connections (Nango).\nSETTINGS     /settings         Tenant config.\nPROFILE                        Work | Personal toggle.\n```\n\n### Three Surfaces\n\n```\nSURFACE 1 — L1 Workbench (main content area)\n  Where the user works. Routes render here.\n  Intelligence overlay: bottom-to-top, ONLY on critical trigger. Passive otherwise.\n  Slimmed overlay: spine + context data reference only.\n\nSURFACE 2 — Twin Workbench (/twin)\n  MODE A — Sliding Overlay (passive)\n    Hidden by default. Pops up ONLY on critical signal or approval.\n    Dismisses when user acts.\n  MODE B — Full OpenWebUI Hub (user-initiated)\n    /twin route. Full-page. Chat + Skills + Tools + Memory + Workflows + Models.\n    Execution surface: think + act + adjust live here.\n    Agent Zero or OpenWebUI as runtime.\n\nSURFACE 3 — IW Governance Workbench (see Section D3 for full spec)\n  NOT merely an approval queue. The collaborative operating layer.\n  Shared Task Board + Proposal Queue + Decision Ledger +\n  Memory Promotion + Procedure Evolution + Outcome Tracking + Audit.\n  Where Real Twin and Digital Twin ENGAGE TOGETHER.\n  Primary collaboration through tasks, not chat.\n```\n\n### Entity 360 — The Cognitive Assembly Point\n\n```\nRoute: /entity360/:entityId — first-class left panel view.\n\nAssembly (parallel):\n  D1 query    → Spine (operational truth)\n  Vectorize   → Memory (AI Search, semantic, top K)\n  D1 query    → Signals (time-ordered, recent)\n\nWHERE:\n  Memory intersects Spine WITHOUT crossing over.\n  Insights generated and read — NOWHERE ELSE.\n  Twin conceptually lives here.\n  User sees truth + knowledge in one view.\n```\n\n### L2 Component Migration (Old → New)\n\n```\nspine         → L2 overlay (stays)\ncontext       → L2 overlay (stays)\nknowledge     → /memory (Assets nav)\nentity360     → /entity360 (left panel, first-class view)\nthink         → Twin Workbench\nact           → Twin Workbench / CF Workflows\nadjust        → Twin Workbench\nTwin panel    → Twin Workbench (removed from L2)\nAIChat        → Twin Workbench (removed from L2)\n```\n\n---\n\n## B4. Product Split & Paywall\n\n### Phase 1 Product (Ships Immediately — Three Workbenches)\n\n```\nWORKBENCH 1: Account Success\n  For: CSM / TAM users\n  Views: 27 Account Success views (built, real data)\n  Intelligence: NONE in Phase 1\n  Connectors: Nango + MCP connected\n  Auth: CF edge (D1 tenant/user, no Supabase)\n\nWORKBENCH 2: Business Ops\n  For: Founder / CEO / COO / Ops users\n  Views: 14 BizOps modules (built, real data)\n  Intelligence: NONE in Phase 1\n  Connectors: Nango + MCP connected\n  Auth: CF edge (D1 tenant/user, no Supabase)\n\nWORKBENCH 3: Customer Zero (IntegrateWise internal)\n  For: Nirmal\n  Views: ALL (AS + BizOps + Ops + full system)\n  Intelligence: Full (Twin, memory, governance)\n  Connectors: All connected\n  Auth: CF edge (full access)\n\nPHASE 1 INCLUDES:\n  ✅ Three workbenches (AS + BizOps + Customer Zero)\n  ✅ Nango setup (OAuth connections)\n  ✅ MCP connected (tools accessible)\n  ✅ Auth: CF edge only (D1 tenant/user)\n  ✅ Data from D1 hard cache (Cloudflare only)\n\n  ✗ NO intelligence for external users (AS + BizOps)\n  ✗ NO Twin for external users\n  ✗ NO memory loop for external users\n  ✗ NO Supabase auth (CF edge handles it)\n```\n\n### Delivery Model\n\nL1 and L2 are built. Features ship as-is. One codebase. One deploy. Tiers gated by runtime feature flags.\n\n### Tier Structure\n\n```\nFREE:       /desk, /inbox, /tasks (limited). 1 connector. Entity 360 (read-only).\n            Manual data entry. No Twin. No memory. No AI Search.\n\nSTARTER:    Full L1 (all routes). 3 connectors. Twin Mode A (reactive overlay).\n            Basic signals (10 triggers). Calendar workflow.\n\nPRO:        Twin Mode B (Full Hub). Unlimited connectors. Entity 360 + memory (Vectorize).\n            Memory (personal + org + conversational). AI Search.\n            CF Workflows. Proposal queue + HITL. /react.\n\nENTERPRISE: External LLM (MCP endpoint per tenant). Custom domain.\n            Multi-workspace. SLA. Manual provisioning.\n```\n\n### Paywall Mechanism\n\n```\ntenant_spine_config.subscription_tier → free | starter | pro | enterprise\nGateway reads tier → injects x-subscription-tier header\nFrontend reads tier → gates routes via feature flags\nBackend returns 403 if feature not in tier\nONE codebase. ONE deploy. Runtime check only.\n```\n\n### Payment (Not Yet Wired)\n\n```\nEXISTS: services/billing/ (Stripe + Razorpay), POST /api/v1/subscriptions\nNEEDED: webhook → tier update, frontend gate (useSubscription()), upgrade UI, downgrade handling\n```\n\n---\n\n## B5. Backend Services (10 Deployed Workers)\n\n24 service directories exist in the monorepo. Post-consolidation (v3.6), they deploy as **10 Cloudflare Workers**:\n\n```\nSERVICE             ABSORBS                              CREDENTIAL\n────────────────────────────────────────────────────────────────────────────\npipeline            normalizer, spine-v2                  SOLE Supabase holder.\n                    8-stage Normalizer. Spine writer.     db-proxy for all writes.\n\nintelligence        think, act, govern, agents,           Service binding to pipeline.\n                    agent-registry, hermes\n                    Signal engine. Proposals. HITL.\n\nconnector           loader, mcp-connector, store          Nango key. R2 bucket.\n                    Nango OAuth. MCP server (20 tools).\n                    Webhook intake. File store.\n\nknowledge           (standalone)                          Service binding to pipeline.\n                    KB ingestion. Memory shim.\n                    Embedding coordination.\n\nworkflow            (standalone)                          Service bindings to all.\n                    BFF. HITL gate (DO). Analytics.\n                    Stream gateway. Onboarding.\n\ngateway             (standalone)                          JWT validation. CF Zero Trust.\n                    Auth. Rate limiting. Routing.\n                    MCP combined. Single entry.\n\nconnector-sync      (standalone)                          Nango key.\n                    Delta polling. Background sync.\n\nwebhook-ingress     (standalone)                          Signature verification.\n                    External webhook intake.\n\nbilling             (standalone)                          Stripe/Razorpay keys.\n                    Stripe + Razorpay.\n\ntenants             (standalone)                          D1 (edge-first, no Supabase).\n                    Tenant + user management. RBAC.       Promotes to Supabase on review.\n```\n\nOther directories (continuity, folder-watcher, l2, admin, telemetry) exist as source but are either stubs, pending deployment, or absorbed into the above.\n\n### Queues (10 Active)\n\n```\npipeline-process, signals, intelligence-events, knowledge-ingest,\naccelerator-trigger, intelligence-act, signals-dlq, pipeline-dlq,\nops-dlq, knowledge-dlq\n```\n\n---\n\n## B6. Repos & Maintenance\n\n```\nREPO                            ROLE                    STACK           DEPLOY\n────────────────────────────────────────────────────────────────────────────────\nintegratewise-live              Engine. All backend.    TS/CF Workers   Workers\n                                packages/ + services/\n\nBusiness Intelligence           BI Hub frontend.        TanStack/React  app.integratewise.ai\nAccount Success & TAM           CS Hub frontend.        TanStack/React  accounts.integratewise.ai\nintegratewise-ops               Ops surface.            Vue3/Nuxt       ops.integratewise.ai (internal)\nintegratewise-docs              Public docs.            Static          docs.integratewise.ai\n```\n\n### Shared Packages (from integratewise-live/packages/)\n\n```\n@integratewise/types        TypeScript types, schemas (EXISTS)\n@integratewise/api-client   Gateway fetch wrapper, framework-agnostic (NEW)\n@integratewise/hooks        React Query wrappers for BI + AS (NEW)\n@integratewise/ui           Shared React components (NEW)\n@integratewise/adk          Registry + cache. Routing. (NEW)\n```\n\n### Independence\n\n```\nEach repo ships independently. Each builds independently.\nShared logic in packages/ — fix once, all repos update.\nGateway is the single API contract (OpenAPI spec).\nNo repo blocks another. Different agents work in isolation.\n```\n\n---\n\n## B7. Phased Wiring (Priority Order)\n\n```\nWIRE 0    Apply 032_governed_proposals.sql to Supabase (P1 BLOCKER)\nWIRE 1    /desk → MorningContext API (morning-context-builder.ts is BUILT)\nWIRE 2    /inbox → HITL queue + engagement entities + signals\nWIRE 3    Twin Board → auto-activation + POST /api/v1/twin/chat\nWIRE 4    L2 overlay slim-down (remove Twin/AIChat, keep spine+context)\nWIRE 5    /entity360 → build as first-class view (D1 + Vectorize + D1)\nWIRE 6    /memory → personal_memory + org_memory + Vectorize search\nWIRE 7    /react → live signal queue (distinct from /triage)\nWIRE 8    Vectorize pipeline (R2 → chunk → embed → index)\nWIRE 9    Shared packages (api-client, hooks, ui)\nWIRE 10   External LLM (per-tenant MCP endpoint + CF Zero Trust token)\nWIRE 11   Five Connections (memory-repo, folder-watcher, continuity→Supabase, ops wiring, docs pipeline)\nWIRE 12   Paywall (Stripe/Razorpay webhook → tier → frontend gate)\n```\n\n---\n\n## B8. What's Already Built\n\n```\n✅ 8-stage Normalizer + Spine write (pipeline)\n✅ Think service + 10 twin triggers + evaluateTriggers()\n✅ Proposal lifecycle (govern, 9 routes, 8-state machine)\n✅ Act service\n✅ CF Workflow (TriageWorkflow — durable execution)\n✅ HITL gate Durable Object\n✅ Nango connector layer (30+ tools, OAuth, token refresh)\n✅ MCP server (20 tools)\n✅ Session capture (/v1/mcp/capture_session)\n✅ MorningContextBuilder (morning-context-builder.ts)\n✅ Zero Trust (CF Access, 4 public domains, service bindings)\n✅ memory.* tables (Supabase + D1 partial mirror)\n✅ Account Success views (27 — real data)\n✅ BizOps views (14 modules — real data)\n✅ Sidebar nav — projection-native\n✅ AI Insight popup system\n✅ All BI Hub routes (desk, twin, inbox, memory, triage, run, decide, build, grow, horizon)\n✅ All AS routes (dashboard, accounts, inbox, memory, tasks, twin)\n✅ TwinCopilot.tsx (ops — brain selector, dials, canvas, HITL)\n✅ memory.index.tsx (ops — Coda-style dual-pane memory hub)\n✅ run.tsx (ops — 4 Edge Agent grid, CLI sandbox, sync logs)\n✅ verify-architecture-alignment.ts (Zero Python + CouchDB audit)\n✅ Edge routing: pipeline.dev / gateway.dev / ingress.dev\n✅ services/billing (Stripe + Razorpay worker)\n```\n\n---\n\n---\n\n---\n\n# SECTION C — THE MEMORY LOOP (BUILD THIS FIRST)\n\nEverything else falls into place once the memory loop works.\n\n---\n\n## C1. Why Memory First\n\n```\nWithout the memory loop:\n  - Every AI session starts cold\n  - Decisions made yesterday are invisible today\n  - Org knowledge stays in filesystem/Gemini brain (scattered, agent-specific)\n  - Twin cannot answer \"what do we know about X\" (Vectorize is empty)\n  - Entity 360 shows Spine only (operational truth without institutional context)\n  - Docs pipeline has nothing to publish\n\nWith the memory loop:\n  - Every session starts with full context\n  - Decisions compound (yesterday's approval = today's knowledge)\n  - All AI agents (Gemini, Kimi, Kiro, Claude, ChatGPT) contribute to one memory\n  - Twin answers from real institutional knowledge\n  - Entity 360 shows Spine + Memory intersection (insights emerge)\n  - Docs pipeline has governed content to publish\n  - Progressive discussion between founder and agent becomes real\n```\n\n---\n\n## C2. The Memory Loop — Complete Specification\n\n```\nCONVERSATIONAL MEMORY → PROMOTION → ORG MEMORY → VECTORIZE → TWIN READS\n\nThis is the only path. There is no shortcut. Org memory is ALWAYS formed\nfrom conversational memory. It is never written directly.\n```\n\n### The Loop\n\n```\n┌──────────────────────────────────────────────────────────────────────────┐\n│                        THE MEMORY LOOP                                   │\n│                                                                          │\n│  1. CAPTURE                                                              │\n│     Any conversation (Twin session, external LLM, manual input)          │\n│     → memory.write_conversational (MCP tool)                             │\n│     → conversational_memory table (D1 + Supabase)                       │\n│     Automatic. No governance needed. This is the scratchpad.             │\n│                                                                          │\n│  2. IDENTIFY                                                             │\n│     Twin (or swarm agent) identifies something worth keeping:            │\n│     a decision, a pattern, a commitment, a learning, an insight          │\n│     Not everything gets promoted — only what has lasting value.           │\n│                                                                          │\n│  3. PROPOSE                                                              │\n│     → memory.propose (MCP tool)                                          │\n│     → D1 proposals table (Triage Bot queue)                              │\n│     Payload:                                                             │\n│       tenant_id, content_type, title, body                               │\n│       target_layer: \"organisational\" | \"personal\" | \"entity\"             │\n│       confidence: 0.0–1.0                                                │\n│       evidence_chain: [source references]                                │\n│       tags: [categories]                                                 │\n│                                                                          │\n│  4. GOVERN                                                               │\n│     Triage Bot (CF Workflow) scores on 5 dimensions:                     │\n│       confidence + relevance + risk + conflict + quality                  │\n│     ≥ 0.85 → auto-approve                                               │\n│     0.60–0.84 → HITL (human review in Governance bench)                  │\n│     < 0.60 → reject                                                     │\n│                                                                          │\n│  5. STORE                                                                │\n│     Approved entry written to THREE places atomically:                    │\n│       R2: raw content (cold, source of truth)                            │\n│       Supabase org_memory: metadata (via pipeline db-proxy)              │\n│       D1: metadata mirror (for human browse at /memory)                  │\n│                                                                          │\n│  6. INDEX                                                                │\n│     → Vectorize: chunk → embed → semantic index                          │\n│     → Entity linking: which entities does this relate to?                │\n│     → Now retrievable by Twin via AI Search                              │\n│                                                                          │\n│  7. RETRIEVE                                                             │\n│     Next Entity 360 assembly:                                            │\n│       Vectorize query → top K relevant memory for this entity            │\n│     Next Twin session:                                                   │\n│       Briefing includes newly promoted knowledge                         │\n│     The insight that was approved yesterday is context today.             │\n│                                                                          │\n│  LOOP CLOSES.                                                            │\n│  New session → new conversation → new promotable insights →              │\n│  new proposals → governance → store → index → retrieve → repeat.         │\n│                                                                          │\n└──────────────────────────────────────────────────────────────────────────┘\n```\n\n---\n\n## C3. The Initial Load (Using Agent Swarm)\n\n```\nSOURCE:\n  /Users/nirmal/Github/IntegrateWise - Memory/ (1,017+ docs)\n  /Users/nirmal/.gemini/antigravity/brain/ (18 sessions, architecture, wireframes)\n  /Users/nirmal/Github/integratewise-live/.kimi/ (3 transcripts)\n  All prior AI conversations that produced decisions\n\nTOOL:\n  BulkCleanupSwarmWorkflow (CF Workflow, durable)\n    → DataCleanerAgent: parse markdown, extract frontmatter, normalize\n    → EntityResolverAgent: match to Spine entities, assign entity_refs, deduplicate\n  Chunks of 5 records. Fan-out. Handles errors per chunk.\n\nSEQUENCE:\n\nSTEP 1: INGEST AS CONVERSATIONAL\n  Memory-repo connector reads vault + AI session transcripts\n  Each document → memory.write_conversational (MCP)\n    session_id: \"initial_load_{category}_{uuid}\"\n    role: \"system\"\n    content: document body\n    metadata: { source, category, file_path, frontmatter }\n  → conversational_memory populated with raw historical content.\n\nSTEP 2: SWARM CLEANS + RESOLVES\n  BulkCleanupSwarmWorkflow triggered per batch:\n    DataCleanerAgent: parse, normalize, extract structured data\n    EntityResolverAgent: match entities, assign spine_ids, deduplicate\n  Output: cleaned records with entity_refs and category assignments.\n\nSTEP 3: PROMOTE VIA memory.propose\n  Each cleaned record that is decision/doctrine/pattern/commitment/learning:\n    memory.propose (MCP):\n      target_layer: \"organisational\"\n      content_type: from frontmatter category\n      confidence: 0.85 (pre-existing approved docs)\n      evidence_chain: [file_path, session_id]\n  → D1 proposals table filled.\n\nSTEP 4: TRIAGE BOT PROCESSES\n  CF Workflow (TriageWorkflow):\n    ≥ 0.85 → auto-approve (initial load = pre-vetted)\n    Conflicts → human_review\n  Approved → org_memory written (R2 + Supabase + D1).\n\nSTEP 5: VECTORIZE INDEXING\n  Every approved entry → R2 → chunk → embed → Vectorize index\n  Entity_refs + category stored as metadata in index.\n  Twin can now retrieve via AI Search.\n\nSTEP 6: VERIFY\n  Entity 360 shows memory intersection for known entities.\n  Twin answers from org_memory via Vectorize.\n  /memory UI populated.\n  Memory loop is primed. Ongoing sessions compound from here.\n```\n\n---\n\n## C4. Ongoing Operations\n\n```\nEVERY TWIN SESSION:\n  Conversation → memory.write_conversational (auto)\n  Twin identifies promotable content → memory.propose\n  Triage Bot governs → approved → R2 → Vectorize → org_memory\n  Next session: Twin briefing includes the new knowledge\n\nEVERY EXTERNAL LLM SESSION:\n  Claude/ChatGPT via MCP → session captured → memory.write_conversational\n  If promotable → memory.propose → same governance pipeline\n\nEVERY DOCUMENT UPLOAD:\n  Knowledge service processes → context_extractions linked to entities\n  If promotable → memory.propose → same governance pipeline\n\nEVERY APPROVAL/REJECTION:\n  Approve → org_memory + Vectorize (knowledge compounds)\n  Reject → stored as rejected (lineage preserved, Twin learns)\n```\n\n---\n\n## C5. MCP Tools That Power the Memory Loop\n\n```\nmemory.write_conversational   Capture to scratchpad         Stage 1 (Capture)\nmemory.read_conversational    Read session context           (briefing assembly)\nmemory.propose                Submit for promotion           Stage 3 (Propose)\nmemory.search_org             Search approved org memory     Stage 7 (Retrieve)\n\nAll exist. All deployed. All callable internally and externally via MCP.\nThe loop requires ZERO new backend tools.\n```\n\n---\n\n## C6. Wiring Needed to Complete the Memory Loop\n\n```\n1. Memory-repo connector trigger (script exists → schedule + run)\n2. Gemini/Kimi transcript ingestion (same pattern as vault)\n3. BulkCleanupSwarmWorkflow endpoint invocation\n4. Vectorize pipeline (R2 → chunk → embed → index) — not yet wired\n5. Triage Bot auto-approve path verified with real data\n6. D1 metadata mirror sync (full org_memory)\n7. Entity 360 Vectorize query integration\n8. Twin session briefing reads from Vectorize (Layers 2+6)\n\nPriority: 1–5 first. Once memory flows through the full loop,\neverything downstream (UI, Entity 360, Twin briefing) just reads from it.\n```\n\n---\n\n## C7. This Conversation — Documented as Memory\n\nDecisions made in this session that must enter the loop:\n\n```\nD-2026-06-04-001: No Hermes, no Claw. Twin is the only agent. Model-agnostic.\nD-2026-06-04-002: No n8n. CF Workflows + CF Queues + DOs replace it.\nD-2026-06-04-003: ADK = registry + cache only. No state, no memory, no orchestration.\nD-2026-06-04-004: Insights live at Entity 360 only. Nowhere else.\nD-2026-06-04-005: Memory retrieved via AI Search (Vectorize) only. Not D1. Not Supabase.\nD-2026-06-04-006: Entity 360 is first-class left panel view. Not a drawer tab.\nD-2026-06-04-007: L2 slimmed to spine + context only. Everything else moved out.\nD-2026-06-04-008: Org memory ALWAYS formed from conversational memory. Never direct write.\nD-2026-06-04-009: Build memory loop FIRST. Everything else follows.\nD-2026-06-04-010: Paywall = runtime feature flags. One codebase. One deploy.\n\nWhen memory loop is built: these enter via memory.propose → Triage Bot → org_memory → Vectorize.\nEvery future session will have these as context. This conversation never needs repeating.\n```\n\n---\n\n---\n\n# SECTION D — PRODUCT PILLARS & CONTINUITY BRIDGE\n\n---\n\n## D1. The Three Product Pillars\n\n```\nIW WORKSPACE     Where the Real Twin works.\nIW TWIN          The Digital Twin.\nIW GOVERNANCE    The trust between them.\n```\n\n---\n\n## D2. Real Twin vs Digital Twin\n\n```\nREAL TWIN (the user):\n  Works in IW Workspace.\n  Makes decisions.\n  Approves or declines proposals.\n  Connects tools.\n  Reviews insights at Entity 360.\n  The human. The authority. The source of intent.\n\nDIGITAL TWIN (the AI):\n  A continuously evolving representation of the user's work, context,\n  memory, relationships, commitments, and operating patterns.\n\n  Reads from Spine (operational truth).\n  Reads from Memory (institutional knowledge via Vectorize).\n  Reasons across both.\n  Learns through continuity (sessions compound, patterns promote).\n  Proposes actions.\n  Never bypasses Governance.\n\n  Model-agnostic. Runs on any LLM. The model is a parameter, not a dependency.\n  Not a chat interface — a true continuity layer synchronized with operational reality.\n\nIW GOVERNANCE (the trust layer):\n  Sits between Real Twin and Digital Twin.\n\n  Real Twin       ↕ Governance       ↕ Digital Twin\n\n  Everything proposed by the Digital Twin is:\n    Proposed → Scored → Approved → Recorded\n  before execution.\n\n  Nothing crosses without governance.\n  Triage Bot scores confidence.\n  Proposal queue holds pending actions.\n  HITL gate for uncertain decisions.\n  The boundary. The trust. The audit trail.\n```\n\n---\n\n## D3. IW Governance Workbench\n\nIW Governance is NOT merely an approval queue.\nIt is the collaborative operating layer where Real Twin and Digital Twin **engage together**.\n\n### Purpose\n\n```\nWork is coordinated.\nDecisions are reviewed.\nProcedures evolve.\nKnowledge accumulates.\nActions are governed.\nOutcomes are recorded.\n```\n\nThe Governance Workbench sits between thinking and acting.\n\n### Core Principle\n\n```\nThe Digital Twin does not primarily CHAT.\nThe Digital Twin primarily WORKS.\n\nThe shared task board is the primary collaboration surface.\nChat remains available as a supporting interaction, but:\n  Tasks, Proposals, Decisions, and Outcomes\nare the primary objects of collaboration.\n```\n\n### Governance Workbench Structure\n\n```\n1. SHARED TASK BOARD (center of collaboration)\n   Both Real Twin and Digital Twin interact through the same board.\n\n   Task Sources:\n     Human users, Digital Twin, Signals, Workflows, Connectors, External systems\n\n   Task Structure:\n     Goal, Description, Context, Related Entities, Related Documents,\n     Procedures, Knowledge References, Status, Priority, Assignee,\n     Due Date, History, Outcomes\n\n   Digital Twin may: create tasks, update tasks, suggest priorities,\n     identify blockers, recommend next actions, detect duplicate work,\n     link related knowledge, attach supporting evidence\n\n   Real Twin may: create tasks, update tasks, approve/reject recommendations,\n     assign work, close work, provide judgment\n\n2. PROPOSAL QUEUE\n   Every recommendation from Digital Twin enters here.\n\n   Examples: process changes, workflow updates, memory promotions,\n     escalation recommendations, new procedures, automation suggestions,\n     strategic recommendations\n\n   States: Draft → Pending Review → Approved → Rejected → Deferred → Executed\n\n   Every proposal contains:\n     Confidence score, Risk score, Evidence, Source context,\n     Impact estimate, Linked entities\n\n3. DECISION LEDGER\n   Permanent record of decisions.\n\n   Records: what, why, who approved, supporting evidence,\n     expected outcome, actual outcome\n\n   Decisions become organizational memory after governance review.\n\n4. MEMORY PROMOTION QUEUE\n   Controls what becomes institutional knowledge.\n\n   Sources: conversations, tasks, procedures, decisions, documents, workflows\n\n   Flow:\n     Conversational Memory → Proposal → Governance Review\n     → Organizational Memory → Book of Records\n\n5. PROCEDURE EVOLUTION\n   Users attach procedures to tasks.\n   Digital Twin proposes improvements.\n   Changes enter Governance. Real Twin approves or rejects.\n   Approved procedures become governed organizational knowledge.\n\n   Example:\n     Current: Review account → Schedule meeting → Send summary\n     Proposed: Review account → Analyze support history → Check expansion signals\n              → Schedule meeting → Generate briefing → Send summary\n\n6. OUTCOME TRACKING\n   Every completed task generates outcomes.\n   States: Successful, Failed, Partial Success, Escalated, Deferred\n\n   Outcomes linked to: Entities, Procedures, Decisions, Signals, Memory\n   Creates continuity and learning.\n\n7. AUDIT & LINEAGE\n   Every action recorded: who created, who modified, who approved,\n   what changed, when, why.\n\n   Nothing enters organizational memory without lineage.\n```\n\n### Relationship With Other Pillars\n\n```\nGOVERNANCE ↔ SPINE:\n  Governance references Spine entities but does not replace the Spine.\n  Spine: entities, relationships, signals, operational truth.\n  Governance: tasks, proposals, decisions, procedures, approvals, outcomes.\n\nGOVERNANCE ↔ MEMORY:\n  Governance controls promotion INTO memory.\n  Memory preserves continuity. Governance controls trust.\n  Nothing enters org_memory without governance approval.\n\nGOVERNANCE ↔ TWIN:\n  Digital Twin continuously: monitors tasks, reads context, reads memory,\n  reads Spine entities, identifies risks, suggests actions, maintains continuity.\n  The Twin NEVER bypasses Governance.\n\nGOVERNANCE ↔ WORKSPACE:\n  IW Workspace — where the Real Twin works.\n  IW Twin — the Digital Twin.\n  IW Governance — where the Real Twin and Digital Twin engage TOGETHER.\n```\n\n### The Core Relationship\n\n```\nShared Tasks. Shared Decisions. Shared Accountability. Shared Continuity.\n\nThe Real Twin decides.\nThe Digital Twin assists.\nGovernance records, controls, and evolves the collaboration.\n```\n\n---\n\n## D3b. Positioning Statement\n\n> IW Workspace is where you work. IW Twin is your Digital Twin.\n> IW Governance is where you engage together.\n\n> Real Twin and Digital Twin. Working together through shared tasks, memory, and governance.\n\n---\n\n## D4. IW Continuity Bridge (The Core Product Engine)\n\nThe bridge is not MCP. MCP is a protocol adapter. The bridge is the normalization +\ncontinuity + governance layer that sits above any protocol.\n\n```\nIW CONTINUITY BRIDGE\n  ├── Loader (universal intake — any source, any format)\n  ├── Normalizer (8-stage, LLM-in-the-loop)\n  ├── Entity Resolution (one Person across HubSpot + Jira + Gmail)\n  ├── Trait Detection (18 traits, 7 resource types)\n  ├── Spine Cache (D1 — operational truth at edge)\n  ├── Delta Sync (cursor-based, schema-driven)\n  ├── Webhook Processing (real-time intake)\n  ├── Memory Linking (entity_refs to Spine entities)\n  └── Protocol Adapters\n        ├── MCP (Claude, ChatGPT, Perplexity, any MCP client)\n        ├── REST (browser apps, internal services)\n        ├── GraphQL (future)\n        └── Future protocols\n```\n\n### Why \"Continuity Bridge\" Not \"MCP Bridge\"\n\n```\nMCP is one protocol. It will be superseded or versioned.\nThe bridge is permanent. The normalization is permanent.\nEntity Resolution is permanent. Trait Detection is permanent.\n\nWorkato, Zapier, Composio — they route data.\nIntegrateWise normalizes, resolves, governs, remembers.\n\nThe continuity is the moat.\nThe normalization is the moat.\nThe governed memory is the moat.\nMCP is just one door into the house.\n```\n\n### What Sits Above Protocol\n\n```\nProtocol layer (MCP / REST / GraphQL)\n       ↕\nGOVERNANCE (Zero Trust + Triage Bot + Proposal Queue + HITL)\n       ↕\nCONTINUITY BRIDGE (Loader + Normalizer + Entity Resolution + Spine Cache)\n       ↕\nMEMORY (R2 + Vectorize + governed org_memory)\n       ↕\nTOOLS (50+ connectors via Nango + adapters)\n```\n\n---\n\n## D5. Connection Paths (Corrected — No Supabase for Initial Users)\n\nPer D-011: CF edge creates user first. Supabase only after promotion (usage review, Nirmal decides).\n\n### Onboarding Sequence\n\n```\nSignup → Role + Department + Industry\n  → Schema Selection (writes D1 tenant_spine_config)\n  → Connector Projection (Nango Connect UI)\n  → Auth Flow (Nango handles OAuth)\n  → SPINE SCHEMA HYDRATION\n  → Loader → Normalizer → Spine D1 (creamy initial load)\n  → Dashboard loads with real data\n```\n\n### Three Connection Paths — Unified\n\n```\nHOW DATA ENTERS THE SPINE (Three Channels)\n\nCHANNEL 1 — VIA CONNECTOR (pull-based, Nango-managed OAuth)\n  User connects a tool (HubSpot, Jira, Stripe, etc.)\n  → Nango handles OAuth + token storage + refresh\n  → connector-sync polls delta (cron every 5 min)\n  → OR webhook-ingress receives real-time event\n  → SPINE SCHEMA HYDRATION (validate entity types against tenant_spine_config)\n  → Loader (8 stages) → Normalizer (8 stages) → Spine D1\n\n  This is the standard path for 30+ supported tools.\n  Auth: Nango holds tokens. D1 holds config. KV holds status.\n\nCHANNEL 2 — VIA API WRAPPER (non-MCP tools, REST APIs wrapped by us)\n  Two sub-paths:\n\n  2A — Nango-authed (tool supports OAuth, we wrap it)\n    Same as Channel 1 but for tools without native connector adapters.\n    Auth via Nango → API call → response wrapped →\n    SPINE SCHEMA HYDRATION → Loader → Normalizer → Spine D1\n\n  2B — API Router / Key-based (tool uses API key, no OAuth)\n    Auth: API key stored in D1 (tenant config) or KV\n    Our wrapper calls tool API → response →\n    SPINE SCHEMA HYDRATION → Loader → Normalizer → Spine D1\n\n  HARD RULE: ALL non-MCP data ingestion goes through Loader → Normalizer.\n  Nothing touches Spine without the pipeline. Period.\n\nCHANNEL 3 — VIA MCP (protocol-native, two sub-paths)\n\n  3A — API WRAPPER over MCP (MCP as transport, data still normalizes)\n    External system pushes data via MCP protocol (tool calls)\n    BUT the data is raw/unstructured from source tools.\n    → Routed to Loader → Normalizer → Spine D1\n    Same pipeline. MCP is just the transport.\n    Example: a custom integration that speaks MCP but pushes CRM records.\n\n  3B — NATIVE MCP (true protocol-native speakers)\n    Claude / ChatGPT / Perplexity / Agent frameworks → mcp.integratewise.ai\n    Auth: CF Zero Trust Service Token + Bearer JWT\n    These are READERS + GOVERNED WRITERS:\n      Read: D1 Spine + Vectorize Memory (via spine.*, memory.* MCP tools)\n      Write: memory.propose → Triage Bot → governed path\n\n    Native MCP clients DO NOT go through Loader/Normalizer.\n    WHY: data is already structured/normalized by protocol definition.\n    They speak directly to the Spine through the protocol adapter.\n\n    BUT: they NEVER write to Spine directly.\n    They can only: read Spine, read Memory, propose to governance.\n```\n\n### The Complete Map\n\n```\nSOURCE                    AUTH                CHANNEL     PIPELINE?        SPINE WRITE?\n─────────────────────────────────────────────────────────────────────────────────────────\nHubSpot, Jira, Stripe    Nango OAuth         1           YES (full)       Loader→Norm→D1\nGmail, Slack, Drive       Nango OAuth         1           YES (full)       Loader→Norm→D1\nCustom REST API (OAuth)   Nango OAuth         2A          YES (full)       Loader→Norm→D1\nCustom REST API (key)     API key (D1/KV)     2B          YES (full)       Loader→Norm→D1\nMCP wrapper (raw data)    MCP + Zero Trust    3A          YES (full)       Loader→Norm→D1\nClaude/ChatGPT (native)   MCP + Zero Trust    3B          NO (native)      READ ONLY + propose\nPerplexity (native)       MCP + Zero Trust    3B          NO (native)      READ ONLY + propose\nCustom agent (native)     MCP + Zero Trust    3B          NO (native)      READ ONLY + propose\nUser manual entry         Gateway JWT         2B          YES (via proxy)  Loader→Norm→D1\nDocument upload           Gateway JWT         —           Knowledge svc    R2→Vectorize (not Spine)\n```\n\n### The Hard Rules (Crystallized)\n\n```\n1. ALL non-MCP data → Loader → Normalizer → Spine D1. No exceptions.\n2. MCP as wrapper (3A) still goes through Loader → Normalizer. MCP is just transport.\n3. Native MCP speakers (3B) are READERS + GOVERNED PROPOSERS. Never Spine writers.\n4. NOTHING writes to Spine D1 without the pipeline. Pipeline is the sole writer.\n5. Native MCP clients DO NOT call connectors. They call Spine/Memory MCP tools.\n6. Non-MCP connectors NEVER call our MCP server. They go through their channel.\n7. Schema Hydration happens BEFORE Loader (validates entity types against config).\n```\n\n### What This Means for the ADK + MCP Gateway\n\n```\nMCP GATEWAY (mcp.integratewise.ai)\n  │\n  ├── READS (anyone with valid auth):\n  │     spine.entity.get    → D1\n  │     spine.entity.list   → D1\n  │     spine.entity.search → D1\n  │     signal.list         → D1\n  │     memory.search_org   → Vectorize\n  │     memory.read_conversational → D1\n  │\n  ├── GOVERNED WRITES (propose only):\n  │     memory.propose      → D1 proposals → Triage Bot\n  │     memory.write_conversational → D1 (auto, no governance)\n  │     proposal.approve    → governance gate\n  │     proposal.reject     → governance gate\n  │\n  └── INGEST (3A path — MCP as wrapper, still normalizes):\n        connector.push_raw  → Loader → Normalizer → Spine D1\n        (for tools that speak MCP but push raw source data)\n\nADK (stateless registry + cache):\n  \"Which service handles this tool call?\" → KV lookup → route\n  No memory. No state. No logs. KV-speed TTL.\n```\n\n### What Is NOT Needed (Removed)\n\n```\n✗ Supabase connectors table (Nango holds tokens)\n✗ token-refresh.ts direct Supabase reads (Nango handles refresh)\n✗ Direct OAuth in tenants service for new users (use Nango)\n✗ @supabase/supabase-js for connector auth (Nango replaces)\n```\n\n---\n\n## D6. The Publishable Asset — IW Continuity Bridge\n\n```\nWHAT WE CAN PUBLISH:\n  Combined Loader + Normalizer + Spine Cache as a standalone bridge.\n  Open or commercial — available for any user globally.\n\nWHAT IT DOES:\n  Any system → Continuity Bridge → Normalized Spine\n  Then: any MCP client (ChatGPT, Claude, Perplexity, custom agents)\n  can read from the Spine through the MCP protocol adapter.\n\nWHY IT MATTERS:\n  Right now: ChatGPT can call tools, but has no continuity.\n  With IW Bridge: ChatGPT reads from a continuously synchronized,\n  normalized context layer. It remembers. It has operational truth.\n\nTHIS IS THE WEDGE:\n  Not \"connect tools to MCP\" (commodity).\n  \"Connect any system ONCE. Every AI operates from the same normalized continuity layer.\"\n  That is much harder to copy.\n```\n\n---\n\n## D7. The Spine Abstraction Principle\n\n```\nTHE SPINE ABSTRACTION PRINCIPLE\n\nOnce a tool is connected to IntegrateWise:\n  - No AI agent ever reads from that tool directly again.\n  - The tool exists as a write-only data source to the Spine.\n  - Spine Cache is the query target. Always. For every agent.\n  - Agents read from Spine Cache in <10ms, rather than slow, rate-limited tool APIs.\n  - Agents do not hold credentials to tools. Credentials live in Nango.\n\nFor tools not yet connected:\n  - Spine returns \"connector_not_available\" with a connect_url.\n  - Agents cannot route around Spine or establish stateless direct channels.\n```\n\n### The Inbound/Outbound Inversion\n\n```\nInbound (Tool -> Spine Ingestion):\n  Tool Webhook/Sync -> Gateway -> Connector -> Loader -> Normalizer -> Spine D1\n\nOutbound (Agent -> Spine Consumption):\n  Agent -> MCP Server -> Gateway -> Spine Cache (D1/KV/Vectorize) -> Agent\n```\n\n---\n\n## D8. Three-Channel MCP Split\n\nTo prevent context pollution, the MCP interface exposes three distinct channels:\n\n1. **Memory MCP (Institutional Knowledge)**\n   - Target: Vectorize (pgvector)\n   - Scope: Read-only promoted/approved org memory and personal behavior rules.\n2. **Session MCP (Operational Context)**\n   - Target: D1 Edge tables + KV Hot Cache (Entity 360)\n   - Scope: Active session state, working entities, and current brief details.\n3. **Tool MCP (Execution & Actions)**\n   - Target: BFF Hono / Gateway Hops\n   - Scope: Propose memories, trigger syncs, dispatch playbooks.\n\n---\n\n## D9. Loader & Normalizer Stages\n\n### The 8-Stage Loader (Universal Ingest Pipeline)\n\n```\nS1 Analyzer   — Computes SHA-256 payload fingerprint and wraps in Ingestion Envelope.\nS2 Classifier — Detects data_kind (entity, activity, event, file) and checks PII sensitivity.\nS3 Filter     — Checks idempotency via fingerprint logs. Validates tenant schema.\nS4 Refiner    — Splits composite payloads, normalizes key names, resolves target domains.\nS5 Extractor  — Maps fields to canonical schema structure (CRM, Billing, Eng, etc.).\nS6 Validator  — Executes required field audits and data type checks (warning vs error).\nS7 Split Router— Computes write targets (Spine vs. R2 Context vs. Audit logs).\nS8 Writers    — Writes payload to target storage and enqueues Normalizer processing.\n```\n\n### The 6-Stage Normalizer (Truth & Context Linkage)\n\n```\nNA0 Schema Detector      — Prunes data fields to tenant's adaptive schema bounds.\nNA1 Canonical Transformer — Formats and transforms field traits.\nNA2 SSOT Binder          — Injects or resolves stable UUIDs for resolved records.\nNA3 Lineage Manager      — Records source tool provenance, sync times, and trace IDs.\nNA4 Relation Binder      — Maps related IDs from source keys to Spine UUIDs (e.g. contact.company_id -> account UUID).\nNA5 Spine Publisher      — Publishes structured entity to D1 Cache and context payload to Knowledge Queue.\n```\n\n---\n\n## D10. Edge-Case Lifecycles\n\n### 1. New Connection Post-Onboarding\n\nConnecting a new tool via the Nango Connect UI immediately triggers a delta sync pull (bypassing the 5-minute cron queue) to hydrate the new entity types and update the `tenant_spine_config` within the 12×11 matrix.\n\n### 2. Detailed Ingest Queue States (`CONNECTOR_STATUS` KV)\n\n- `not_connected`\n- `oauth_pending`\n- `oauth_complete` (Nango holds tokens, sync not started)\n- `syncing_initial` (Creamy initial load in progress)\n- `sync_complete` (Spine contains baseline data, dashboard ready)\n- `sync_error` (Identifies the failed loader/normalizer stage)\n- `syncing_delta` (Background poll active)\n\n### 3. Knowledge Ingestion Ordering\n\nIf context files (Drive, Slack messages) reference entities not yet synced to Spine, the linking is deferred to a background `entity-linker` job to prevent orphaned context records.\n\n### 4. Entity Eviction & Soft Deletes\n\nDeleted records in HubSpot/Salesforce are not hard-deleted from Spine. Instead, they are marked with a soft delete tombstone flag (`is_deleted = true`) to prevent the Twin from proposing operations on ghost entities.\n\n### 5. Reindex Reverse Verification\n\nThe reindex job verifies Vectorize embeddings against R2. If an embedding exists in Vectorize but the corresponding raw doc is missing from R2, it is flagged as `orphaned_vector` for manual review.\n\n### 6. Personal Memory Auto-Promotion Thresholds\n\nA behavioral pattern or context rule candidate is auto-promoted to personal memory when it occurs in **5 or more distinct sessions** within a rolling 30-day window, with a pattern detection confidence score **≥ 0.70**.\n\n### 7. Triage Bot Initial Load Scoring\n\nTo prevent raw data ingestion from flooding the approved `org_memory`, the initial load documents are scored dynamically by document category:\n\n- **Architecture Docs:** base confidence **0.90**\n- **Meeting Transcripts:** base confidence **0.70**\n- **Work Notes:** base confidence **0.75**\n\n### 8. Gateway vs. Governance Boundaries\n\n- **Gateway:** Auth, Zero Trust, rate limits, CORS, context packaging. (Enforcer)\n- **Governance (Triage Bot):** Proposal workflow, scoring, conflict detection, HITL approvals. (Decision Engine)\n\n---\n\n_No Hermes. No Claw. No n8n. No Python. No CouchDB. No Neon._\n_One Twin. Model-agnostic. One Spine. One protocol adapter (MCP). One loop that never breaks._\n_Real Twin and Digital Twin. Working together through shared context, memory, and governance._\n_Build the memory loop first. Everything else falls into place._\n_One document. Complete. Final._\n"}