{"slug":"business/locked-v1","title":"IntegrateWise Continuity Bridge","section":"business","sectionLabel":"Business","status":"superseded","type":"document","path":"business/locked-v1.mdx","bytes":44588,"description":null,"updated":null,"source":"integratewise/Integratewise-docs-wiki","content":"\n## Canonical Architecture Specification v1.0.0-FINAL\n\n**Status:** SUPERSEDED — historical architecture lineage\n**Date:** 2026-07-02  \n**Version:** 1.0.0-FINAL  \n**Current replacement:** `ARCHITECTURE_LOCK.md`,\n`IMPLEMENTATION_CONTRACT_v1.1.md` and\n`CONSOLIDATED_PRODUCT_PLATFORM_CONTRACT_v1.2.md`.\n\n> This document no longer supersedes later architecture. Its product naming,\n> storage and UI-layer claims are retained for genealogy only.\n\n---\n\n## 1. The Doctrine\n\n> **Context you own. AI you rent. Approval in between.**\n\nThe IntegrateWise Continuity Bridge is an OODA Engine for Business Continuity. It preserves organizational context, memory, governance, and execution across all tools, humans, and AI agents through one stable continuity contract.\n\n**Product Name:** IW Continuity Bridge  \n**Category:** The Operational Continuity Platform  \n**Anti-categories:** Not an OS, not a tool, not a platform-first product. \"Knowledge workspace\" is a descriptor, not the name.\n\n### 1.1 The Core Promise\n\n> **One JWT. One SSE connection. One Bridge. The Bridge connects to everything else.**\n\nA consumer (human, AI assistant, app, tool) needs exactly one credential to reach Salesforce, GitHub, Slack, Notion, AWS, and twenty other tools. The Bridge holds all provider credentials. The consumer holds none. The consumer never imports internal topology, never bypasses the governance gate, and never writes to a provider without approval.\n\n### 1.2 The 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---\n\n## 2. The OODA Engine (The Universal Loop)\n\nEvery entity, tool, user, and AI agent in the system operates on the same four-phase decision cycle. This is the core mental model of the platform.\n\n```\n┌─────────────────────────────────────────────────────────────────┐\n│  OODA — Observe, Orient, Decide, Act                            │\n│                                                                 │\n│  OBSERVE ──► Read signals from tools, users, webhooks, files  │\n│  ORIENT  ──► Assemble Entity360 + Memory + Knowledge            │\n│  DECIDE  ──► Propose action, score confidence, govern            │\n│  ACT     ──► Execute approved action, writeback, compound       │\n│                                                                 │\n│  └──────► Each cycle makes the next faster (compounding) ────┘ │\n└─────────────────────────────────────────────────────────────────┘\n```\n\n### 2.1 Observe\n\nIngest raw signals from the perimeter: webhooks from Salesforce, Slack messages, file changes from the folder watcher, user clicks in the workbench, AI assistant queries via MCP.\n\n- **Services:** `webhook-ingress`, `connector-sync`, `folder-watcher`, `mcp-connector` (inbound)\n- **Output:** Raw payload → `PIPELINE_QUEUE` → `normalizer`\n- **Speed:** Milliseconds (event-driven) to minutes (scheduled polling)\n\n### 2.2 Orient\n\nTransform raw signals into unified context. The 8-stage normalizer (NA0–NA5) runs inside a single pipeline stage. Entity360 assembles data from all connected tools into one canonical view. Memory retrieval surfaces relevant historical context from active, staging, and archived tiers.\n\n- **Services:** `normalizer`, `intelligence` (Context Assembly), `knowledge` (RAG), `continuity` (memory retrieval)\n- **Data:** `spine_entities` (D1), `entity:{id}:360` (KV cache), Vectorize (semantic embeddings)\n- **Speed:** < 2s for normalizer p99, < 10ms for Entity360 cache hit\n\n### 2.3 Decide\n\nThe Twin (per-user AI reasoning engine) evaluates context and proposes an action. The governance gate scores confidence. The decision is immutable and auditable.\n\n| Confidence  | Action           | Destination                        | Human Touch                |\n| ----------- | ---------------- | ---------------------------------- | -------------------------- |\n| ≥ 0.85      | Auto-approve     | `ACT_QUEUE`                        | None                       |\n| 0.70 – 0.85 | Queue for review | My Desk                            | Approve / Modify / Dismiss |\n| < 0.70      | Discard          | `spine_audit_log` (discard reason) | None                       |\n\n- **Services:** `twin-orchestrator` (OODA engine), `govern` (confidence gate), `think` (LLM reasoning orchestration)\n- **Model:** Default `gpt-5-mini` via OpenRouter (aggregator). Swappable to Claude, Grok, Gemini, Ollama by config change.\n- **Speed:** 1–2s for simple proposals, 5–10s for complex analysis\n\n### 2.4 Act\n\nExecute approved actions through the Integration Router (South Plane). Write outcomes back to the Spine. Update memory so the next OODA cycle starts with more context than the last.\n\n- **Services:** `act` (execution), `workflow` (durable orchestration), `hermes` (message queue)\n- **Output:** External API call (Salesforce, Slack, etc.) + Spine writeback + memory promotion\n- **Speed:** 500ms–2s depending on external API latency\n\n---\n\n## 3. The Four Layers (Conceptual Law)\n\nThese layers describe trust boundaries, not deployment units. The physical implementation is the 0–16 stack 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                                                               | One MCP connection, one JWT, one web workbench, or one SDK call |\n| **Continuity Bridge** | The public interface and 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. 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## 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** | Consumers → Platform | AuthN/Z, tenant routing, rate-limit, capability routing, Discovery, inbound MCP              | `gateway` (single Worker)                                |\n| **South** | Platform → Providers | Adapter routing (Nango / MCP / Native), credential wall, health, Entity360 context injection | Integration Router (inside `act` + `connector` services) |\n\n**Rule:** Neither plane talks to the other except through the Spine. The Gateway and Integration Router are the only two doors — one in, one out.\n\n---\n\n## 5. MCP Pool Architecture (Bidirectional, First-Class)\n\nMCP is a multiplexed, bidirectional, tenant-scoped pool. It is not a single connection. It is not \"server/client.\" It is a pool.\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. Traditional SaaS webhooks are secondary.\n\n**Security gates (P0 — must close before production):**\n\n1. JWT required on `/tools`, `/invoke`, `/mcp`, `/sessions` — 403 on bypass\n2. `tenant_id` extracted from JWT claim, never from client payload\n3. Cross-tenant session reuse → 403 (fail-loud, not 404)\n4. Read-only default. Write requires `scope: write` + governance approval.\n5. Tool catalog filtered by Discovery — tenant cannot discover another tenant's tools\n6. Every invocation logged to `spine_audit_log` with `via: mcp`\n\n**Consumer config (the ONLY client-side entry):**\n\n```json\n{\n  \"mcpServers\": {\n    \"integratewise\": {\n      \"type\": \"sse\",\n      \"url\": \"https://mcp.integratewise.ai/v1/mcp\",\n      \"headers\": { \"Authorization\": \"Bearer ${input:integratewise_jwt}\" }\n    }\n  }\n}\n```\n\n**Key rule:** One entry. Not 21. Not 5. One.\n\n### 5.2 Outbound MCP Pool (South Plane)\n\nInside the Integration Router. We connect to provider MCP servers (Salesforce MCP, Slack MCP, GitHub MCP) using MCP as the transport. Entity360 context is injected before every outbound call.\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 Name             | Purpose                                                          | Binding           |\n| ----------------- | ----------------------- | ---------------------------------------------------------------- | ----------------- |\n| `gateway`         | `integratewise-gateway` | Single entry point; JWT validation; tenant routing; rate-limit   | N/A               |\n| `webhook-ingress` | `iw-webhook-ingress`    | Receives external webhooks (Salesforce, HubSpot, Stripe, GitHub) | `WEBHOOK_INGRESS` |\n\n### Tier 1 — Tenant & Sync\n\n| Service          | Worker Name         | Purpose                                                                                                                     | Binding          |\n| ---------------- | ------------------- | --------------------------------------------------------------------------------------------------------------------------- | ---------------- |\n| `tenants`        | `iw-tenants`        | Multi-tenant context resolution, tenant CRUD, RBAC, plan limits                                                             | `TENANTS`        |\n| `connector-sync` | `iw-connector-sync` | Orchestrates connector sync (fetch → Normalizer → Triage)                                                                   | `CONNECTOR_SYNC` |\n| `normalizer`     | `iw-normalizer`     | 8-stage pipeline: parse → trait-detect → resolve-type → resolve-entity → link-rels → enrich-map → validate → emit-canonical | `NORMALIZER`     |\n| `loader`         | `iw-loader`         | Cold-start pre-loader; Nango webhook handler; triggers immediate \"creamy\" sync                                              | `LOADER`         |\n| `connector`      | `iw-connector`      | OAuth callback handler (Nango)                                                                                              | `CONNECTOR`      |\n\n### Tier 2 — Projection & Rendering\n\n| Service             | Worker Name            | Purpose                                                       | Binding             |\n| ------------------- | ---------------------- | ------------------------------------------------------------- | ------------------- |\n| `pipeline`          | `iw-pipeline`          | **Only writer to the Spine**; commits to D1; writes audit log | `PIPELINE`          |\n| `twin-orchestrator` | `iw-twin-orchestrator` | Persistent per-user OODA 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 (RAG)                   | `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| `spine-v2`          | `iw-spine-v2`          | Spine normalization & graph services                          | `SPINE_V2`          |\n\n### Tier 3 — Capability Runtime & Orchestration\n\n| Service            | Worker Name        | Purpose                                                       | 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                              | `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 Name         | Purpose                                                        | 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 management; overrides                   | `ADMIN`          |\n| `folder-watcher` | `iw-folder-watcher` | Durable Object filesystem watcher (macOS chokidar → DO)        | `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\n---\n\n## 7. The 0–16 Stack (Physical Implementation Topology)\n\nThe 4-layer law is conceptual (trust boundaries). The 0–16 stack is physical (implementation). Both hold simultaneously.\n\n| #   | Layer                       | Physical Services                                                  | Data / Storage                                          |\n| --- | --------------------------- | ------------------------------------------------------------------ | ------------------------------------------------------- |\n| 0   | **Tenant Lifecycle**        | `tenants`, `loader`, `admin`                                       | D1 `tenants`, `tenant_spine_config`                     |\n| 1   | **Customer Ecosystem**      | `connector`, `connector-sync`, `agent-registry`                    | Nango vault, `connectors` table                         |\n| 2   | **Surface Layer**           | `apps/web`, `apps/mcp-server`                                      | Cloudflare Pages, R2 assets                             |\n| 3   | **Gateway Layer**           | `gateway`                                                          | N/A — pure routing                                      |\n| 4   | **Identity & Organization** | `tenants` (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`, `spine_audit_log`       |\n| 7   | **Context Assembly**        | `intelligence`, `knowledge`                                        | Vectorize, AI Search, KV context cache                  |\n| 8   | **Shared Memory**           | `continuity`, `triage`                                             | D1 `memory` (active/staging/archived), KV decay         |\n| 9   | **Capability Engine**       | `iw-agent-runtime`, `think`                                        | OpenRouter API, 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, Queues (`ACT_QUEUE`, `PIPELINE_QUEUE`) |\n| 12  | **Projection Registry**     | `l2`, `store`                                                      | D1 `projections`, `projection_registry`                 |\n| 13  | **Registry Layer**          | `agent-registry`, `intelligence`                                   | D1 `capability_registry`, `endpoint_registry`, KV 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, 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, encryption, tenant isolation).\n\n---\n\n## 8. The Discovery Contract (Consumer Surface)\n\n**Endpoint:** `GET /api/v1/discovery`  \n**Cache:** Client-side 5 minutes  \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\nAI 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## 9. Governance & Approval Gate (The 0.70/0.85 Law)\n\nTwo triage gates run on the same confidence thresholds:\n\n### 9.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\nEven 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### 9.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\nActive memory decays if not reinforced and archives after ~30 days of no access. Triage is continuous, not one-shot.\n\n### 9.3 Memory Scopes (FINAL — 4 Scopes)\n\n| Scope                  | Who                  | Access                                            |\n| ---------------------- | -------------------- | ------------------------------------------------- |\n| `Personal` (`human`)   | Individual user      | User sees their own data                          |\n| `Work` (`work`)        | Task/project context | Team sees shared task data                        |\n| `Organization` (`org`) | Org-wide             | Admin manages org Spine via capabilities          |\n| `AI` (`twin`)          | Twin/agent reasoning | Agent sees its own traces and compounding context |\n\nAudit is cross-cutting Compliance, not a memory scope.\n\n---\n\n## 10. 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\nEvery agent turn starts with more context than the last. This is compounding memory.\n\n---\n\n## 11. AI / Twin / Reasoning Layer\n\n### 11.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 DECISION 30 (Grok):** Superseded. Twin default = `gpt-5-mini` via OpenRouter. Grok available as config option only.\n\n### 11.2 Agent Services\n\n| Service             | Role                                                                |\n| ------------------- | ------------------------------------------------------------------- |\n| `twin-orchestrator` | Persistent per-user OODA engine — 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### 11.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### 11.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## 12. 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## 13. 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## 14. 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## 15. Frontend Surfaces (Projection Platform)\n\nThe live repo ships one full UI — not many apps:\n\n- **User Workbench** — role-based L1 domain workbenches (8 lenses)\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. Not Vercel. Not Replit. The UI is an agnostic dimension, but the template default is Vite on Cloudflare Pages.\n\n---\n\n## 16. Deployment Topology (100% Cloudflare)\n\n**Runtime:** Workers (all 26 services), Durable Objects (stateful: Twin, Hermes, Workflow, Folder Watcher), D1 (relational + cache), 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 as the canonical relational store.** Supabase is the current adapter, wrapped behind `packages/lib/db-gate.ts`. D1 is the operational/cache layer. HyperDrive is the future path for PostgreSQL connection pooling. The relational store is swappable by design.\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## 17. Registry Layer (§13 — The Discovery Backbone)\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\nDiscovery reads from these registries. Agents, frontends, docs, and tests all read the same Endpoint Registry to stay drift-proof.\n\n---\n\n## 18. 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## 19. 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               | `WHERE tenant_id = ?` on every query; 403 fail-loud          | ALL services              |\n| 2   | Tenant-id spoofing                   | Extract from JWT claim only; reject client-provided          | `gateway`                 |\n| 3   | Tenant middleware no-op              | Enforce service bindings carry `tenant_id` implicitly        | `gateway`                 |\n| 4   | HITL DO 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 secrets                    | Move to Cloudflare Secrets; rotate                           | `admin`                   |\n| 7   | `.env` committed                     | Remove from git; add `.gitignore`; scan history              | `admin`                   |\n| 8   | SQL injection in shims               | Use Drizzle ORM parameterized queries                        | `continuity`, `knowledge` |\n| 9   | MCP-JWT bypass                       | Require `Authorization: Bearer <jwt>` on all MCP endpoints   | `mcp-connector`           |\n| 10  | Auth root thrashing                  | Freeze on API Keys + JWT; remove Clerk/Stack/Descope 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## 20. 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## 21. Consumer Contract Summary (The \"One Connection\" Rule)\n\nWhat a consumer 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\nWhat 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## 22. Resolution of All Conflicts (§14)\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 as canonical. Supabase is current adapter, wrapped behind `db-gate`. | **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** (§3); **0-16 = physical topology** (§7); 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                     | **8 lenses above** adopted.                                                                                                                                          | **Locked** |\n| §20.3 Memory scopes (3 sets)                     | **FINAL 4:** 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## 23. GTM & Positioning\n\n### 23.1 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### 23.2 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## 24. Closing Checklist (Before Publish)\n\n- [ ] Close P0 #1–10 (§19)\n- [ ] Remove all `@supabase/supabase-js` imports (DECISION 22 completion)\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## 25. The One Invariant\n\n> Identity gates the door. Discovery advertises the capabilities. Integration Manager is the only hand that touches outside tools. Spine is the only place context is written. Govern sits between reasoning and execution. Memory is scoped and compounds. Agents and tools coordinate through the Spine, never directly. Every hop carries `tenant_id`.\n\n---\n\n**END OF DOCUMENT**\n\n_IntegrateWise Continuity Bridge — Canonical Architecture Specification v1.0.0-FINAL. All prior documents, diagrams, and decisions are superseded by this version where they conflict._\n"}