{"slug":"business/locked-v1.0.1","title":"IntegrateWise Continuity Bridge — Canonical Architecture Specification v1.0.1-FINAL","section":"business","sectionLabel":"Business","status":"unclassified","type":"document","path":"business/locked-v1.0.1.mdx","bytes":34666,"description":null,"updated":null,"source":"integratewise/Integratewise-docs-wiki","content":"\n> **Status: SUPERSEDED ARCHITECTURE LINEAGE.** This file is not a current lock.\n> Its product name, service removal, storage and runtime decisions are retained\n> for genealogy only. Current authority is\n> [`ARCHITECTURE_LOCK.md`](./ARCHITECTURE_LOCK.md).\n\n**Original Status:** LOCKED — Integration Manager service removed; adapter pattern folded into `act` + `connector` services. Native builds and deployments are faster without an extra abstraction layer.\n**Date:** 2026-07-02  \n**Version:** 1.0.1-FINAL  \n**Supersedes:** v1.0.0-FINAL where it conflicts. All §14 conflicts remain locked.\n\n---\n\n## The Revision\n\nThe Integration Manager is **not a separate service**. It is a **pattern** implemented within the services that actually touch external providers. The 7× agnostic moat is achieved through adapter modules, not a separate orchestrator.\n\n**Why:** Native builds and deployments work much faster. Adding an extra service hop (act → Integration Manager → provider) adds latency, increases blast radius, and complicates deployment. The adapter pattern inside `act` achieves the same swappability with zero extra infrastructure.\n\n---\n\n## 1. The Doctrine (Unchanged)\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**Core Promise:** One JWT. One SSE connection. One Bridge. The Bridge connects to everything else.\n\n---\n\n## 2. The OODA Engine (Unchanged)\n\nEvery entity, tool, user, and AI agent operates on the same four-phase decision cycle:\n\n```\nOBSERVE ──► ORIENT ──► DECIDE ──► ACT ──► (memory compounds) ──► OBSERVE...\n```\n\n| Phase       | What                                                                 | Services                                                                                                      | Speed                               |\n| ----------- | -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | ----------------------------------- |\n| **Observe** | Ingest signals from webhooks, sync polls, user actions, file changes | `webhook-ingress`, `connector-sync`, `folder-watcher`, `mcp-connector` (inbound)                              | ms (event) to min (poll)            |\n| **Orient**  | Assemble Entity360 + Memory + Knowledge into context                 | `normalizer` (8-stage), `intelligence` (Context Assembly), `knowledge` (RAG), `continuity` (memory retrieval) | <2s normalizer p99, <10ms cache hit |\n| **Decide**  | Twin reasons, proposes action, governance scores confidence          | `twin-orchestrator` (OODA engine), `govern` (confidence gate), `think` (LLM orchestration)                    | 1-2s simple, 5-10s complex          |\n| **Act**     | Execute approved action, writeback to Spine, update memory           | `act` (execution + provider adapters), `workflow` (durable orchestration), `hermes` (message queue)           | 500ms-2s (external API)             |\n\n---\n\n## 3. The Four Layers (Conceptual Law — Unchanged)\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 — Revised)\n\n```\nConsumers → [API Gateway] → Spine (context) → [Act + Connector Services] → 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 modules inside `act` and `connector` services** — Nango OAuth, MCP outbound, Native REST, credential fetch from Secrets/KV, Entity360 injection | `act` (execution + outbound adapters), `connector` (OAuth callbacks), `connector-sync` (sync orchestration) |\n\n**Rule:** Neither plane talks to the other except through the Spine. The Gateway and the `act` + `connector` services are the only two doors — one in, one out.\n\n**The Integration Manager is NOT a separate service.** It is the adapter pattern implemented inside `act` (for outbound execution) and `connector`/`connector-sync` (for inbound sync and OAuth). This is faster, simpler, and achieves the same swappability.\n\n---\n\n## 5. The Adapter Pattern (Replaces Integration Manager)\n\nThe 7× agnostic moat is achieved through **adapter modules** inside the services that need them, not a separate orchestration service.\n\n### 5.1 Outbound Adapter Modules (Inside `act` Service)\n\n```\nservices/act/\n├── src/\n│   ├── index.ts                 # Entry point — handles ACT_QUEUE\n│   ├── execute.ts               # Main execution logic\n│   ├── adapters/                # Outbound provider adapters\n│   │   ├── nango.ts             # Nango OAuth adapter (Salesforce, HubSpot, etc.)\n│   │   ├── mcp-outbound.ts      # MCP outbound adapter (calls provider MCP servers)\n│   │   ├── native.ts            # Native REST adapter (direct HTTP calls)\n│   │   ├── credentials.ts       # Credential wall — fetches from CF Secrets/KV\n│   │   └── context-inject.ts    # Entity360 injection before outbound call\n│   └── types.ts\n├── wrangler.toml\n└── package.json\n```\n\n**Execution flow inside `act`:**\n\n```typescript\n// services/act/src/execute.ts\n\nexport async function executeCapability(\n  capability: string, // e.g., \"salesforce.opportunity.update\"\n  tenantId: string,\n  payload: any\n): Promise<ExecutionResult> {\n  // 1. Resolve provider from capability path\n  const [provider, resource, operation] = capability.split(\".\");\n\n  // 2. Fetch tenant credentials (credential wall)\n  const credentials = await getCredentials(provider, tenantId);\n  //    → reads from Cloudflare Secrets or KV, never hardcoded\n\n  // 3. Fetch Entity360 context for injection\n  const context = await getEntity360(tenantId, payload.entity_id);\n\n  // 4. Select adapter based on provider config\n  const adapter = selectAdapter(provider, credentials);\n  //    → Nango adapter for OAuth-mature providers\n  //    → MCP adapter for AI-native providers\n  //    → Native adapter for direct REST\n\n  // 5. Inject context and execute\n  const enrichedPayload = injectContext(payload, context);\n  const result = await adapter.execute(resource, operation, enrichedPayload, credentials);\n\n  // 6. Writeback to Spine (through Pipeline, not direct D1 write)\n  await enqueueToPipelineQueue({\n    type: \"execution_result\",\n    tenantId,\n    capability,\n    result,\n    timestamp: Date.now(),\n  });\n\n  return result;\n}\n\n// Adapter selection — no separate Integration Manager service\nfunction selectAdapter(provider: string, credentials: Credentials): Adapter {\n  if (credentials.type === \"nango\") return new NangoAdapter();\n  if (credentials.type === \"mcp\") return new MCPOutboundAdapter();\n  if (credentials.type === \"native\") return new NativeAdapter();\n  throw new Error(`Unknown adapter type: ${credentials.type}`);\n}\n```\n\n**Why this is better than a separate Integration Manager:**\n\n- **Zero extra hop:** `act` → adapter → provider. No `act` → Integration Manager → adapter → provider.\n- **Faster deploy:** `act` deploys as one Worker. No coordinating deploys between `act` and Integration Manager.\n- **Smaller blast radius:** If Salesforce adapter breaks, only `act` service is affected. Not a shared Integration Manager that takes down all outbound calls.\n- **Same swappability:** Adapter interface is the contract. Swap Nango for direct OAuth by changing the adapter implementation. No external orchestrator needed.\n\n### 5.2 Inbound Adapter Modules (Inside `connector` + `connector-sync`)\n\n```\nservices/connector/\n├── src/\n│   ├── index.ts                 # OAuth callback handler\n│   ├── nango.ts                 # Nango session creation\n│   └── adapters/                # Provider-specific auth handling\n│       ├── salesforce.ts\n│       ├── hubspot.ts\n│       └── slack.ts\n\nservices/connector-sync/\n├── src/\n│   ├── index.ts                 # Sync orchestration\n│   ├── sync.ts                  # Main sync loop\n│   └── adapters/                # Provider-specific sync logic\n│       ├── salesforce-sync.ts\n│       ├── hubspot-sync.ts\n│       └── slack-sync.ts\n```\n\n**Sync flow inside `connector-sync`:**\n\n```typescript\n// services/connector-sync/src/sync.ts\n\nexport async function runSync(connectorId: string, tenantId: string): Promise<SyncResult> {\n  // 1. Fetch connector config\n  const config = await getConnectorConfig(connectorId, tenantId);\n\n  // 2. Get credentials (from Nango vault or CF Secrets)\n  const credentials = await getCredentials(config.provider, tenantId);\n\n  // 3. Select sync adapter\n  const adapter = selectSyncAdapter(config.provider);\n  //    → SalesforceSyncAdapter, HubSpotSyncAdapter, etc.\n\n  // 4. Fetch raw records from provider\n  const rawRecords = await adapter.fetch(credentials, config.lastSyncTime);\n\n  // 5. Enqueue to Normalizer (not direct Pipeline write)\n  await enqueueToNormalizerQueue({\n    tenantId,\n    provider: config.provider,\n    records: rawRecords,\n    timestamp: Date.now(),\n  });\n\n  return { recordsFetched: rawRecords.length };\n}\n```\n\n### 5.3 The Adapter Interface (The Contract)\n\n```typescript\n// packages/connectors/src/types.ts (shared adapter contract)\n\nexport interface OutboundAdapter {\n  execute(\n    resource: string,\n    operation: string,\n    payload: any,\n    credentials: Credentials\n  ): Promise<ExecutionResult>;\n}\n\nexport interface InboundSyncAdapter {\n  fetch(credentials: Credentials, since: Date): Promise<RawRecord[]>;\n}\n\nexport interface Credentials {\n  type: \"nango\" | \"mcp\" | \"native\";\n  tenantId: string;\n  // Provider-specific fields\n  accessToken?: string;\n  refreshToken?: string;\n  apiKey?: string;\n  // Nango-specific\n  connectionId?: string;\n  // MCP-specific\n  serverUrl?: string;\n}\n\n// Adapter registry (simple map, not a separate service)\n  salesforce: NangoAdapter,\n  hubspot: NangoAdapter,\n  slack: NangoAdapter,\n  github: MCPOutboundAdapter,\n  linear: MCPOutboundAdapter,\n  stripe: NativeAdapter,\n  custom: NativeAdapter,\n};\n\n  salesforce: SalesforceSyncAdapter,\n  hubspot: HubSpotSyncAdapter,\n  slack: SlackSyncAdapter,\n  // ...\n};\n```\n\n### 5.4 Swappability Without a Separate Service\n\nThe 7× agnostic moat is achieved through:\n\n| Dimension               | Adapter Module                                        | Location                                | Swap Method                                                  |\n| ----------------------- | ----------------------------------------------------- | --------------------------------------- | ------------------------------------------------------------ |\n| **Storage**             | `db-adapter.ts`                                       | `packages/lib/`                         | Change `db-gate.ts` to use D1, Supabase, Neon, or HyperDrive |\n| **Auth**                | `auth-adapter.ts`                                     | `packages/lib/`                         | Change `auth.ts` to issue JWT, Clerk, or Stack tokens        |\n| **AI Model**            | `openrouter.ts`                                       | `packages/lib/`                         | Change model config in `think` service                       |\n| **Provider (Outbound)** | `NangoAdapter`, `MCPOutboundAdapter`, `NativeAdapter` | `services/act/src/adapters/`            | Change adapter registration in `outboundAdapters` map        |\n| **Provider (Inbound)**  | `SalesforceSyncAdapter`, `HubSpotSyncAdapter`, etc.   | `services/connector-sync/src/adapters/` | Change adapter registration in `syncAdapters` map            |\n| **Queue**               | `queue-adapter.ts`                                    | `packages/lib/`                         | Change from Cloudflare Queues to SQS or Kafka                |\n| **Cache**               | `cache-adapter.ts`                                    | `packages/lib/`                         | Change from KV to Redis or Upstash                           |\n| **Deployment**          | `wrangler.toml`                                       | Per service                             | Change from Workers to Lambda or Vercel                      |\n\n**No separate Integration Manager service needed.** The adapter pattern inside the services that actually need it is faster, simpler, and more deployable.\n\n---\n\n## 6. The 26 Services (Physical Topology — Revised)\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; 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, RBAC, plan limits                                                                                     | `TENANTS`        |\n| `connector`      | `iw-connector`      | OAuth callback handler; Nango session creation; **inbound adapter pattern**                                                 | `CONNECTOR`      |\n| `connector-sync` | `iw-connector-sync` | Orchestrates sync; **inbound sync adapters**                                                                                | `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\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 (8 lenses)                                         | `L2`                |\n| `intelligence`      | `iw-intelligence`      | Analytics, insights, signal generation, Context Assembly                                     | `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; **outbound adapter modules** (Nango, MCP, Native); 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` | Inbound MCP bridge; external agents → scoped Spine/Memory     | `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 (OpenRouter abstraction)    | `THINK`          |\n\n---\n\n## 7. The 0–16 Stack (Physical Implementation — Revised)\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, **inbound adapter modules**                          |\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`), **outbound adapter modules** |\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, Reliability (idempotency, retries, DLQ, backpressure), Compliance (audit & lineage, retention, encryption, tenant isolation).\n\n---\n\n## 8. MCP Pool Architecture (Unchanged)\n\n### 8.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):**\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### 8.2 Outbound MCP Pool (South Plane — Inside `act` Service)\n\nInside `act` service, not a separate Integration Manager. The `act` service's `MCPOutboundAdapter` module connects to provider MCP servers (Salesforce MCP, Slack MCP, GitHub MCP) using MCP as the transport.\n\n**Entity360 context injected before every outbound call.** Credential wall fetches per-tenant keys from Cloudflare Secrets/KV. No shared tokens across tenants.\n\n---\n\n## 9. Governance & Approval Gate (The 0.70/0.85 Law — Unchanged)\n\nTwo triage gates run on the same confidence thresholds:\n\n### 9.1 Governance Triage (Execution Gate)\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### 9.2 Memory Triage (Knowledge Gate)\n\n| Confidence  | Action       | Destination                         |\n| ----------- | ------------ | ----------------------------------- |\n| ≥ 0.85      | Auto-promote | Active memory (D1 + KV + Vectorize) |\n| 0.70 – 0.85 | Staging      | Staging memory (D1 only)            |\n| < 0.70      | Discard      | R2 cold storage (compliance/audit)  |\n\n---\n\n## 10. The Swappable Layers (7× Agnostic Moat — Revised)\n\nThe swappability is achieved through **adapter modules**, not a separate Integration Manager service.\n\n| Dimension               | Adapter Module                                        | Location                                | Swap Method                                                             |\n| ----------------------- | ----------------------------------------------------- | --------------------------------------- | ----------------------------------------------------------------------- |\n| **Frontend**            | UI framework                                          | `apps/web/`                             | Vite → Next.js → Electron by replacing framework                        |\n| **Auth**                | `auth-adapter.ts`                                     | `packages/lib/`                         | JWT → Clerk → Stack by changing `verify()` implementation               |\n| **Relational Store**    | `db-adapter.ts`                                       | `packages/lib/`                         | D1 → Supabase → Neon by changing `query()` implementation               |\n| **Cache**               | `cache-adapter.ts`                                    | `packages/lib/`                         | KV → Redis → Upstash by changing `get()`/`set()` implementation         |\n| **Queue**               | `queue-adapter.ts`                                    | `packages/lib/`                         | Queues → SQS → Kafka by changing `enqueue()`/`dequeue()` implementation |\n| **AI / Model**          | `openrouter.ts`                                       | `packages/lib/`                         | gpt-5-mini → Claude → Grok by changing model config                     |\n| **Provider (Outbound)** | `NangoAdapter`, `MCPOutboundAdapter`, `NativeAdapter` | `services/act/src/adapters/`            | Change adapter registration in `outboundAdapters` map                   |\n| **Provider (Inbound)**  | `SalesforceSyncAdapter`, `HubSpotSyncAdapter`, etc.   | `services/connector-sync/src/adapters/` | Change adapter registration in `syncAdapters` map                       |\n| **Deployment**          | `wrangler.toml`                                       | Per service                             | Workers → Lambda → Vercel by changing deploy target                     |\n\n**The adapter interface is the contract.** The implementation is swappable. No separate orchestrator needed.\n\n---\n\n## 11. Security Posture (P0 & P1 — Unchanged)\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## 12. The One Invariant (Unchanged)\n\n> Identity gates the door. Discovery advertises the capabilities. The `act` and `connector` services are the only hands that touch outside tools (through their adapter modules). 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## 13. Resolution of All Conflicts (Unchanged from v1.0.0)\n\nAll §14 conflicts from v1.0.0-FINAL remain locked. The only change in v1.0.1 is the removal of the Integration Manager as a separate service and the formalization of the adapter pattern inside `act` + `connector` + `connector-sync`.\n\n---\n\n**END OF DOCUMENT**\n\n_IntegrateWise Continuity Bridge — Canonical Architecture Specification v1.0.1-FINAL. The Integration Manager is not a separate service. It is the adapter pattern inside the services that actually touch providers. Native builds and deployments are faster this way._\n"}