{"slug":"architecture/final-e2e-system","title":"IntegrateWise Continuity Bridge — Final End-to-End System","section":"architecture","sectionLabel":"Architecture","status":"unclassified","type":"document","path":"architecture/final-e2e-system.mdx","bytes":62567,"description":null,"updated":null,"source":"integratewise/Integratewise-docs-wiki","content":"\n> **Status: SUPERSEDED ARCHITECTURE LINEAGE.** The old product name,\n> Descope-as-authority and conflicting storage/runtime claims are historical.\n> Current authority starts at\n> [`ARCHITECTURE_LOCK.md`](./ARCHITECTURE_LOCK.md).\n\n> **Canonical Reference:** [CANONICAL_PLATFORM_ARCHITECTURE.md](../architecture/CANONICAL_PLATFORM_ARCHITECTURE.md)  \n> _This document is downstream of the canonical architecture. Refer to the canonical source for current truth._\n\n**Version:** 1.0.0-FINAL  \n**Date:** 2026-07-02  \n**Status:** LOCKED — all §14 conflicts resolved, all P0 blockers defined with closure criteria  \n**Scope:** Multi-tenant continuity bridge, 26-service Cloudflare-native mesh, MCP-first ingress, governance-gated AI Twin, **100% swappable infrastructure layers**\n\n---\n\n## 1. The One-Liner\n\n> **One JWT. One SSE connection. One Bridge. The Bridge connects to everything else.**\n\nThe IntegrateWise Continuity Bridge is a multi-tenant continuity ecosystem that preserves identity, context, memory, governance, and execution across all consumers (humans, AI assistants, apps, tools) through one stable continuity contract. Consumers never hold provider credentials, never import internal topology, and never bypass the governance gate.\n\n**Doctrine:** _Truth you own. AI you rent. Approval in between._\n\n**Product Name:** IW Continuity Bridge (DECISION 23 retired — \"Platform\" is the operational continuity platform, \"Bridge\" is the product name, \"OS\" and \"tool\" are explicitly rejected).  \n**Category:** The Operational Continuity Platform\n\n---\n\n## 1.1 The Swappable Dimensions (The 7× Agnostic Moat)\n\nThe platform is **deliberately swappable at every infrastructure layer**. The only fixed surface is the **capability contract** (Identity, Discovery, Projections, Capabilities, Events). Everything underneath is managed by the **Integration Manager** and can be swapped without consumer code changes.\n\n| Dimension                    | Default                                                         | Swappable To                                                                                  | Managed By          |\n| ---------------------------- | --------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | ------------------- |\n| **Frontend**                 | `apps/workbench` (Vite + React + shadcn/ui, Cloudflare Pages)   | Next.js, Electron, Lovable, Replit, React Native, Browser Extension, iOS, Android             | Integration Manager |\n| **Auth**                     | Gateway-issued JWT + API Keys                                   | Clerk, Stack Auth, Descope, Auth0, Custom OAuth                                               | Integration Manager |\n| **Relational Store (Spine)** | PostgreSQL via **HyperDrive** (Cloudflare's connection pooling) | Any PostgreSQL (Neon, Supabase, AWS RDS, CockroachDB, PlanetScale), any SQL-compatible engine | Integration Manager |\n| **Cache / KV**               | Cloudflare KV                                                   | Redis, Memcached, Upstash, DynamoDB                                                           | Integration Manager |\n| **Queue**                    | Cloudflare Queues                                               | SQS, RabbitMQ, Kafka, BullMQ                                                                  | Integration Manager |\n| **AI / Model**               | gpt-5-mini via **OpenRouter**                                   | Claude, Grok, Gemini, Ollama, local LLM, any OpenAI-compatible endpoint                       | Integration Manager |\n| **Deployment**               | Cloudflare Workers                                              | Vercel, AWS Lambda, Fly.io, Kubernetes, self-hosted                                           | Integration Manager |\n\n**Key principle:** The Integration Manager is the **capability adapter** that sits between the capability contract and the provider fabric. It makes swappability real by translating the fixed capability contract into provider-specific calls. Consumers never see the provider.\n\n---\n\n## 1.2 The Fixed Surface (What Never Changes)\n\n| Layer                   | Fixed                                                                                       | Why                                                          |\n| ----------------------- | ------------------------------------------------------------------------------------------- | ------------------------------------------------------------ |\n| **Capability Contract** | Identity, Discovery, Projections, Capabilities, Events                                      | This is the Bridge — the public API that all consumers speak |\n| **Governance Gate**     | 0.70 / 0.85 confidence thresholds, HITL, audit                                              | Safety and trust are invariant                               |\n| **Tenant Isolation**    | `WHERE tenant_id = ?` on every query, 403 fail-loud                                         | Security is non-negotiable                                   |\n| **MCP Protocol**        | `mcp.integratewise.ai/v1/mcp` as the primary ingress                                        | AI-first is the product thesis                               |\n| **The Loop**            | Observe → Understand → Propose → Govern → Execute → Writeback → Remember → Organize → Learn | The operational lifecycle is the product                     |\n\n---\n\n## 2. The Four Layers (Conceptual Law)\n\nThese layers are **conceptual** — they describe trust boundaries, not deployment units. The physical 0–16 topology is in §8.\n\n```\nConsumers  ↔  Continuity Bridge  ↔  Continuity Kernel  ↔  Provider Fabric\n```\n\n| Layer                 | What It Is                                                                                                                             | What Consumers See                                                     |\n| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |\n| **Consumers**         | Humans, AI assistants (ChatGPT, Claude, Perplexity, Cursor), apps, tools                                                               | A thin surface: one MCP connection, one web workbench, or one SDK call |\n| **Continuity Bridge** | The public interface / the moat: identity, auth, discovery, projections, capabilities, governance entry, events                        | Identity, Discovery, Projections, Capabilities, Events                 |\n| **Continuity Kernel** | The internal context substrate: Adaptive Spine, Memory, Knowledge, Context, Capability Engine, Governance, Workflow, Continuity Engine | Nothing — consumers never import internal topology                     |\n| **Provider Fabric**   | Replaceable external execution: SaaS providers, databases, APIs, queues, agents, runtimes                                              | Nothing — the Fabric is entirely behind the Kernel                     |\n\n**Invariant:** Consumers never import internal service topology. They see only Identity, Discovery, Projections, Capabilities, and Events.\n\n---\n\n## 3. The Universal Loop (Every Action Flows Through This)\n\n```\nObserve → Understand → Propose → Govern → Execute → Writeback → Evidence Return → Remember → Organize → Learn\n```\n\nEvery consumer interaction resolves through five public concepts:\n\n1. **Identity** — who are you? (Gateway JWT, `x-tenant-id`, `x-correlation-id`)\n2. **Discovery** — what exists / what can I do? (`GET /api/v1/discovery`)\n3. **Projections** — persona-specific views (Desk, Entity360, Executive, Twin, etc.)\n4. **Capabilities** — named business actions (Analyze Account, Draft Email, …)\n5. **Events** — Signal, Proposal, Approval, Outcome, Stream\n\n---\n\n## 4. The Two Planes (North / South)\n\n```\nConsumers → [API Gateway] → Spine (context) → [Integration Router] → Provider tools\n             (north / ingress)                (south / egress)\n```\n\n| Plane     | Direction                          | Role                                                                                         | Physical Service                                      |\n| --------- | ---------------------------------- | -------------------------------------------------------------------------------------------- | ----------------------------------------------------- |\n| **North** | Ingress — consumers → platform     | AuthN/Z, tenant routing, rate-limit, capability routing, Discovery                           | `gateway` (single Worker)                             |\n| **South** | Egress — platform → external tools | Adapter routing (Nango / MCP / Native), credential wall, health, Entity360 context injection | Integration Router (folded into §5 Continuity Bridge) |\n\n**Rule:** Neither plane talks to the other except **through the Spine**. The Gateway and Integration Router are not alternatives — they are the only two doors, one in, one out.\n\n---\n\n## 5. MCP Pool Architecture (Bidirectional, First-Class)\n\nMCP is not a single connection. It is a **multiplexed, bidirectional, tenant-scoped pool** with two distinct trust models.\n\n### 5.1 Inbound MCP Pool (North Plane)\n\n**Endpoint:** `mcp.integratewise.ai/v1/mcp` (SSE/stdio)  \n**Role:** AI assistants (ChatGPT, Claude, Perplexity, Cursor) connect **to us** to read scoped Spine/Memory context.  \n**Primary ingress:** This is the **primary** front door — AI assistants are the lead ecosystem category, ahead of traditional SaaS/webhook connectors.\n\n```\nInbound MCP Pool\n├── mcp.integratewise.ai/v1/mcp (Cloudflare Worker — single deploy, multi-tenant)\n│   ├── POST /sessions          — SSE transport negotiation, session lifecycle\n│   ├── POST /tools             — Discovery-driven tool catalog (filtered per tenant)\n│   ├── POST /invoke            — Capability execution (read-only default)\n│   ├── GET /health             — Session + tenant health (SSE stream)\n│   └── DELETE /sessions/:id    — Cleanup\n│\n├── Per-tenant scoping\n│   ├── JWT validation (gateway-issued, NOT provider-issued)\n│   ├── x-tenant-id extracted from JWT claim `tenant_id` (never from client payload)\n│   ├── Tool catalog assembled from Discovery (§9) — tenant sees only their capabilities\n│   └── Audit: `via: mcp` in `spine_audit_log` for every call\n│\n└── Security gates (P0 — must be closed before production)\n    ├── 1. JWT bypass on /tools, /invoke, /mcp, /sessions → 403 (fail-loud)\n    ├── 2. Cross-tenant session reuse → 403 (fail-loud, not 404)\n    ├── 3. Read-only default: `scope: read` in JWT; write requires `scope: write` + governance approval\n    ├── 4. Tool catalog filtered by Discovery: tenant cannot discover another tenant's tools\n    └── 5. Every invocation logged to `spine_audit_log` with full request/response hash\n```\n\n**Consumer Config (Template):**\n\n```json\n{\n  \"mcpServers\": {\n    \"integratewise\": {\n      \"type\": \"sse\",\n      \"url\": \"https://mcp.integratewise.ai/v1/mcp\",\n      \"headers\": {\n        \"Authorization\": \"Bearer ${input:integratewise_jwt}\"\n      },\n      \"description\": \"IntegrateWise Continuity Bridge — Spine, Memory, Knowledge, Signals, Proposals, Governance\"\n    }\n  }\n}\n```\n\n**Key rule:** There is **one** client-side MCP entry. Not 21. Not 5. One.\n\n### 5.2 Outbound MCP Pool (South Plane)\n\n**Location:** Inside the Integration Router (part of §5 Continuity Bridge)  \n**Role:** We connect **to provider MCP servers** (Salesforce MCP, Slack MCP, GitHub MCP, etc.) using MCP as the transport.\n\n```\nOutbound MCP Pool (Integration Router)\n├── Provider MCP Adapters\n│   ├── Salesforce MCP Server\n│   ├── Slack MCP Server\n│   ├── GitHub MCP Server\n│   ├── Notion MCP Server\n│   ├── Figma MCP Server\n│   └── Custom MCP Servers (tenant-defined)\n│\n├── Per-tenant context injection\n│   ├── Entity360 fetched from Spine before every outbound call\n│   ├── Context window optimization (Context Assembly, §8.7)\n│   └── Result normalized back to Spine schema via Normalizer\n│\n├── Adapter selection logic\n│   ├── Nango (OAuth-mature SaaS): Salesforce, HubSpot, Stripe\n│   ├── MCP (AI-native / tool-calling): GitHub, Linear, custom\n│   └── Native (direct REST): legacy / custom APIs\n│\n└── Security gates\n    ├── Credential wall: per-tenant API keys, never shared across tenants\n    ├── Tool whitelist per tenant: no arbitrary tool calling\n    ├── Health checks + circuit breaker per provider\n    └── Audit: `outbound_mcp_calls` log with `tenant_id`, `provider`, `tool`, `latency`\n```\n\n**Rule:** The Integration Router is the **only** service that touches external APIs. Frontends, agents, and AI assistants never call provider tools directly.\n\n### 5.3 Why \"Pool\" and Not \"Server/Client\"\n\n| Property           | Inbound MCP Pool                                                 | Outbound MCP Pool                                                     |\n| ------------------ | ---------------------------------------------------------------- | --------------------------------------------------------------------- |\n| Multiplexed        | Many concurrent sessions per tenant                              | Many concurrent provider connections per tenant                       |\n| Tenant-scoped      | Each session bound to JWT `tenant_id`                            | Each connection bound to tenant's credential wall                     |\n| Replaceable        | Provider servers can be swapped without changing Bridge contract | Adapter can be swapped (Nango ↔ MCP ↔ Native) without consumer change |\n| Read/write posture | Read-only default; write via governance                          | Write via governance; read via Entity360 injection                    |\n\n---\n\n## 6. The 26 Services (Physical Topology)\n\nAll services run on every deployment and serve **all tenants**. Customer-Zero is a _tenant class_, not a separate service. All 26 are wired into the Gateway as Cloudflare service bindings.\n\n### Tier 0 — Ingress & Routing\n\n| Service           | Worker                  | Purpose                                                             | Service Binding   |\n| ----------------- | ----------------------- | ------------------------------------------------------------------- | ----------------- |\n| `gateway`         | `integratewise-gateway` | Single entry point; JWT validation; tenant routing; rate-limit      | N/A (entry point) |\n| `webhook-ingress` | `iw-webhook-ingress`    | Receives external webhooks (Salesforce, HubSpot, Stripe, GitHub, …) | `WEBHOOK_INGRESS` |\n\n> **Ingress priority:** AI assistants (inbound MCP) are the **primary** ingress class. Traditional SaaS/webhook connectors are secondary/complementary. Both feed the same normalization pipeline.\n\n### Tier 1 — Tenant & Sync\n\n| Service          | Worker              | Purpose                                                                                                             | Service Binding  |\n| ---------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------- | ---------------- |\n| `tenants`        | `iw-tenants`        | Multi-tenant context resolution, tenant CRUD, SSO, plan limits                                                      | `TENANTS`        |\n| `connector-sync` | `iw-connector-sync` | Orchestrates connector sync (fetch → Normalizer → Triage)                                                           | `CONNECTOR_SYNC` |\n| `normalizer`     | `iw-normalizer`     | 8-stage NA0–NA5 pipeline: schema detect → canonical transform → SSOC bind → lineage → relation bind → Spine publish | `NORMALIZER`     |\n\n### Tier 2 — Projection & Rendering\n\n| Service             | Worker                 | Purpose                                                   | Service Binding     |\n| ------------------- | ---------------------- | --------------------------------------------------------- | ------------------- |\n| `pipeline`          | `iw-pipeline`          | **Only writer to the Spine**; product/eng domain renderer | `PIPELINE`          |\n| `twin-orchestrator` | `iw-twin-orchestrator` | Persistent per-user AI reasoning engine (Durable Object)  | `TWIN_ORCHESTRATOR` |\n| `l2`                | `iw-l2`                | Department × industry overlay projections                 | `L2`                |\n| `intelligence`      | `iw-intelligence`      | Analytics & insights renderer + signal generation         | `INTELLIGENCE`      |\n| `knowledge`         | `iw-knowledge`         | Knowledge base, docs, semantic search                     | `KNOWLEDGE`         |\n| `govern`            | `iw-govern`            | Governance rules engine (approval gates, HITL thresholds) | `GOVERN`            |\n| `store`             | `iw-store`             | Persistence for projections (accounts, deals, tasks)      | `STORE`             |\n| `act`               | `iw-act`               | Action execution / write-back to providers                | `ACT`               |\n\n### Tier 3 — Capability Runtime & Orchestration\n\n| Service            | Worker             | Purpose                                                       | Service Binding    |\n| ------------------ | ------------------ | ------------------------------------------------------------- | ------------------ |\n| `hermes`           | `iw-hermes`        | Message queue + execution engine (Durable Object)             | `HERMES`           |\n| `triage`           | `iw-triage`        | Confidence routing + active-memory decay (runs inside Hermes) | `TRIAGE`           |\n| `workflow`         | `iw-workflow`      | Durable orchestration (pause, retry, saga)                    | `WORKFLOW`         |\n| `iw-agent-runtime` | `iw-agent-runtime` | MCP-compliant AI agent execution (gpt-5-mini default)         | `IW_AGENT_RUNTIME` |\n| `mcp-connector`    | `iw-mcp-connector` | MCP bridge: external agents → scoped Spine/Memory access      | `MCP_CONNECTOR`    |\n\n### Tier 4 — Supporting\n\n| Service          | Worker              | Purpose                                                      | Service Binding  |\n| ---------------- | ------------------- | ------------------------------------------------------------ | ---------------- |\n| `agent-registry` | `iw-agent-registry` | Catalog of available agents/integrations                     | `AGENT_REGISTRY` |\n| `billing`        | `iw-billing`        | Usage tracking + plan enforcement                            | `BILLING`        |\n| `admin`          | `iw-admin`          | Platform admin (tenant mgmt, overrides)                      | `ADMIN`          |\n| `loader`         | `iw-loader`         | Cold-start pre-loader; Nango webhook handler                 | `LOADER`         |\n| `folder-watcher` | `iw-folder-watcher` | Durable Object filesystem watcher                            | `FOLDER_WATCHER` |\n| `continuity`     | `iw-continuity`     | Memory consolidation + decay (the continuity substrate)      | `CONTINUITY`     |\n| `telemetry`      | `iw-telemetry`      | Traces, metrics, observability                               | `TELEMETRY`      |\n| `think`          | `iw-think`          | LLM reasoning orchestration (separate from iw-agent-runtime) | `THINK`          |\n| `connector`      | `iw-connector`      | OAuth callback handler (Nango)                               | `CONNECTOR`      |\n\n---\n\n## 7. The 0–16 Stack (Physical Implementation Topology)\n\nThis is the **physical** view. The 4-layer law in §2 is the **conceptual** view. Both hold — 0–16 is the implementation map, 4-layer is the trust model.\n\n| #   | Layer                       | Physical Services                                                  | Data / Storage                                                   |\n| --- | --------------------------- | ------------------------------------------------------------------ | ---------------------------------------------------------------- |\n| 0   | **Tenant Lifecycle**        | `tenants`, `loader`, `admin`                                       | D1 `tenants` table, `tenant_spine_config`                        |\n| 1   | **Customer Ecosystem**      | `connector`, `connector-sync`, `agent-registry`                    | Nango tokens (vault), `connectors` table                         |\n| 2   | **Surface Layer**           | `apps/web` (Vite), `apps/mcp-server`                               | Cloudflare Pages, R2 assets                                      |\n| 3   | **Gateway Layer**           | `gateway`                                                          | N/A — pure routing                                               |\n| 4   | **Identity & Organization** | `tenants` (SSO, RBAC)                                              | D1 `rbac_roles`, `rbac_permissions`                              |\n| 5   | **Continuity Bridge**       | `connector-sync`, `normalizer`, `mcp-connector`, `webhook-ingress` | D1 `sync_jobs`, `normalizer_state`, KV Discovery cache           |\n| 6   | **Adaptive Spine**          | `pipeline`                                                         | D1 (entities, relationships, SSOC), `spine_audit_log`            |\n| 7   | **Context Assembly**        | `intelligence`, `knowledge`                                        | Vectorize (embeddings), AI Search (semantic), KV context cache   |\n| 8   | **Shared Memory**           | `continuity`, `triage`                                             | D1 `memory` (active/staging/archived), KV memory decay           |\n| 9   | **Capability Engine**       | `iw-agent-runtime`, `think`                                        | OpenRouter API (gpt-5-mini default), KV model config             |\n| 10  | **Governance Layer**        | `govern`                                                           | D1 `governance_audit_log`, `action_proposals`                    |\n| 11  | **Capability Runtime**      | `hermes`, `workflow`, `act`, `mcp-connector`                       | Durable Objects (stateful), Queues (ACT_QUEUE, PIPELINE_QUEUE)   |\n| 12  | **Projection Registry**     | `l2`, `store`                                                      | D1 `projections`, `projection_registry`                          |\n| 13  | **Registry Layer**          | `agent-registry`, `intelligence` (catalog)                         | D1 `capability_registry`, `endpoint_registry`, KV registry cache |\n| 14  | **Continuity Engine**       | `continuity`, `twin-orchestrator`                                  | D1 `continuity_graph`, KV session handoffs                       |\n| 15  | **Data & Infrastructure**   | `telemetry`, `folder-watcher`                                      | D1 `audit_logs`, R2 (telemetry blobs), Workers Analytics         |\n| 16  | **Endpoint Registry**       | `gateway` (serves), `intelligence` (updates)                       | KV + D1 `endpoint_registry` (living API contract)                |\n\n**Cross-cutting:** Security (WAF, DDoS, TLS, CF Secrets, Zero Trust), Observability (logs/metrics/traces/alerts/audit), Reliability (idempotency, retries, DLQ, backpressure), Compliance (audit & lineage, retention, field-level security, encryption, tenant isolation).\n\n---\n\n## 8. End-to-End: First Connection Flow\n\n### 8.1 New Tenant Onboarding (First Auth)\n\n1. **Identity provider** (Google / GitHub / email) → trust root established.\n2. **Gateway** issues JWT with `tenant_id` claim.\n3. **Schema-generation AI** (gpt-5-mini) hydrates tenant on first auth: entity types, relationships, RBAC roles (owner/tam/account_success), billing tier.\n4. **Tenant init:** D1 partition, `tenant_spine_config` row, RBAC rows, billing record, memory tables created.\n5. **Target:** signup → workspace < 5 min; first tool connected < 10 min; normalizer p99 < 2s.\n\n### 8.2 Connecting the First Tool (Salesforce Example)\n\n| Step | Actor               | Action                                                                                                                            | Service                              | Data Store                                        |\n| ---- | ------------------- | --------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------ | ------------------------------------------------- |\n| 1    | User                | Clicks \"Connect Salesforce\"                                                                                                       | `apps/web`                           | —                                                 |\n| 2    | Frontend            | `POST /api/v1/connector/nango/session` + `x-tenant-id`                                                                            | `gateway` → `connector`              | —                                                 |\n| 3    | Connector           | Creates Nango session token (`connectionId = tenant_id`)                                                                          | `connector`                          | Nango vault                                       |\n| 4    | Nango               | Opens Connect UI; user authorizes; tokens captured                                                                                | Nango (external)                     | —                                                 |\n| 5    | Loader              | Receives `auth.created` webhook; verifies signature                                                                               | `loader`                             | D1 `tenant_spine_config.connected_connectors`     |\n| 6    | Loader              | Triggers immediate \"creamy\" (full) sync; no 6h cron wait                                                                          | `loader` → `connector-sync`          | `CONNECTOR_SYNC_QUEUE`                            |\n| 7    | Connector-sync      | Resolves Nango token; calls provider adapter; returns raw records                                                                 | `connector-sync`                     | Nango vault (read)                                |\n| 8    | Normalizer          | 8-stage NA0–NA5: schema detect → canonical transform (traits) → SSOC bind (stable UUID) → lineage → relation bind → Spine publish | `normalizer`                         | D1 `normalizer_state`                             |\n| 9    | Pipeline            | **Only Spine writer:** `INSERT` entities + relationships; writes audit log                                                        | `pipeline`                           | D1 `entities`, `relationships`, `spine_audit_log` |\n| 10   | Intelligence / Twin | Twin reads Spine (`WHERE tenant_id = ?`), reasons with gpt-5-mini, emits proposal                                                 | `twin-orchestrator`, `think`         | OpenRouter API                                    |\n| 11   | Governance          | Confidence score evaluated: ≥0.85 auto; 0.70–0.85 → My Desk; <0.70 discard                                                        | `govern`                             | D1 `action_proposals`, `governance_audit_log`     |\n| 12   | My Desk             | Owner reviews proposal; approves/rejects                                                                                          | `apps/web`                           | D1 `action_proposals` (status update)             |\n| 13   | Act                 | Approved action routed to `act` → Integration Router → Salesforce                                                                 | `act`                                | `ACT_QUEUE`                                       |\n| 14   | Writeback           | Outcome written to Spine; audit emitted; memory compounds                                                                         | `pipeline` (writeback), `continuity` | D1 `entities`, `spine_audit_log`, `memory`        |\n\n---\n\n## 9. The Discovery Contract (Consumer Surface)\n\n**Endpoint:** `GET /api/v1/discovery`  \n**Cache:** Client-side 5 min  \n**Purpose:** How humans and AI agents learn \"what exists / what can I do\" without hardcoding topology.\n\n**Response includes:**\n\n- `identity` — user, tenant, org, role\n- `workspace` — tenant config, connected connectors, plan limits\n- `projections` — available lenses (Sales, CS, Finance, Executive, Architecture, Operations, Personal, Developer)\n- `capabilities` — named actions filtered by tier/role/level (e.g., `analyze_account`, `draft_email`, `get_department_health`)\n- `features` — gated by plan (free/pro/enterprise)\n- `navigation` — role-based menu structure\n- `personalization` — user preferences, recent context\n- `limits` — rate limits, storage quotas, model quotas\n\n**AI agents read the same Discovery response as humans.** This is the contract that makes cross-component communication effective and drift-proof.\n\n---\n\n## 10. Governance & Approval Gate (The 0.70/0.85 Law)\n\n### 10.1 Governance Triage (Execution Gate)\n\n| Confidence  | Action            | Destination            | Audit                                  |\n| ----------- | ----------------- | ---------------------- | -------------------------------------- |\n| ≥ 0.85      | Auto-approve      | `ACT_QUEUE`            | `governance_audit_log` (auto-approved) |\n| 0.70 – 0.85 | Queued for review | My Desk (owner review) | `governance_audit_log` (pending)       |\n| < 0.70      | Discard           | —                      | `governance_audit_log` (discarded)     |\n\n- Even Customer-Zero cannot bypass hard approval-expiry gates.\n- **Customer-Zero posture:** Hermes native auto-execute (for internal operations only).\n- **External tenant posture:** Async Handoff contract only (`/api/v1/handoff/outcome`, validated `x-approval-token`).\n\n### 10.2 Memory Triage (Knowledge Gate)\n\n| Confidence  | Action       | Destination    | Where                                    |\n| ----------- | ------------ | -------------- | ---------------------------------------- |\n| ≥ 0.85      | Auto-promote | Active memory  | `continuity` (TriageBot inside `hermes`) |\n| 0.70 – 0.85 | Staging      | Staging memory | `continuity`                             |\n| < 0.70      | Discard      | —              | `continuity`                             |\n\n- **Active memory decay:** If not reinforced, decays and archives after ~30 days of no access.\n- **Memory scopes (FINAL):** `Personal` (human), `Work` (task/project), `Organization` (org-wide), `AI` (twin/audit). Audit is cross-cutting Compliance, not a memory scope.\n\n---\n\n## 11. Memory Lifecycle (Continuity Engine)\n\nThe Continuity Engine runs 7 stages:\n\n```\nMemory Intake → Classification → Validation → Promotion → Memory Store → Continuity Graph → Memory Decay\n```\n\n- **Intake:** Raw signals from Pipeline, Act, Twin, user actions.\n- **Classification:** TriageBot scores confidence (0–1.0).\n- **Validation:** Deduplication against SSOC (stable UUIDs); lineage verification.\n- **Promotion:** ≥0.85 → active; 0.70–0.85 → staging; <0.70 → discard.\n- **Memory Store:** Active / staging / archived tiers in D1 + KV cache.\n- **Continuity Graph:** Relationship traversal — who/what/when/where connected.\n- **Decay:** Time-decay + access-decay; archive after ~30 days; reinforcement resets clock.\n\n**Every agent turn starts with more context than the last.** This is compounding memory.\n\n---\n\n## 12. AI / Twin / Reasoning Layer\n\n### 12.1 Model Provider (The \"AI You Rent\")\n\n- **Default:** gpt-5-mini via **OpenRouter** (aggregator)\n- **Swappable:** OpenAI, Anthropic, Google, Grok — config change, not migration\n- **Binding:** Consumers call capabilities (`twin/propose`, `insights`, `predictions`), never model names\n- **Per-tenant/per-capability model selection:** Cheap model for triage, strong model for high-stakes proposals, provider failover\n\n**Resolution of §14.8:** DECISION 30 (Grok) is **superseded** by §20.2 FINAL. Twin default = gpt-5-mini via OpenRouter. Grok is available as a config option, not the default.\n\n### 12.2 Agent Services\n\n| Service             | Role                                                         |\n| ------------------- | ------------------------------------------------------------ |\n| `twin-orchestrator` | Persistent per-user Twin — reasoning engine (Durable Object) |\n| `iw-agent-runtime`  | MCP-compliant AI agent execution                             |\n| `think`             | LLM reasoning orchestration (SDK abstraction layer)          |\n| `mcp-connector`     | Inbound MCP bridge — external agents → scoped Spine/Memory   |\n| `agent-registry`    | Catalog of available agents / integrations                   |\n\n### 12.3 Agent Tools (Capabilities)\n\n- `analyze_metric`\n- `get_metric_data`\n- `get_recommendations`\n- `generate_forecast`\n- `compare_metrics`\n- `create_action_plan`\n- `get_department_health`\n\n### 12.4 A2A (Agent-to-Agent)\n\n**Status:** Month-6 roadmap. Today: agents coordinate through **shared Spine context** via Twin — the Spine is the shared blackboard. No peer-to-peer calls. Every agent reads/writes the same Spine, gated by `tenant_id` and JWT scope.\n\n---\n\n## 13. Multi-Tenancy & Isolation (Hard Rules)\n\n1. **Every query carries `WHERE tenant_id = ?`.** Cross-tenant access = security violation → 403 (fail-loud, not 404).\n2. **Nango credentials isolated per tenant:** `connectionId = tenant_id`, encrypted in vault. No shared tokens.\n3. **Org is the hard isolation boundary.** Sharing happens _within_ an org across departments/lenses.\n4. **Gateway enforces `x-tenant-id` extraction from JWT.** Never from client payload, never from URL parameter, never from header injection.\n5. **Service bindings carry `tenant_id` implicitly.** Every internal RPC includes the caller's tenant context.\n\n---\n\n## 14. Audit & Observability (Immutable, Fail-Loud)\n\n| Table                  | What It Logs                                    | Failure Behavior               |\n| ---------------------- | ----------------------------------------------- | ------------------------------ |\n| `audit_logs`           | Generic events                                  | Write failure → halt operation |\n| `governance_audit_log` | Approval decisions (approve/reject/discard)     | Write failure → halt operation |\n| `spine_audit_log`      | Entity changes, MCP access, reads, writes       | Write failure → halt sync      |\n| `twin_audit_events`    | Reasoning trace, model calls, confidence scores | Write failure → halt proposal  |\n| `outbound_mcp_calls`   | Provider calls, latency, errors                 | Write failure → circuit break  |\n\n**Rule:** Audit write failure stops the sync. No silent drops. Telemetry service (`telemetry`) collects traces/metrics from all workers.\n\n---\n\n## 15. Public Contract Surface (What Consumers Call)\n\n| Endpoint                                                                                  | Purpose                          | Auth                        |\n| ----------------------------------------------------------------------------------------- | -------------------------------- | --------------------------- |\n| `GET /api/v1/discovery`                                                                   | Capability handshake             | Gateway JWT                 |\n| `POST /api/v1/handoff/outcome`                                                            | Async external execution results | `x-approval-token`          |\n| `POST /api/v1/connector/nango/session`                                                    | Initiate OAuth connection        | Gateway JWT + `x-tenant-id` |\n| `GET /api/v1/{workspace,connector,intelligence,knowledge,cognitive,pipeline,admin,mcp}/*` | Tiered capability routing        | Gateway JWT                 |\n| `mcp.integratewise.ai/v1/mcp`                                                             | MCP SSE transport                | Bearer JWT                  |\n\n**SDK:** `packages/api-client` (Gateway SDK, complete) + `packages/sdk` (consumer facade).\n\n---\n\n## 16. Frontend Surfaces (Projection Platform)\n\nThe live repo ships **one full UI** — not many apps:\n\n- **User Workbench** — role-based L1 domain workbenches\n- **Twin Workbench** — AI reasoning interface, proposal review\n- **Collaboration Overlay** — ambient memory, governance, continuity signals\n- **My Desk** — approval interface (0.70–0.85 proposals)\n- **Real-time metrics dashboard**\n\n**Projections (FINAL lens taxonomy):** Sales, CS, Finance, Executive, Architecture, Operations, Personal, Developer.\n\n**Frontend host:** `apps/web` (Vite, React, shadcn/ui). Deployed to Cloudflare Pages. Not Next.js/Vercel. Not Replit. The UI is an agnostic dimension (§21.2), but the template default is Vite on Cloudflare Pages.\n\n---\n\n## 17. Deployment Topology (100% Cloudflare)\n\n**Runtime:** Workers (all 26 services), Durable Objects (stateful: Twin, Hermes, Folder Watcher), D1 (relational), KV (cache, registry), R2 (blobs, telemetry), Vectorize (embeddings), AI Search (semantic), Queues (PIPELINE_QUEUE, ACT_QUEUE, CONNECTOR_SYNC_QUEUE), Workflows (durable orchestration), Pages (frontend).\n\n**No Supabase.** No Vercel. No AWS backend. No Neon PostgreSQL. DECISION 22 is complete in the template.\n\n**CI/CD gap:** No GitHub Actions gate today. Required: unified pipeline, pre-deploy test/typecheck, semantic versioning, rollback. Target: `wrangler deploy` through a GitHub Actions gate with pnpm workspace caching.\n\n**Folder Monitor bridge:** macOS chokidar watcher → Cloudflare Folder Watcher DO → `spine_audit_log` + AI Search. Powers the Agent Continuity Protocol (session handoffs → triage → org memory).\n\n---\n\n## 18. Registry Layer (§13 — New Structure)\n\nEverything the ecosystem can do is **cataloged**:\n\n- **Connector Registry** — Nango, MCP, Native adapters\n- **MCP Registry** — Inbound/outbound MCP servers, health status\n- **Tool Registry** — Provider tool schemas, versions, deprecation\n- **Capability Registry** — Named business actions (Analyze Account, Draft Email, …)\n- **Skill Registry** — Agent skills (analyze_metric, …)\n- **Agent Registry** — Available agents, runtime status\n- **Provider Registry** — External providers (Salesforce, Slack, …)\n- **Endpoint Registry** — Living API contract: path/method, service owner, auth type, status, surface access, change summary (cached in KV + D1)\n- **Schema Registry** — Entity schemas, versions, migration history\n- **Policy Registry** — Governance rules, approval thresholds, HITL policies\n\n**Discovery reads from these registries.** Agents, frontends, docs, and tests all read the same Endpoint Registry to stay drift-proof.\n\n---\n\n## 19. Context Assembly (Intelligence Fabric — §7)\n\nThe RAG layer feeding the Twin:\n\n1. **Entity resolution** — SSOC lookup, stable UUID binding\n2. **Memory retrieval** — active memory query, recency + relevance scoring\n3. **Relationship traversal** — Continuity Graph walk (entity → relation → entity)\n4. **Tool retrieval** — Capability Registry lookup for available actions\n5. **Capability discovery** — What can this tenant do right now?\n6. **Prompt assembly** — Structured prompt with Entity360 + memory + tools\n7. **Context-window optimization** — Truncation/prioritization to fit model limits\n8. **Evidence retrieval** — Audit trail, lineage, confidence scoring for past decisions\n\n---\n\n## 20. Security Posture (P0 & P1)\n\n### P0 — Tenant Safety (Must Close Before Production)\n\n| #   | Vulnerability                                              | Fix                                                           | Owner                     |\n| --- | ---------------------------------------------------------- | ------------------------------------------------------------- | ------------------------- |\n| 1   | Cross-tenant data leak (intelligence)                      | `WHERE tenant_id = ?` on every query; 403 fail-loud           | `intelligence`            |\n| 2   | Tenant-id spoofing (unstripped `x-tenant-id`)              | Extract from JWT only; reject client-provided                 | `gateway`                 |\n| 3   | Tenant middleware no-op                                    | Enforce `gateway` → all services binding includes `tenant_id` | `gateway`                 |\n| 4   | HITL Durable Object using `idFromName(\"global\")`           | Use `idFromName(tenant_id + user_id)`                         | `govern`                  |\n| 5   | Invitation cross-tenant scan                               | Add `WHERE tenant_id = ?` to invitation lookup                | `tenants`                 |\n| 6   | Hardcoded RSA key / DB creds / MCP key / WebUI password    | Move to Cloudflare Secrets; rotate                            | `admin`                   |\n| 7   | `.env` committed                                           | Remove from git; add to `.gitignore`; scan history            | `admin`                   |\n| 8   | SQL injection in continuity/knowledge shims                | Use Drizzle ORM parameterized queries                         | `continuity`, `knowledge` |\n| 9   | MCP-JWT bypass on `/tools`, `/invoke`, `/mcp`, `/sessions` | Require `Authorization: Bearer <jwt>`; verify signature       | `mcp-connector`           |\n| 10  | Auth root thrashing (Clerk/Stack/Descope)                  | **Freeze on API Keys + JWT**; remove all other auth imports   | `gateway`                 |\n\n### P1 — Hardening (Post-Production)\n\n| #   | Vulnerability                   | Fix                                              | Owner             |\n| --- | ------------------------------- | ------------------------------------------------ | ----------------- |\n| 1   | Billing still on Supabase       | Migrate to D1 + Workers billing                  | `billing`         |\n| 2   | Gateway rate-limiter fails open | Add Cloudflare Rate Limiting; fail-closed        | `gateway`         |\n| 3   | CORS reflects arbitrary origins | Whitelist `app.integratewise.ai` + Pages domains | `gateway`         |\n| 4   | MCP JWT bypass                  | Close P0 #9 first                                | `mcp-connector`   |\n| 5   | Unsigned-webhook auto-approve   | Verify Nango webhook signatures; reject unsigned | `loader`          |\n| 6   | Webhook replay/timing leaks     | Add idempotency keys; deduplicate                | `webhook-ingress` |\n| 7   | Weak password hashing           | Argon2id via Cloudflare Workers                  | `tenants`         |\n| 8   | Remove `@supabase/supabase-js`  | DECISION 22 completion                           | All services      |\n\n---\n\n## 21. The Ownership Split (Context vs. Mechanism)\n\n| What                                                                   | Who Owns It                                  | Access                                           |\n| ---------------------------------------------------------------------- | -------------------------------------------- | ------------------------------------------------ |\n| **Context** — data/entities in the Spine                               | **Customer organization** (data sovereignty) | Admin views/manages org's Spine via capabilities |\n| **Mechanism** — Spine schema, Schema AI, Normalizer, Continuity Engine | **IntegrateWise (proprietary IP)**           | Not shared, not exposed to tenant                |\n\nThis split is possible because consumers reach context **through capabilities**, never through the schema. One boundary delivers sovereignty, IP protection, and swappability simultaneously.\n\n---\n\n## 22. Consumer Contract Summary (The \"One Connection\" Rule)\n\n**What a consumer (human, AI assistant, app) needs to connect:**\n\n1. **One JWT** — issued by the Gateway, bound to a tenant.\n2. **One SSE endpoint** — `mcp.integratewise.ai/v1/mcp` (for AI assistants) or `https://api.integratewise.ai` (for apps).\n3. **One Discovery call** — `GET /api/v1/discovery` to learn what exists and what they can do.\n\n**What they do NOT need:**\n\n- Provider credentials (Salesforce, GitHub, AWS, …) — held by the Integration Router.\n- Multiple MCP connections — the Bridge routes to 20+ providers internally.\n- Knowledge of internal topology — 26 services, D1 schema, DO IDs are all hidden.\n- Auth provider accounts — no Clerk, no Stack Auth, no Descope. API Keys + JWT only.\n\n---\n\n## 23. Resolution of All §14 Conflicts\n\n| Conflict                                          | v1.0 FINAL Decision                                                                                                                                   | Status     |\n| ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- |\n| §14.1 Storage/runtime (4 backends)                | **100% Cloudflare** — D1, DO, KV, R2, Vectorize, AI Search, Queues. No Supabase/Vercel/AWS/Neon.                                                      | **Locked** |\n| §14.2 Auth model (Clerk vs JWT)                   | **API Keys (external) + JWT (internal)**, service bindings internal, same code path. Clerk/Stack/Descope **removed**.                                 | **Locked** |\n| §14.3 Frontend host                               | `apps/web` (Vite + React + shadcn/ui) on Cloudflare Pages. Not Next.js. Not Replit.                                                                   | **Locked** |\n| §14.4 Product framing (\"not a platform\")          | DECISION 23 **superseded**. Product = \"IW Continuity Bridge\"; Category = \"The Operational Continuity Platform\".                                       | **Locked** |\n| §14.5 Layer model (4-layer vs 10-layer vs L0-L3)  | **4-layer = conceptual law** (§2); **0-16 = physical topology** (§8); 10-layer and L0-L3 **retired**.                                                 | **Locked** |\n| §14.6 Capability-first APIs                       | Named endpoints: `entity/:type/:id`, `memory/query`, `twin/propose`, `signals`, `insights`, `predictions`, `handoff`, `stream` (WS), `mcp`, `health`. | **Locked** |\n| §14.7 Domains                                     | `integratewise.ai` (canonical). `integrate-voice.ai` (GTM landing) is a redirect to main.                                                             | **Locked** |\n| §14.8 Twin model provider                         | **gpt-5-mini via OpenRouter** (default). Grok available as config option. DECISION 30 superseded.                                                     | **Locked** |\n| §18.2 \"Platform\" branding vs DECISION 23          | Platform = category; Bridge = product name. Both coexist.                                                                                             | **Locked** |\n| §18.3 Integration Manager vs existing services    | Folded into §5 Continuity Bridge (Connector Pool + MCP Pool + Discovery Catalog + Normalization + Schema AI). Not a separate 4th service.             | **Locked** |\n| §18.4 One-auth vs per-tool Nango                  | **Both, at different layers:** \"Connect Once\" at surface; Nango is the Credential Wall underneath.                                                    | **Locked** |\n| §18.5 Lens naming                                 | **8 lenses (FINAL):** Sales, CS, Finance, Executive, Architecture, Operations, Personal, Developer.                                                   | **Locked** |\n| §18.6 ADK vs Twin naming                          | **ADK is canonical** — lives in §11 Capability Runtime alongside Twin. No clash.                                                                      | **Locked** |\n| §20.3 \"Platform\" in title vs DECISION 23          | DECISION 23 retired. Title = \"Platform Architecture\".                                                                                                 | **Locked** |\n| §20.3 Numbered (0-16) vs un-numbered (names)      | **Names for doctrine, numbers for implementation topology** — both canonical, different purposes.                                                     | **Locked** |\n| §20.3 Lens taxonomy mismatch (mindmap vs diagram) | **8 lenses above** adopted.                                                                                                                           | **Locked** |\n| §20.3 Memory scopes (3 sets)                      | **FINAL:** Personal, Work, Organization, AI. Audit = cross-cutting Compliance.                                                                        | **Locked** |\n| §21.3 Twin reframed as Operational Participant    | Adopted: \"always working, never idle, accountable like an employee.\"                                                                                  | **Locked** |\n| §22.4 L1-L4 definitions                           | **Pinned:** L1 = projection/read, L2 = intelligence/insight, L3 = operation/execution, L4 = full continuity/autonomous participation.                 | **Locked** |\n\n---\n\n## 24. The Mermaid Wiring Diagram (Canonical)\n\n```mermaid\nflowchart TB\n  subgraph CONS[\"Consumers — thin surfaces\"]\n    subgraph UI[\"Live repo — ONE full UI\"]\n      UWB[\"User Workbench\"]\n      TWB[\"Twin Workbench\"]\n      OVL[\"Collaboration Overlay\"]\n      SUB[\"Memory — Governance — Continuity<br/>surfaced subtly as ambient layers\"]\n    end\n    AIA[\"AI Assistants<br/>Claude — ChatGPT — Perplexity — Cursor\"]\n    EXT[\"External Agents\"]\n  end\n\n  subgraph ING[\"Ingress — NORTH plane\"]\n    GW[\"API Gateway<br/>JWT + API keys — tenant routing — rate-limit\"]\n    WH[\"webhook-ingress\"]\n    MCP[\"Inbound MCP Pool<br/>mcp.integratewise.ai/v1/mcp<br/>read-only default — scoped — audited\"]\n  end\n\n  REG[\"Common Discovery + Capability Registry<br/>one shared contract everyone speaks<br/>capabilities gated by tier/role/level\"]\n\n  subgraph BRIDGE[\"Continuity Bridge\"]\n    CP[\"Connector Pool<br/>Nango / OAuth / Token Vault\"]\n    MCP_OUT[\"Outbound MCP Pool<br/>Salesforce MCP — Slack MCP — GitHub MCP\"]\n    NORM[\"Normalizer<br/>NA0-NA5\"]\n    PIPE[\"Pipeline<br/>ONLY Spine writer\"]\n    IR[\"Integration Router<br/>SOUTH plane — egress<br/>adapter selection — context injection\"]\n  end\n\n  subgraph KERNEL[\"Continuity Kernel\"]\n    SPINE[\"Adaptive Spine<br/>SSOC — context\"]\n    CTX[\"Context Assembly<br/>Intelligence Fabric<br/>Entity360 + timeline + RAG\"]\n    MEM[\"Shared Memory<br/>Personal — Work — Organization — AI\"]\n    TWIN[\"ADK / Twin<br/>reasoning — gpt-5-mini via OpenRouter\"]\n    GOV[\"Govern<br/>approval gate<br/>0.70 / 0.85\"]\n    ACT[\"Act<br/>execution — writeback\"]\n  end\n\n  subgraph PROV[\"Provider Fabric\"]\n    SF[\"Salesforce\"]\n    SL[\"Slack\"]\n    GH[\"GitHub\"]\n    NOTION[\"Notion\"]\n    FIGMA[\"Figma\"]\n    AWS[\"AWS\"]\n  end\n\n  AUDIT[\"Audit + Telemetry<br/>spine_audit_log — governance_audit_log — twin_audit_events\"]\n\n  %% A — consumer ingress north plane\n  UWB -->|capability call + JWT| GW\n  TWB -->|capability call + JWT| GW\n  AIA -->|inbound MCP SSE + Bearer JWT| MCP\n  EXT -->|inbound MCP SSE + Bearer JWT| MCP\n  MCP -->|validated + tenant-scoped| GW\n  GW <-->|discover what exists / can do| REG\n  AIA -.->|discover| REG\n  EXT -.->|discover| REG\n  CP -.->|register connectors + capabilities| REG\n  MCP_OUT -.->|register MCP tools + capabilities| REG\n  GW -->|read via capability| SPINE\n\n  %% B — provider ingest to context\n  SF -->|webhook / sync| WH\n  SL -->|webhook / sync| WH\n  GH -->|webhook / sync| WH\n  WH --> CP\n  CP --> NORM\n  NORM --> PIPE\n  PIPE -->|only writer| SPINE\n\n  %% C — reason govern act writeback\n  SPINE --> CTX\n  CTX --> TWIN\n  TWIN -->|proposal + confidence| GOV\n  GOV -->|approved ≥0.85| ACT\n  GOV -.->|0.70-0.85 My Desk review| UWB\n  ACT -->|outbound Nango / MCP / Native| IR\n  IR --> MCP_OUT\n  MCP_OUT --> SF\n  MCP_OUT --> SL\n  MCP_OUT --> GH\n  MCP_OUT --> NOTION\n  MCP_OUT --> FIGMA\n  MCP_OUT --> AWS\n  ACT -->|writeback| SPINE\n  SPINE --> MEM\n  MEM --> CTX\n\n  %% cross-cutting audit\n  SPINE -.-> AUDIT\n  GOV -.-> AUDIT\n  ACT -.-> AUDIT\n  MCP -.-> AUDIT\n  MCP_OUT -.-> AUDIT\n```\n\n### How to Read the Diagram\n\n- **North plane (ingress):** All consumers — UI, AI assistants (inbound MCP), external agents — enter through the **Gateway** or **Inbound MCP Pool**, authenticated, scoped to `tenant_id`, and served the **common Discovery + Capability Registry**.\n- **One full UI:** User Workbench + Twin Workbench + Collaboration Overlay, with Memory, Governance, Continuity as ambient layers.\n- **Ingest path:** Providers push → Connector Pool → Normalizer → Pipeline. **Pipeline is the only Spine writer.**\n- **Reason → Govern → Act:** Spine → Context Assembly → Twin → Govern (confidence gate) → Act → Integration Router (Outbound MCP Pool) → Providers. Entity360 context injected on outbound.\n- **Writeback + Memory:** Every outcome writes back to Spine; Memory compounds and feeds Context Assembly on the next turn.\n- **Two invariants:** (1) Spine is the **only** place context is written; (2) Gateway and Integration Router are the **only** two doors — one in, one out — with Spine between them.\n\n---\n\n## 25. GTM & Positioning (From Strategy Session)\n\n### Category & Positioning\n\n- **Category claim:** \"The Operational Continuity Platform — the infrastructure layer that preserves context, memory, and governance across every tool, every person, and every AI.\"\n- **Competitive frame:** high structure × high intelligence × human-first workbench. \"They connect apps; we connect context.\"\n- **Anti-positioning:** Not \"AI-powered platform,\" not \"no-code automation,\" not \"replace your tools,\" not \"chat with your data.\" Instead: human workbench + assistive AI + governed context.\n\n### Tagline Hierarchy\n\n| Level      | Line                                                                 |\n| ---------- | -------------------------------------------------------------------- |\n| Category   | The Operational Continuity Platform                                  |\n| Product    | IW Continuity Bridge                                                 |\n| Promise    | Nothing important is forgotten                                       |\n| Action     | The last auth for endless continuity / One click to total continuity |\n| Proof      | One workbench. Full continuity. Zero context loss.                   |\n| Philosophy | Human workbench. Assistive AI. Governed context.                     |\n\n### Customer-Zero GTM (Acme Corp)\n\n- **Two-app kill shot:** Salesforce + Slack, read-only, approval-required, 90-day retention.\n- **Win condition:** One workspace auth → CS Workbench shows cross-system account context in < 60s → Twin proposes ≥1 insight/day → VP CS answers \"what's our risk?\" without opening Salesforce or Slack → adding a 3rd app is an \"enable\" toggle, not a project.\n- **Distribution:** Through AI assistant marketplaces (ChatGPT GPT Store, Claude connectors, Perplexity apps) — we list as an MCP app, users discover inside the assistant they already use.\n- **Do NOT build for CZ:** marketplace UI, partner portal, public connector directory, per-app OAuth flows, frontend→app direct calls.\n\n---\n\n## 26. Template Repo Structure (Publishable)\n\n```\nintegratewise-continuity-bridge/\n├── apps/\n│   ├── gateway/              # Hono + JWT + tenant routing + service bindings map\n│   │   ├── src/\n│   │   │   ├── index.ts      # Entry point; route map to 26 bindings\n│   │   │   ├── auth.ts       # JWT verify + tenant_id extraction\n│   │   │   ├── discovery.ts  # Discovery assembly from registries\n│   │   │   └── bindings.ts   # Service binding type definitions\n│   │   ├── wrangler.toml\n│   │   └── package.json\n│   │\n│   ├── workbench/            # Vite + React + shadcn/ui\n│   │   ├── src/\n│   │   │   ├── main.tsx\n│   │   │   ├── components/   # shadcn components\n│   │   │   ├── hooks/        # useWorkbenchAI, useAIInsights, useAIAgent\n│   │   │   ├── projections/  # 8 lens implementations\n│   │   │   └── desk/         # My Desk approval interface\n│   │   ├── wrangler.toml     # Cloudflare Pages deploy\n│   │   └── package.json\n│   │\n│   └── mcp-server/           # Inbound MCP Pool (single Worker, multi-tenant)\n│       ├── src/\n│       │   ├── index.ts      # SSE transport setup\n│       │   ├── sessions.ts   # Session lifecycle (KV-backed)\n│       │   ├── tools.ts      # Discovery → tool catalog assembly\n│       │   ├── invoke.ts     # Capability routing via service binding\n│       │   └── guard.ts      # JWT verify + tenant_id + read-only gate\n│       ├── wrangler.toml\n│       └── package.json\n│\n├── packages/\n│   ├── spine-schema/         # Drizzle ORM + D1 driver + tenant_id helpers\n│   │   ├── src/\n│   │   │   ├── schema/       # All D1 tables (entities, relationships, memory, audit...)\n│   │   │   ├── helpers.ts    # withTenant(query, tenantId)\n│   │   │   └── migrations/   # D1 migration files\n│   │   └── package.json\n│   │\n│   ├── normalizer/           # NA0–NA5 pipeline skeleton\n│   │   ├── src/\n│   │   │   ├── stages/\n│   │   │   │   ├── na0-detect.ts\n│   │   │   │   ├── na1-transform.ts\n│   │   │   │   ├── na2-ssoc.ts\n│   │   │   │   ├── na3-lineage.ts\n│   │   │   │   ├── na4-relations.ts\n│   │   │   │   └── na5-publish.ts\n│   │   │   └── index.ts\n│   │   └── package.json\n│   │\n│   ├── sdk/                  # @integratewise/sdk — consumer facade\n│   │   ├── src/\n│   │   │   ├── client.ts     # Gateway SDK\n│   │   │   ├── discovery.ts  # Discovery response types\n│   │   │   ├── capabilities.ts # Capability call wrappers\n│   │   │   └── mcp.ts        # MCP client helpers\n│   │   └── package.json\n│   │\n│   ├── mcp-types/            # Shared MCP schemas (inbound + outbound)\n│   │   ├── src/\n│   │   │   ├── inbound.ts    # Session, Tool, Invoke, Health types\n│   │   │   ├── outbound.ts   # ProviderAdapter, ContextInjection types\n│   │   │   └── guards.ts     # JWT claims, TenantScope, ReadOnlyGate\n│   │   └── package.json\n│   │\n│   └── twin-types/           # Shared Twin/ADK types\n│       ├── src/\n│       │   ├── proposal.ts   # Proposal + ConfidenceScore\n│       │   ├── governance.ts # ApprovalState, GovernanceEvent\n│       │   └── memory.ts     # MemoryScope, MemoryTier, DecayRule\n│       └── package.json\n│\n├── services/                 # 26 service stubs as Cloudflare Worker templates\n│   ├── tier-0-ingress/       # gateway, webhook-ingress\n│   ├── tier-1-tenant/        # tenants, connector-sync, normalizer\n│   ├── tier-2-projection/    # pipeline, twin-orchestrator, l2, intelligence, knowledge, govern, store, act\n│   ├── tier-3-runtime/       # hermes, triage, workflow, iw-agent-runtime, mcp-connector\n│   └── tier-4-support/       # agent-registry, billing, admin, loader, folder-watcher, continuity, telemetry, think, connector\n│\n├── infra/\n│   ├── wrangler.toml          # Root config; service bindings for all 26\n│   ├── d1-migrations/         # Tenant isolation schema (run once per env)\n│   ├── kv-namespaces/         # Discovery cache, Endpoint Registry, Session store\n│   └── queues/                # PIPELINE_QUEUE, ACT_QUEUE, CONNECTOR_SYNC_QUEUE definitions\n│\n├── scripts/\n│   ├── mcpflare-aggregator.mjs   # Local MCP aggregator (dev only)\n│   └── integratewise-mcp-bridge.mjs # stdio bridge for local AI assistants\n│\n├── docs/\n│   ├── FINAL_E2E_SYSTEM.md   # This document\n│   ├── ARCHITECTURE.md         # 4-layer conceptual law\n│   ├── SECURITY.md             # P0/P1 hardening checklist\n│   └── API.md                  # Endpoint Registry documentation\n│\n├── README.md\n├── package.json               # pnpm workspace root\n├── pnpm-workspace.yaml\n├── tsconfig.json\n└── .github/\n    └── workflows/\n        └── deploy.yml          # CI/CD: typecheck → test → wrangler deploy\n```\n\n---\n\n## 27. Closing Checklist (Before Publish)\n\n- [ ] Close P0 #1–10 (§20)\n- [ ] Remove all `@supabase/supabase-js` imports (DECISION 22)\n- [ ] Remove all Clerk/Stack Auth/Descope imports (§20.2)\n- [ ] Lock MCP-JWT on all inbound endpoints (`/tools`, `/invoke`, `/mcp`, `/sessions`)\n- [ ] Implement `withTenant()` helper on all D1 queries (packages/spine-schema)\n- [ ] Hard `WHERE tenant_id = ?` in every service query\n- [ ] Fix HITL DO to use `idFromName(tenant_id + user_id)`\n- [ ] Move all secrets to Cloudflare Secrets (no `.env` in repo)\n- [ ] Verify `spine_audit_log` write failure halts sync (fail-loud)\n- [ ] Confirm gpt-5-mini via OpenRouter as default Twin model\n- [ ] Verify 8-lens taxonomy in Discovery response\n- [ ] Confirm 4 memory scopes: Personal, Work, Organization, AI\n- [ ] Test one-connection MCP config (read-only default, write via governance)\n- [ ] Test outbound MCP pool with Entity360 injection\n- [ ] CI/CD: GitHub Actions → typecheck → test → wrangler deploy\n- [ ] Documentation: `README.md` + `ARCHITECTURE.md` + `SECURITY.md` + `API.md`\n- [ ] Template repository enabled in GitHub settings\n\n---\n\n**END OF DOCUMENT**\n\n_This is the canonical end-to-end system specification for the IntegrateWise Continuity Bridge v1.0.0-FINAL. All prior documents, diagrams, and decisions are superseded by this version where they conflict. Source-of-context conflicts are flagged in §24 and resolved in §20.2._\n"}