{"slug":"architecture/v2-deployment","title":"IntegrateWise Continuity Bridge v2.0 — Deployment Architecture and Service Topology","section":"architecture","sectionLabel":"Architecture","status":"superseded","type":"document","path":"architecture/v2-deployment.mdx","bytes":101426,"description":null,"updated":null,"source":"integratewise/Integratewise-docs-wiki","content":"\n**Domain:** Deployment Architecture and Service Topology — Cloudflare Workers topology, D1 databases, KV namespaces, Durable Objects, Queues, R2, Vectorize, Service bindings map, CI/CD pipeline, Local dev stack, Per-app deployment subsets  \n**Stage:** 1/2 Deep-Dive → Canonical Architecture Document  \n**Version:** 2.0.0-DRAFT  \n**Date:** 2026-07-02  \n**Platform Layer:** Infrastructure Foundation (Layer 0 of the 6-Layer Stack: Identity → Ingress → Capability → Continuity → Governance → Provider Fabric)\n\n> **Status:** SUPERSEDED DRAFT — topology reference only. D1 source-of-truth\n> and shared-environment claims do not override\n> `IMPLEMENTATION_CONTRACT_v1.1.md` or\n> `CONSOLIDATED_PRODUCT_PLATFORM_CONTRACT_v1.2.md`.\n\n---\n\n## 1. Domain Charter\n\nThis document specifies the **physical deployment substrate** of the IntegrateWise Continuity Bridge v2.0. It is the definitive reference for how the 26-service mesh maps to Cloudflare primitives, how data flows across those primitives, and how the platform maintains tenant isolation, observability, and deployability at scale.\n\n**Scope In:** Cloudflare Workers (service mesh), D1 (relational), KV (cache/registry), Durable Objects (stateful compute), Queues (async messaging), R2 (object storage), Vectorize (vector search), Service Bindings (inter-service RPC), CI/CD (GitHub Actions → Wrangler), local development (Miniflare + Wrangler), per-app deployment subsets (selective deploys).\n\n**Scope Out:** Application business logic (covered by service-specific specs), frontend build pipeline (covered by Frontend Architecture domain), AI model selection (covered by Capability Engine domain), provider adapter implementations (covered by Provider Fabric domain).\n\n**Key Invariant:** Every physical primitive carries `tenant_id`. Every deployment unit is tenant-agnostic at the infrastructure level — isolation is enforced at the data layer, not by separate infrastructure per tenant.\n\n---\n\n## 2. Physical Topology Overview\n\n### 2.1 The 6-Layer Architecture — Infrastructure Mapping\n\n```\n┌─────────────────────────────────────────────────────────────────────────────┐\n│  LAYER 1: IDENTITY          │  Gateway JWT, API Keys, RBAC, Tenant Resolution│\n│  Services: gateway, tenants │  Storage: D1 (tenants, rbac_roles)            │\n├─────────────────────────────────────────────────────────────────────────────┤\n│  LAYER 2: INGRESS           │  Webhooks, MCP Inbound, SSE, OAuth callbacks  │\n│  Services: webhook-ingress, │  Storage: KV (session cache), D1 (sync_jobs)  │\n│  mcp-connector, connector   │  Queues: CONNECTOR_SYNC_QUEUE                 │\n├─────────────────────────────────────────────────────────────────────────────┤\n│  LAYER 3: CAPABILITY        │  OODA Observe+Orient, Normalization, RAG,     │\n│  Services: normalizer,      │  Context Assembly, Knowledge, Intelligence    │\n│  intelligence, knowledge,   │  Storage: D1 (entities, relationships),        │\n│  think, iw-agent-runtime    │  Vectorize (embeddings), KV (context cache)   │\n├─────────────────────────────────────────────────────────────────────────────┤\n│  LAYER 4: CONTINUITY        │  The Moat — Spine, Memory, Twin, Governance,  │\n│  Services: pipeline,        │  Workflow, Continuity Engine                  │\n│  twin-orchestrator,         │  Storage: D1 (spine, memory, audit),           │\n│  continuity, govern,        │  DO (stateful sessions), KV (decay, handoffs) │\n│  workflow, hermes, triage   │  Queues: PIPELINE_QUEUE, ACT_QUEUE            │\n├─────────────────────────────────────────────────────────────────────────────┤\n│  LAYER 5: GOVERNANCE        │  Confidence gates, HITL, Approval, Audit      │\n│  Services: govern, billing, │  Storage: D1 (governance_audit_log, proposals)│\n│  admin, telemetry           │  Storage: R2 (telemetry blobs), D1 (audit)    │\n├─────────────────────────────────────────────────────────────────────────────┤\n│  LAYER 6: PROVIDER FABRIC   │  Outbound execution, adapters, credential wall│\n│  Services: act, connector,  │  Storage: KV (credentials cache — encrypted),  │\n│  connector-sync, loader     │  D1 (connector configs), R2 (sync blobs)      │\n└─────────────────────────────────────────────────────────────────────────────┘\n                              │\n                              ▼\n              ┌───────────────────────────────┐\n              │  Nango Vault (external)        │\n              │  Provider APIs (Salesforce,    │\n              │  Slack, GitHub, Stripe, ...)   │\n              └───────────────────────────────┘\n```\n\n**OODA Span:** The OODA loop physically spans Layer 3 (Observe/ Orient via `normalizer`, `intelligence`, `knowledge`) and Layer 4 (Decide/Act via `twin-orchestrator`, `govern`, `workflow`, `act`). The loop closes through `pipeline` writes to Spine.\n\n**Twin Ambience:** `twin-orchestrator` is a Durable Object — it is ambient to Layers 3–5, not a separate layer. It reasons over Spine context, proposes through Governance, and persists state in DO storage.\n\n---\n\n## 3. Cloudflare Workers Service Mesh (26 Services)\n\n### 3.1 Tiered Deployment Topology\n\nAll 26 services deploy as Cloudflare Workers. All serve all tenants. Customer-Zero is a tenant class, not a separate deployment.\n\n```\n┌──────────────────────────────────────────────────────────────────────────────┐\n│                              TIER 0 — INGRESS                                 │\n│  ┌─────────────────┐    ┌─────────────────┐    ┌─────────────────────────┐   │\n│  │   gateway       │    │ webhook-ingress │    │  (Pages) apps/web       │   │\n│  │   integratewise-│    │   iw-webhook-   │    │  (Pages) apps/mcp-server│   │\n│  │   gateway       │    │   ingress       │    │                         │   │\n│  │   [Worker]      │    │   [Worker]      │    │  [Cloudflare Pages]     │   │\n│  └────────┬────────┘    └────────┬────────┘    └─────────────────────────┘   │\n│           │                      │                                            │\n│           ▼                      ▼                                            │\n│  ┌────────────────────────────────────────────────────────────────────────┐  │\n│  │                     SERVICE BINDINGS (RPC)                              │  │\n│  │  gateway ──► {TENANTS, WEBHOOK_INGRESS, NORMALIZER, PIPELINE, ACT, ...} │  │\n│  └────────────────────────────────────────────────────────────────────────┘  │\n├──────────────────────────────────────────────────────────────────────────────┤\n│                              TIER 1 — TENANT & SYNC                           │\n│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────┐  │\n│  │   tenants   │  │  connector  │  │connector-sync│  │      normalizer     │  │\n│  │  iw-tenants │  │ iw-connector│  │iw-connector- │  │    iw-normalizer    │  │\n│  │  [Worker]   │  │  [Worker]   │  │   sync      │  │     [Worker]        │  │\n│  └─────────────┘  └─────────────┘  │   [Worker]   │  └─────────────────────┘  │\n│  ┌─────────────┐                   └─────────────┘  ┌─────────────────────┐  │\n│  │    loader   │                                    │     spine-v2        │  │\n│  │  iw-loader  │                                    │     iw-spine-v2     │  │\n│  │  [Worker]   │                                    │     [Worker]        │  │\n│  └─────────────┘                                    └─────────────────────┘  │\n├──────────────────────────────────────────────────────────────────────────────┤\n│                           TIER 2 — PROJECTION & RENDERING                     │\n│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────┐  │\n│  │   pipeline  │  │twin-orchestr│  │     l2      │  │    intelligence     │  │\n│  │ iw-pipeline │  │   ator      │  │    iw-l2    │  │   iw-intelligence   │  │\n│  │ [Worker]    │  │ [Durable    │  │  [Worker]   │  │    [Worker]         │  │\n│  │             │  │  Object]    │  │             │  │                     │  │\n│  └─────────────┘  └─────────────┘  └─────────────┘  └─────────────────────┘  │\n│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────┐  │\n│  │  knowledge  │  │   govern    │  │    store    │  │        act          │  │\n│  │ iw-knowledge│  │  iw-govern  │  │   iw-store  │  │      iw-act         │  │\n│  │  [Worker]   │  │  [Worker]   │  │  [Worker]   │  │     [Worker]        │  │\n│  └─────────────┘  └─────────────┘  └─────────────┘  └─────────────────────┘  │\n├──────────────────────────────────────────────────────────────────────────────┤\n│                        TIER 3 — CAPABILITY RUNTIME                            │\n│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────┐  │\n│  │   hermes    │  │   triage    │  │   workflow  │  │   iw-agent-runtime  │  │\n│  │  iw-hermes  │  │  iw-triage  │  │ iw-workflow │  │  iw-agent-runtime   │  │\n│  │ [Durable    │  │ [Worker —   │  │ [Durable    │  │     [Worker]        │  │\n│  │  Object]    │  │  in Hermes] │  │  Object]    │  │                     │  │\n│  └─────────────┘  └─────────────┘  └─────────────┘  └─────────────────────┘  │\n│  ┌────────────────────────────────────────────────────────────────────────┐  │\n│  │                      mcp-connector (inbound MCP)                        │  │\n│  │                      iw-mcp-connector [Worker]                          │  │\n│  └────────────────────────────────────────────────────────────────────────┘  │\n├──────────────────────────────────────────────────────────────────────────────┤\n│                            TIER 4 — SUPPORTING                                │\n│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐        │  │\n│  │agent-registry│  │   billing   │  │    admin    │  │folder-watcher│       │  │\n│  │iw-agent-reg │  │ iw-billing  │  │  iw-admin   │  │ iw-folder-   │       │  │\n│  │  [Worker]   │  │  [Worker]   │  │  [Worker]   │  │  watcher     │       │  │\n│  └─────────────┘  └─────────────┘  └─────────────┘  │ [Durable     │       │  │\n│  ┌─────────────┐  ┌─────────────┐                   │   Object]    │       │  │\n│  │  continuity │  │  telemetry  │                   └─────────────┘       │  │\n│  │iw-continuity│  │ iw-telemetry│  ┌─────────────┐                        │  │\n│  │  [Worker]   │  │  [Worker]   │  │    think    │                        │  │\n│  └─────────────┘  └─────────────┘  │   iw-think  │                        │  │\n│                                     │   [Worker]  │                        │  │\n│                                     └─────────────┘                        │  │\n└──────────────────────────────────────────────────────────────────────────────┘\n```\n\n### 3.2 Worker Configuration Schema (wrangler.toml)\n\nEach service declares its bindings in `wrangler.toml`. The root `infra/wrangler.toml` aggregates all service bindings for cross-service RPC.\n\n```toml\n# infra/wrangler.toml — Root configuration template\nname = \"integratewise-gateway\"\nmain = \"apps/gateway/src/index.ts\"\ncompatibility_date = \"2026-06-01\"\ncompatibility_flags = [\"nodejs_compat\", \"rpc\"]\n\n# D1 Databases\nd1_databases = [\n  { binding = \"DB\", database_name = \"integratewise-spine\", database_id = \"<UUID>\" },\n  { binding = \"DB_AUDIT\", database_name = \"integratewise-audit\", database_id = \"<UUID>\" },\n  { binding = \"DB_TENANTS\", database_name = \"integratewise-tenants\", database_id = \"<UUID>\" }\n]\n\n# KV Namespaces\nkv_namespaces = [\n  { binding = \"KV_DISCOVERY\", id = \"<UUID>\", title = \"discovery-cache\" },\n  { binding = \"KV_SESSIONS\", id = \"<UUID>\", title = \"session-store\" },\n  { binding = \"KV_ENDPOINTS\", id = \"<UUID>\", title = \"endpoint-registry\" },\n  { binding = \"KV_CREDENTIALS\", id = \"<UUID>\", title = \"credentials-cache\" },\n  { binding = \"KV_DECAY\", id = \"<UUID>\", title = \"memory-decay\" },\n  { binding = \"KV_MODEL_CONFIG\", id = \"<UUID>\", title = \"model-config\" }\n]\n\n# R2 Buckets\nr2_buckets = [\n  { binding = \"R2_TELEMETRY\", bucket_name = \"integratewise-telemetry\" },\n  { binding = \"R2_ASSETS\", bucket_name = \"integratewise-assets\" },\n  { binding = \"R2_SYNC_BLOBS\", bucket_name = \"integratewise-sync-blobs\" }\n]\n\n# Vectorize Index\nvectorize = [\n  { binding = \"VECTORIZE_KNOWLEDGE\", index_name = \"integratewise-knowledge\" }\n]\n\n# Queues\nqueues.producers = [\n  { binding = \"PIPELINE_QUEUE\", queue = \"integratewise-pipeline\" },\n  { binding = \"ACT_QUEUE\", queue = \"integratewise-act\" },\n  { binding = \"CONNECTOR_SYNC_QUEUE\", queue = \"integratewise-connector-sync\" },\n  { binding = \"NORMALIZER_QUEUE\", queue = \"integratewise-normalizer\" },\n  { binding = \"TELEMETRY_QUEUE\", queue = \"integratewise-telemetry\" }\n]\n\nqueues.consumers = [\n  { queue = \"integratewise-pipeline\", max_batch_size = 10, max_batch_timeout = 5 },\n  { queue = \"integratewise-act\", max_batch_size = 5, max_batch_timeout = 10 },\n  { queue = \"integratewise-connector-sync\", max_batch_size = 20, max_batch_timeout = 30 },\n  { queue = \"integratewise-normalizer\", max_batch_size = 50, max_batch_timeout = 10 },\n  { queue = \"integratewise-telemetry\", max_batch_size = 100, max_batch_timeout = 5 }\n]\n\n# Service Bindings (RPC to other Workers)\nservices = [\n  { binding = \"TENANTS\", service = \"iw-tenants\" },\n  { binding = \"WEBHOOK_INGRESS\", service = \"iw-webhook-ingress\" },\n  { binding = \"CONNECTOR\", service = \"iw-connector\" },\n  { binding = \"CONNECTOR_SYNC\", service = \"iw-connector-sync\" },\n  { binding = \"NORMALIZER\", service = \"iw-normalizer\" },\n  { binding = \"LOADER\", service = \"iw-loader\" },\n  { binding = \"PIPELINE\", service = \"iw-pipeline\" },\n  { binding = \"TWIN_ORCHESTRATOR\", service = \"iw-twin-orchestrator\" },\n  { binding = \"L2\", service = \"iw-l2\" },\n  { binding = \"INTELLIGENCE\", service = \"iw-intelligence\" },\n  { binding = \"KNOWLEDGE\", service = \"iw-knowledge\" },\n  { binding = \"GOVERN\", service = \"iw-govern\" },\n  { binding = \"STORE\", service = \"iw-store\" },\n  { binding = \"ACT\", service = \"iw-act\" },\n  { binding = \"SPINE_V2\", service = \"iw-spine-v2\" },\n  { binding = \"HERMES\", service = \"iw-hermes\" },\n  { binding = \"TRIAGE\", service = \"iw-triage\" },\n  { binding = \"WORKFLOW\", service = \"iw-workflow\" },\n  { binding = \"IW_AGENT_RUNTIME\", service = \"iw-agent-runtime\" },\n  { binding = \"MCP_CONNECTOR\", service = \"iw-mcp-connector\" },\n  { binding = \"AGENT_REGISTRY\", service = \"iw-agent-registry\" },\n  { binding = \"BILLING\", service = \"iw-billing\" },\n  { binding = \"ADMIN\", service = \"iw-admin\" },\n  { binding = \"FOLDER_WATCHER\", service = \"iw-folder-watcher\" },\n  { binding = \"CONTINUITY\", service = \"iw-continuity\" },\n  { binding = \"TELEMETRY\", service = \"iw-telemetry\" },\n  { binding = \"THINK\", service = \"iw-think\" }\n]\n\n# Durable Objects (stateful)\n[durable_objects]\nbindings = [\n  { name = \"TWIN_DO\", class_name = \"TwinOrchestrator\" },\n  { name = \"HERMES_DO\", class_name = \"HermesEngine\" },\n  { name = \"WORKFLOW_DO\", class_name = \"WorkflowOrchestrator\" },\n  { name = \"FOLDER_WATCHER_DO\", class_name = \"FolderWatcher\" },\n  { name = \"GOVERN_HITL_DO\", class_name = \"GovernanceHITL\" }\n]\n\n# Secrets (populated via `wrangler secret put` or GitHub Actions)\n[vars]\nENVIRONMENT = \"production\"\nOPENROUTER_API_URL = \"https://openrouter.ai/api/v1\"\n\n# Environment-specific overrides\n[env.staging]\nname = \"integratewise-gateway-staging\"\nd1_databases = [\n  { binding = \"DB\", database_name = \"integratewise-spine-staging\", database_id = \"<STAGING-UUID>\" }\n]\n\n[env.development]\nname = \"integratewise-gateway-dev\"\n```\n\n---\n\n## 4. D1 Database Architecture\n\n### 4.1 Multi-Database Strategy\n\nThe platform uses **three logical D1 databases** with distinct consistency and retention requirements. All tables carry `tenant_id` as the leading column in every index.\n\n```\n┌─────────────────────────────────────────────────────────────────────────────┐\n│  DB (Spine + Context)         │  Primary operational database                │\n│  ─────────────────────────────┼──────────────────────────────────────────────│\n│  entities                     │  Core SSOC entities (accounts, contacts,     │\n│  relationships                │  deals, tasks, tickets, etc.)                │\n│  spine_audit_log              │  Immutable audit trail — every read/write    │\n│  memory (active/staging/arch) │  Shared memory tiers — Personal, Work, Org   │\n│  continuity_graph             │  Relationship traversal graph                │\n│  normalizer_state             │  8-stage pipeline checkpointing              │\n│  sync_jobs                    │  Connector sync job metadata                 │\n│  action_proposals             │  Governance proposals (pending/approved)     │\n│  projections                  │  L1/L2 projection materialized views         │\n│  capability_registry          │  Named capabilities + schemas                │\n│  endpoint_registry            │  Living API contract (path, method, owner)   │\n└─────────────────────────────────────────────────────────────────────────────┘\n\n┌─────────────────────────────────────────────────────────────────────────────┐\n│  DB_AUDIT (Compliance)        │  Append-only, long-retention, encrypted      │\n│  ─────────────────────────────┼──────────────────────────────────────────────│\n│  governance_audit_log         │  Approval decisions with confidence scores   │\n│  twin_audit_events            │  Model calls, reasoning traces, latencies    │\n│  outbound_mcp_calls           │  Provider call log with latency/error        │\n│  tenant_access_log            │  Who accessed what, when, from where         │\n└─────────────────────────────────────────────────────────────────────────────┘\n\n┌─────────────────────────────────────────────────────────────────────────────┐\n│  DB_TENANTS (Identity)        │  Small, hot, cached aggressively             │\n│  ─────────────────────────────┼──────────────────────────────────────────────│\n│  tenants                      │  Tenant metadata, plan tier, limits          │\n│  rbac_roles                   │  Role definitions per tenant                 │\n│  rbac_permissions             │  Permission grants (user × role × resource)  │\n│  tenant_spine_config          │  Per-tenant schema overrides, connectors     │\n│  invitations                  │  Pending org invitations (scoped)            │\n└─────────────────────────────────────────────────────────────────────────────┘\n```\n\n### 4.2 Tenant Isolation Schema\n\nEvery D1 query MUST use `withTenant()`. The helper injects `WHERE tenant_id = ?` and validates the tenant matches the JWT claim.\n\n```typescript\n// packages/spine-schema/src/helpers.ts\n\nexport interface TenantQueryOptions {\n  tenantId: string;\n  tableName: string;\n  action: \"read\" | \"write\" | \"delete\";\n}\n\n  // Enforce tenant_id filter on every query\n  // Fail-loud: if tenantId is missing or mismatched, throw 403\n  if (!tenantId || tenantId.length < 4) {\n    throw new Error(\"TENANT_ID_REQUIRED: Cross-tenant queries are forbidden\");\n  }\n  return query.where(eq(query.tenant_id, tenantId));\n}\n\n// Example usage in a service:\n// const records = await withTenant(\n//   db.select().from(entities),\n//   env.tenantId\n// ).limit(100);\n```\n\n### 4.3 Connection Pooling\n\nD1 has built-in connection pooling. For complex analytics queries that exceed D1's 5-minute query limit, the platform falls back to **HyperDrive** (Cloudflare's PostgreSQL connection pooler) or the swappable relational store (currently Supabase, wrapped behind `db-gate`).\n\n| Workload Type            | Default Store           | Fallback              | Adapter             |\n| ------------------------ | ----------------------- | --------------------- | ------------------- |\n| CRUD operations          | D1                      | HyperDrive PostgreSQL | `db-adapter.ts`     |\n| Analytics / aggregations | D1 (materialized views) | HyperDrive            | `db-adapter.ts`     |\n| Full-text search         | D1 (FTS5)               | AI Search / Vectorize | `search-adapter.ts` |\n| Large blob storage       | R2                      | S3-compatible         | `blob-adapter.ts`   |\n\n---\n\n## 5. KV Namespaces (Cache & Registry Layer)\n\n### 5.1 KV Topology\n\n```\n┌─────────────────────────────────────────────────────────────────────────────┐\n│  KV_DISCOVERY                 │  Capability catalog cache (TTL: 300s)        │\n│  ─────────────────────────────┼──────────────────────────────────────────────│\n│  Key: `discovery:{tenant_id}` │  JSON: { projections, capabilities, limits } │\n│  Key: `registry:{type}:{id}`  │  JSON: { endpoint, schema, version, owner }  │\n└─────────────────────────────────────────────────────────────────────────────┘\n\n┌─────────────────────────────────────────────────────────────────────────────┐\n│  KV_SESSIONS                  │  MCP session state + JWT token cache         │\n│  ─────────────────────────────┼──────────────────────────────────────────────│\n│  Key: `session:{session_id}`  │  JSON: { tenant_id, user_id, scopes, expiry }│\n│  Key: `token:{jti}`           │  JSON: { tenant_id, roles, issued_at }       │\n└─────────────────────────────────────────────────────────────────────────────┘\n\n┌─────────────────────────────────────────────────────────────────────────────┐\n│  KV_ENDPOINTS                 │  Living API contract — endpoint registry     │\n│  ─────────────────────────────┼──────────────────────────────────────────────│\n│  Key: `ep:{method}:{path}`    │  JSON: { service, auth_type, status, change }│\n│  Key: `ep:list:{service}`     │  JSON: [ { method, path, description } ]     │\n└─────────────────────────────────────────────────────────────────────────────┘\n\n┌─────────────────────────────────────────────────────────────────────────────┐\n│  KV_CREDENTIALS               │  Encrypted credential cache (TTL: 3600s)     │\n│  ─────────────────────────────┼──────────────────────────────────────────────│\n│  Key: `cred:{provider}:{tid}` │  JSON: { type, encrypted_blob, expires_at }  │\n│  Key: `nango:{connectionId}`  │  JSON: { session_token, provider_config }    │\n└─────────────────────────────────────────────────────────────────────────────┘\n\n┌─────────────────────────────────────────────────────────────────────────────┐\n│  KV_DECAY                     │  Memory decay tracking + session handoffs    │\n│  ─────────────────────────────┼──────────────────────────────────────────────│\n│  Key: `decay:{tenant_id}:{mem_id}` │  JSON: { last_access, decay_score, tier } │\n│  Key: `handoff:{tenant_id}:{user_id}` │  JSON: { from_session, to_session, ts } │\n└─────────────────────────────────────────────────────────────────────────────┘\n\n┌─────────────────────────────────────────────────────────────────────────────┐\n│  KV_MODEL_CONFIG              │  Per-tenant / per-capability model selection │\n│  ─────────────────────────────┼──────────────────────────────────────────────│\n│  Key: `model:{tenant_id}`     │  JSON: { default, fallback, max_tokens }     │\n│  Key: `model:{tenant_id}:{cap}` │  JSON: { provider, model, temperature }    │\n└─────────────────────────────────────────────────────────────────────────────┘\n```\n\n### 5.2 KV Contract (TypeScript)\n\n```typescript\n// packages/spine-schema/src/kv-contracts.ts\n\nexport interface DiscoveryCacheEntry {\n  tenantId: string;\n  projections: string[]; // 8 lenses\n  capabilities: CapabilityEntry[];\n  features: Record<string, boolean>;\n  limits: { rateLimit: number; storageQuota: number; modelQuota: number };\n  updatedAt: number;\n  ttl: number; // 300 seconds\n}\n\nexport interface SessionCacheEntry {\n  sessionId: string;\n  tenantId: string;\n  userId: string;\n  scopes: (\"read\" | \"write\" | \"admin\")[];\n  createdAt: number;\n  expiresAt: number;\n  via: \"mcp\" | \"web\" | \"api_key\";\n}\n\nexport interface EndpointRegistryEntry {\n  method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n  path: string;\n  service: string; // Worker name\n  authType: \"jwt\" | \"api_key\" | \"none\";\n  status: \"stable\" | \"beta\" | \"deprecated\";\n  changeSummary: string;\n  lastUpdated: number;\n}\n\nexport interface CredentialCacheEntry {\n  provider: string;\n  tenantId: string;\n  type: \"nango\" | \"mcp\" | \"native\";\n  encryptedBlob: string; // AES-256-GCM encrypted\n  expiresAt: number;\n  rotationDueAt: number;\n}\n\nexport interface DecayTrackingEntry {\n  memoryId: string;\n  tenantId: string;\n  lastAccessed: number;\n  accessCount: number;\n  decayScore: number; // 0.0 – 1.0, computed by triage\n  currentTier: \"active\" | \"staging\" | \"archived\";\n}\n```\n\n### 5.3 Cache Invalidation Strategy\n\n| Cache Type  | Invalidation Trigger                         | Pattern                                    |\n| ----------- | -------------------------------------------- | ------------------------------------------ |\n| Discovery   | Tenant config change, connector add/remove   | Write-through + TTL 300s                   |\n| Sessions    | JWT expiry, explicit logout, scope change    | TTL matching JWT expiry                    |\n| Endpoints   | Service deployment, API version change       | Version-stamped keys; old keys TTL 3600s   |\n| Credentials | Token rotation, Nango webhook, manual revoke | Immediate delete + re-fetch on next use    |\n| Decay       | Memory access, triage run (hourly cron)      | Background update via `continuity` service |\n\n---\n\n## 6. Durable Objects (Stateful Compute)\n\n### 6.1 DO Topology\n\nFive Durable Object classes manage stateful compute. Each DO is scoped by `tenant_id` or `tenant_id + user_id`.\n\n```\n┌─────────────────────────────────────────────────────────────────────────────┐\n│  TwinOrchestrator (twin-orchestrator service)                               │\n│  ───────────────────────────────────────────────────────────────────────────│\n│  DO ID: idFromName(`${tenant_id}:${user_id}`)                               │\n│  State: User context window, reasoning chain, proposal history, confidence    │\n│  Persistence: DO storage (transactional) + periodic D1 snapshot             │\n│  Lifecycle: Created on first user interaction; hibernates after 10m idle    │\n│  Alarm: Every 5 minutes — decay old context, snapshot to D1                 │\n└─────────────────────────────────────────────────────────────────────────────┘\n\n┌─────────────────────────────────────────────────────────────────────────────┐\n│  HermesEngine (hermes service)                                              │\n│  ───────────────────────────────────────────────────────────────────────────│\n│  DO ID: idFromName(`${tenant_id}:hermes`)                                   │\n│  State: Message queue head/tail, in-flight jobs, dead-letter tracking       │\n│  Persistence: DO storage for queue state; messages in D1 for durability     │\n│  Lifecycle: Singleton per tenant; always active for active tenants          │\n│  Alarm: Every 30s — process batch, retry dead letters                       │\n└─────────────────────────────────────────────────────────────────────────────┘\n\n┌─────────────────────────────────────────────────────────────────────────────┐\n│  WorkflowOrchestrator (workflow service)                                    │\n│  ───────────────────────────────────────────────────────────────────────────│\n│  DO ID: idFromName(`${tenant_id}:${workflow_id}`)                           │\n│  State: Workflow step, saga compensation log, pause/resume checkpoint       │\n│  Persistence: DO storage + D1 `workflow_state` table                        │\n│  Lifecycle: Created per workflow instance; destroyed on completion          │\n│  Alarm: Configurable per workflow (default: 60s heartbeat)                  │\n└─────────────────────────────────────────────────────────────────────────────┘\n\n┌─────────────────────────────────────────────────────────────────────────────┐\n│  FolderWatcher (folder-watcher service)                                     │\n│  ───────────────────────────────────────────────────────────────────────────│\n│  DO ID: idFromName(`${tenant_id}:${folder_path_hash}`)                      │\n│  State: File tree snapshot, last checksum, watcher config                   │\n│  Persistence: DO storage for active watches; D1 for historical changes      │\n│  Lifecycle: Created when folder registered; hibernates if no changes        │\n│  Alarm: Every 60s — compare checksums, emit change events                   │\n└─────────────────────────────────────────────────────────────────────────────┘\n\n┌─────────────────────────────────────────────────────────────────────────────┐\n│  GovernanceHITL (govern service)                                            │\n│  ───────────────────────────────────────────────────────────────────────────│\n│  DO ID: idFromName(`${tenant_id}:${user_id}:hitl`)                          │\n│  State: Pending proposals, approval history, delegation rules               │\n│  Persistence: DO storage + D1 `action_proposals` (source of truth)          │\n│  Lifecycle: Created on first proposal; active while proposals pending       │\n│  Alarm: Every 5 minutes — expire stale proposals, notify delegates          │\n└─────────────────────────────────────────────────────────────────────────────┘\n```\n\n### 6.2 DO Hibernation & Reactivation\n\n```typescript\n// services/twin-orchestrator/src/index.ts\n\nexport class TwinOrchestrator implements DurableObject {\n  private state: DurableObjectState;\n  private contextWindow: ContextWindow | null = null;\n  private lastActivity: number = Date.now();\n\n  constructor(state: DurableObjectState) {\n    this.state = state;\n    // Restore from DO storage on activation\n    state.blockConcurrencyWhile(async () => {\n      this.contextWindow = await state.storage.get<ContextWindow>(\"context\");\n    });\n  }\n\n  async fetch(request: Request): Promise<Response> {\n    this.lastActivity = Date.now();\n    const { tenantId, userId, action, payload } = await request.json();\n\n    // SECURITY: Validate DO ID matches tenant_id + user_id\n    const expectedId = this.state.id.toString();\n    const derivedId = this.state.idFromName(`${tenantId}:${userId}`).toString();\n    if (expectedId !== derivedId) {\n      return new Response(\"TENANT_MISMATCH\", { status: 403 });\n    }\n\n    switch (action) {\n      case \"reason\":\n        return this.handleReason(payload);\n      case \"propose\":\n        return this.handlePropose(payload);\n      case \"context_snapshot\":\n        return this.handleSnapshot();\n      default:\n        return new Response(\"UNKNOWN_ACTION\", { status: 400 });\n    }\n  }\n\n  async alarm(): Promise<void> {\n    // Every 5 minutes: decay context, snapshot to D1\n    if (this.contextWindow) {\n      const decayed = await applyDecay(this.contextWindow);\n      await this.state.storage.put(\"context\", decayed);\n\n      // Backup to D1 for recovery\n      await backupToD1(this.state.id.toString(), decayed);\n    }\n\n    // Hibernation check: if idle > 10 minutes, allow hibernation\n    if (Date.now() - this.lastActivity > 10 * 60 * 1000) {\n      await this.state.storage.deleteAlarm();\n    }\n  }\n}\n```\n\n---\n\n## 7. Queues (Async Message Fabric)\n\n### 7.1 Queue Topology & Flow\n\n```\n┌─────────────────────────────────────────────────────────────────────────────┐\n│                         MESSAGE FLOW DIAGRAM                                 │\n│                                                                              │\n│   [Provider Webhook]                                                        │\n│        │                                                                    │\n│        ▼                                                                    │\n│   [webhook-ingress] ──► validate signature ──► enqueue                      │\n│        │                                                                    │\n│        ▼                                                                    │\n│   ┌─────────────────┐                                                       │\n│   │ CONNECTOR_SYNC_ │  Consumer: connector-sync                             │\n│   │     QUEUE       │  Batch: 20, Timeout: 30s                              │\n│   │                 │  DLQ: After 3 retries → R2 cold storage               │\n│   └────────┬────────┘                                                       │\n│            │                                                                │\n│            ▼                                                                │\n│   [connector-sync] ──► fetch raw records ──► enqueue                        │\n│            │                                                                │\n│            ▼                                                                │\n│   ┌─────────────────┐                                                       │\n│   │  NORMALIZER_    │  Consumer: normalizer                                 │\n│   │     QUEUE       │  Batch: 50, Timeout: 10s                              │\n│   │                 │  DLQ: After 3 retries → manual review queue           │\n│   └────────┬────────┘                                                       │\n│            │                                                                │\n│            ▼                                                                │\n│   [normalizer] ──► 8-stage pipeline ──► enqueue                             │\n│            │                                                                │\n│            ▼                                                                │\n│   ┌─────────────────┐                                                       │\n│   │  PIPELINE_      │  Consumer: pipeline                                   │\n│   │     QUEUE       │  Batch: 10, Timeout: 5s                               │\n│   │                 │  DLQ: HALT — pipeline failure stops sync (fail-loud)  │\n│   └────────┬────────┘                                                       │\n│            │                                                                │\n│            ▼                                                                │\n│   [pipeline] ──► ONLY WRITER TO SPINE (D1) ──► emit event                   │\n│            │                                                                │\n│            ▼                                                                │\n│   ┌─────────────────┐    ┌─────────────────┐    ┌─────────────────────┐    │\n│   │   intelligence  │    │twin-orchestrator│    │      govern         │    │\n│   │   (analytics)   │◄───│  (reasoning DO) │───►│  (confidence gate)  │    │\n│   └─────────────────┘    └─────────────────┘    └──────────┬──────────┘    │\n│                                                            │               │\n│                                       ┌────────────────────┼──────────┐    │\n│                                       │                    │          │    │\n│                                       ▼                    ▼          ▼    │\n│                              [>=0.85 auto]          [0.70-0.85]   [<0.70]  │\n│                                  │                     │           │       │\n│                                  ▼                     ▼           ▼       │\n│   ┌─────────────────┐       ┌─────────┐          ┌──────────┐  ┌────────┐  │\n│   │    ACT_QUEUE    │◄──────│  ACT    │          │ My Desk  │  │ Discard│  │\n│   │  Batch: 5       │       │         │          │ (review) │  │ (audit)│  │\n│   │  Timeout: 10s   │       └─────────┘          └──────────┘  └────────┘  │\n│   │  DLQ: 3 retries │                                                      │\n│   └────────┬────────┘                                                      │\n│            │                                                               │\n│            ▼                                                               │\n│   [act] ──► adapter select ──► provider API ──► writeback ──► pipeline    │\n│                                                                              │\n│   ┌─────────────────┐                                                       │\n│   │  TELEMETRY_     │  Consumer: telemetry                                  │\n│   │     QUEUE       │  Batch: 100, Timeout: 5s                              │\n│   │                 │  Fire-and-forget observability events                 │\n│   └─────────────────┘                                                       │\n└─────────────────────────────────────────────────────────────────────────────┘\n```\n\n### 7.2 Queue Contract (TypeScript)\n\n```typescript\n// packages/types/src/queues.ts\n\nexport type QueueName =\n  | \"PIPELINE_QUEUE\"\n  | \"ACT_QUEUE\"\n  | \"CONNECTOR_SYNC_QUEUE\"\n  | \"NORMALIZER_QUEUE\"\n  | \"TELEMETRY_QUEUE\";\n\nexport interface QueueMessage<T = unknown> {\n  id: string; // ULID\n  tenantId: string; // Enforced on every message\n  correlationId: string; // x-correlation-id from ingress\n  timestamp: number; // Unix ms\n  type: string; // Message type discriminator\n  payload: T;\n  retryCount: number; // Managed by queue infrastructure\n  traceId: string; // OpenTelemetry trace ID\n}\n\n// ── Pipeline Queue Messages ──\n\nexport interface PipelineMessage extends QueueMessage {\n  type: \"spine_write\" | \"audit_log\" | \"projection_update\";\n  payload: {\n    table: string; // D1 table name\n    operation: \"insert\" | \"update\" | \"delete\";\n    record: Record<string, unknown>;\n    previousRecord?: Record<string, unknown>; // For audit trail\n  };\n}\n\n// ── Act Queue Messages ──\n\nexport interface ActMessage extends QueueMessage {\n  type: \"capability_execute\" | \"writeback\" | \"adapter_retry\";\n  payload: {\n    capability: string; // e.g., \"salesforce.opportunity.update\"\n    provider: string;\n    resource: string;\n    operation: string;\n    entityId?: string;\n    parameters: Record<string, unknown>;\n    governanceToken?: string; // For 0.70-0.85 approved actions\n  };\n}\n\n// ── Connector Sync Queue Messages ──\n\nexport interface ConnectorSyncMessage extends QueueMessage {\n  type: \"creamy_sync\" | \"incremental_sync\" | \"webhook_triggered_sync\";\n  payload: {\n    connectorId: string;\n    provider: string;\n    syncMode: \"full\" | \"incremental\" | \"webhook\";\n    since?: number; // Last sync timestamp\n    webhookPayload?: Record<string, unknown>;\n  };\n}\n\n// ── Normalizer Queue Messages ──\n\nexport interface NormalizerMessage extends QueueMessage {\n  type: \"raw_records\" | \"schema_detect\" | \"retry_stage\";\n  payload: {\n    records: RawRecord[];\n    provider: string;\n    connectorId: string;\n    stage?: number; // NA0–NA5 stage indicator\n  };\n}\n\n// ── Telemetry Queue Messages ──\n\nexport interface TelemetryMessage extends QueueMessage {\n  type: \"metric\" | \"trace\" | \"log\" | \"audit\";\n  payload: {\n    service: string;\n    metric?: { name: string; value: number; unit: string };\n    trace?: { spanId: string; parentSpanId?: string; durationMs: number };\n    log?: { level: \"debug\" | \"info\" | \"warn\" | \"error\"; message: string };\n  };\n}\n\n// ── Dead Letter Queue Contract ──\n\nexport interface DeadLetterMessage<T = unknown> extends QueueMessage<T> {\n  deadLetteredAt: number;\n  failureReason: string;\n  originalQueue: QueueName;\n  maxRetries: number;\n}\n\n// DLQ destination: R2 bucket `integratewise-dlq` for manual review\n```\n\n### 7.3 Consumer Configuration\n\n```typescript\n// packages/lib/src/queue-adapter.ts\n\nexport interface QueueConsumerConfig {\n  queueName: QueueName;\n  maxBatchSize: number;\n  maxBatchTimeout: number;\n  maxRetries: number;\n  deadLetterQueue?: QueueName | \"R2\";\n  backoffStrategy: \"fixed\" | \"exponential\";\n  backoffMs: number;\n}\n\n  PIPELINE_QUEUE: {\n    queueName: \"PIPELINE_QUEUE\",\n    maxBatchSize: 10,\n    maxBatchTimeout: 5,\n    maxRetries: 3,\n    deadLetterQueue: undefined, // HALT on failure — no DLQ\n    backoffStrategy: \"exponential\",\n    backoffMs: 1000,\n  },\n  ACT_QUEUE: {\n    queueName: \"ACT_QUEUE\",\n    maxBatchSize: 5,\n    maxBatchTimeout: 10,\n    maxRetries: 3,\n    deadLetterQueue: \"R2\", // DLQ to R2 for investigation\n    backoffStrategy: \"exponential\",\n    backoffMs: 2000,\n  },\n  CONNECTOR_SYNC_QUEUE: {\n    queueName: \"CONNECTOR_SYNC_QUEUE\",\n    maxBatchSize: 20,\n    maxBatchTimeout: 30,\n    maxRetries: 3,\n    deadLetterQueue: \"R2\",\n    backoffStrategy: \"fixed\",\n    backoffMs: 5000,\n  },\n  NORMALIZER_QUEUE: {\n    queueName: \"NORMALIZER_QUEUE\",\n    maxBatchSize: 50,\n    maxBatchTimeout: 10,\n    maxRetries: 3,\n    deadLetterQueue: \"R2\",\n    backoffStrategy: \"exponential\",\n    backoffMs: 1000,\n  },\n  TELEMETRY_QUEUE: {\n    queueName: \"TELEMETRY_QUEUE\",\n    maxBatchSize: 100,\n    maxBatchTimeout: 5,\n    maxRetries: 1, // Telemetry is best-effort\n    deadLetterQueue: undefined, // Drop on failure\n    backoffStrategy: \"fixed\",\n    backoffMs: 1000,\n  },\n};\n```\n\n---\n\n## 8. R2 Storage (Object & Blob Layer)\n\n### 8.1 R2 Bucket Topology\n\n```\n┌─────────────────────────────────────────────────────────────────────────────┐\n│  R2_TELEMETRY                 │  Observability data, audit archives          │\n│  ─────────────────────────────┼──────────────────────────────────────────────│\n│  Key: `traces/{date}/{trace_id}.json` │  OpenTelemetry trace spans              │\n│  Key: `metrics/{date}/{service}.parquet` │  Time-series metrics (Parquet)       │\n│  Key: `logs/{date}/{hour}.ndjson` │  Structured logs (newline-delimited JSON) │\n│  Key: `dlq/{queue}/{date}/{msg_id}.json` │  Dead letter queue archives        │\n│  Lifecycle: 90-day retention, then Glacier                                │\n└─────────────────────────────────────────────────────────────────────────────┘\n\n┌─────────────────────────────────────────────────────────────────────────────┐\n│  R2_ASSETS                    │  Static assets, exports, generated docs      │\n│  ─────────────────────────────┼──────────────────────────────────────────────│\n│  Key: `exports/{tenant_id}/{export_id}.csv` │  User data exports               │\n│  Key: `docs/{tenant_id}/{doc_id}.pdf` │  Generated reports                  │\n│  Key: `avatars/{user_id}.png` │  User avatars                                │\n│  Key: `attachments/{tenant_id}/{msg_id}/{file}` │  File attachments           │\n│  Lifecycle: Tenant-controlled; default 1 year                             │\n└─────────────────────────────────────────────────────────────────────────────┘\n\n┌─────────────────────────────────────────────────────────────────────────────┐\n│  R2_SYNC_BLOBS                │  Large sync payloads, raw provider dumps     │\n│  ─────────────────────────────┼──────────────────────────────────────────────│\n│  Key: `sync/{tenant_id}/{provider}/{sync_id}.json.gz` │  Compressed raw data │\n│  Key: `backups/{tenant_id}/{date}/spine.jsonl.gz` │  Spine backups         │\n│  Key: `snapshots/do/{do_id}/{timestamp}.json` │  DO state snapshots      │\n│  Lifecycle: 30-day hot, then archive                                      │\n└─────────────────────────────────────────────────────────────────────────────┘\n```\n\n### 8.2 R2 Access Pattern\n\n```typescript\n// packages/lib/src/blob-adapter.ts\n\nexport interface R2Operations {\n  putTelemetryBlob(\n    key: string,\n    data: ReadableStream,\n    metadata: Record<string, string>\n  ): Promise<void>;\n  getExport(tenantId: string, exportId: string): Promise<ReadableStream | null>;\n  putSyncBlob(tenantId: string, provider: string, syncId: string, data: Buffer): Promise<void>;\n  listBackups(tenantId: string, prefix: string): Promise<string[]>;\n  deleteExpired(prefix: string, before: Date): Promise<number>;\n}\n\n// Security: All R2 keys prefixed with tenant_id\n// Cross-tenant access = 403 (enforced at key-construction time)\n```\n\n---\n\n## 9. Vectorize (Semantic Search Layer)\n\n### 9.1 Vectorize Configuration\n\n```\n┌─────────────────────────────────────────────────────────────────────────────┐\n│  VECTORIZE_KNOWLEDGE          │  Semantic search index                       │\n│  ─────────────────────────────┼──────────────────────────────────────────────│\n│  Dimensions: 768              │  Using text-embedding-3-small (OpenAI)       │\n│  Distance: cosine             │  Cosine similarity for semantic matching     │\n│  Metadata: tenant_id, scope, type, source, created_at                       │\n└─────────────────────────────────────────────────────────────────────────────┘\n```\n\n### 9.2 Vectorize Contract\n\n```typescript\n// packages/types/src/vectorize.ts\n\nexport interface VectorizeDocument {\n  id: string; // ULID\n  tenantId: string; // Filtered in every query\n  vector: number[]; // 768-dimensional embedding\n  metadata: {\n    scope: \"personal\" | \"work\" | \"organization\" | \"ai\";\n    type: \"document\" | \"memory\" | \"insight\" | \"proposal\";\n    source: string; // Service that created the vector\n    entityId?: string; // Linked SSOC entity\n    createdAt: number;\n    accessCount: number; // For recency scoring\n  };\n}\n\nexport interface VectorizeQuery {\n  tenantId: string;\n  vector: number[];\n  topK: number;\n  filter?: {\n    scope?: VectorizeDocument[\"metadata\"][\"scope\"][];\n    type?: VectorizeDocument[\"metadata\"][\"type\"][];\n    source?: string[];\n    minCreatedAt?: number;\n  };\n}\n\n// Example usage in knowledge service:\n// const results = await env.VECTORIZE_KNOWLEDGE.query(query.vector, {\n//   topK: 10,\n//   filter: { tenantId: query.tenantId, scope: ['work', 'organization'] }\n// });\n```\n\n---\n\n## 10. Service Bindings Map (Complete RPC Topology)\n\n### 10.1 Binding Matrix\n\nThe Gateway exposes all 26 services via service bindings. Internal services MAY call each other directly via bindings (bypassing Gateway for performance), but MUST still carry `tenant_id`.\n\n| Caller \\ Callee | gateway | webhook-ingress | tenants | connector | connector-sync | normalizer | loader | pipeline | twin-orch | l2  | intelligence | knowledge | govern | store | act | spine-v2 | hermes | triage | workflow | iw-agent | mcp-conn | agent-reg | billing | admin | folder-w | continuity | telemetry | think |\n| --------------- | ------- | --------------- | ------- | --------- | -------------- | ---------- | ------ | -------- | --------- | --- | ------------ | --------- | ------ | ----- | --- | -------- | ------ | ------ | -------- | -------- | -------- | --------- | ------- | ----- | -------- | ---------- | --------- | ----- |\n| gateway         | —       | R               | R       | R         | R              | R          | R      | R        | R         | R   | R            | R         | R      | R     | R   | R        | R      | R      | R        | R        | R        | R         | R       | R     | R        | R          | R         | R     |\n| webhook-ingress | —       | —               | —       | —         | W              | —          | W      | —        | —         | —   | —            | —         | —      | —     | —   | —        | —      | —      | —        | —        | —        | —         | —       | —     | —        | —          | W         | —     |\n| connector       | R       | —               | R       | —         | W              | —          | —      | —        | —         | —   | —            | —         | —      | —     | —   | —        | —      | —      | —        | —        | —        | —         | —       | —     | —        | —          | —         | —     |\n| connector-sync  | —       | —               | R       | —         | —              | W          | —      | —        | —         | —   | —            | —         | —      | —     | —   | —        | —      | —      | —        | —        | —        | —         | —       | —     | —        | —          | —         | —     |\n| normalizer      | —       | —               | —       | —         | —              | —          | —      | W        | —         | —   | —            | —         | —      | —     | —   | R        | —      | —      | —        | —        | —        | —         | —       | —     | —        | —          | —         | —     |\n| pipeline        | —       | —               | —       | —         | —              | —          | —      | —        | —         | —   | W            | W         | —      | W     | —   | W        | W      | W      | —        | —        | —        | —         | —       | —     | —        | W          | W         | —     |\n| twin-orch       | —       | —               | —       | —         | —              | —          | —      | R        | —         | —   | R            | R         | W      | —     | —   | R        | —      | —      | —        | —        | —        | —         | —       | —     | —        | R          | —         | W     |\n| govern          | —       | —               | —       | —         | —              | —          | —      | R        | —         | —   | —            | —         | —      | —     | W   | —        | —      | —      | W        | —        | —        | —         | —       | —     | —        | —          | —         | —     |\n| act             | —       | —               | —       | —         | —              | —          | —      | W        | —         | —   | —            | —         | —      | —     | —   | —        | —      | —      | —        | —        | —        | —         | —       | —     | —        | —          | —         | —     |\n| hermes          | —       | —               | —       | —         | —              | —          | —      | —        | —         | —   | —            | —         | —      | —     | W   | —        | —      | W      | —        | —        | —        | —         | —       | —     | —        | —          | —         | —     |\n| workflow        | —       | —               | —       | —         | —              | —          | —      | —        | —         | —   | —            | —         | W      | —     | W   | —        | W      | —      | —        | —        | —        | —         | —       | —     | —        | —          | —         | —     |\n| mcp-conn        | —       | —               | R       | —         | —              | —          | —      | R        | —         | —   | R            | R         | —      | —     | —   | R        | —      | —      | —        | —        | —        | —         | —       | —     | —        | —          | —         | —     |\n\n**Legend:** R = Read (calls service for data), W = Write (enqueues or triggers)\n\n### 10.2 Service Binding TypeScript Contract\n\n```typescript\n// apps/gateway/src/bindings.ts\n\nexport interface ServiceBindings {\n  // Tier 0 — Ingress\n  WEBHOOK_INGRESS: Fetcher;\n\n  // Tier 1 — Tenant & Sync\n  TENANTS: Fetcher;\n  CONNECTOR: Fetcher;\n  CONNECTOR_SYNC: Fetcher;\n  NORMALIZER: Fetcher;\n  LOADER: Fetcher;\n\n  // Tier 2 — Projection & Rendering\n  PIPELINE: Fetcher;\n  TWIN_ORCHESTRATOR: Fetcher; // Durable Object binding\n  L2: Fetcher;\n  INTELLIGENCE: Fetcher;\n  KNOWLEDGE: Fetcher;\n  GOVERN: Fetcher;\n  STORE: Fetcher;\n  ACT: Fetcher;\n  SPINE_V2: Fetcher;\n\n  // Tier 3 — Capability Runtime\n  HERMES: Fetcher; // Durable Object binding\n  TRIAGE: Fetcher;\n  WORKFLOW: Fetcher; // Durable Object binding\n  IW_AGENT_RUNTIME: Fetcher;\n  MCP_CONNECTOR: Fetcher;\n\n  // Tier 4 — Supporting\n  AGENT_REGISTRY: Fetcher;\n  BILLING: Fetcher;\n  ADMIN: Fetcher;\n  FOLDER_WATCHER: Fetcher; // Durable Object binding\n  CONTINUITY: Fetcher;\n  TELEMETRY: Fetcher;\n  THINK: Fetcher;\n}\n\n// Every internal RPC call MUST include tenant context\nexport interface InternalRpcRequest {\n  tenantId: string; // From JWT claim — NEVER from client\n  correlationId: string; // Tracing\n  userId?: string; // For user-scoped operations\n  scopes: string[]; // JWT scopes\n  payload: unknown;\n}\n\n// Gateway middleware injects this into every binding call\nexport async function callService<T>(\n  binding: Fetcher,\n  request: InternalRpcRequest,\n  path: string\n): Promise<T> {\n  const response = await binding.fetch(path, {\n    method: \"POST\",\n    headers: {\n      \"Content-Type\": \"application/json\",\n      \"X-Tenant-Id\": request.tenantId, // Fail-loud if missing\n      \"X-Correlation-Id\": request.correlationId,\n    },\n    body: JSON.stringify(request),\n  });\n\n  if (!response.ok) {\n    throw new Error(`SERVICE_ERROR: ${response.status} from ${path}`);\n  }\n\n  return response.json();\n}\n```\n\n---\n\n## 11. CI/CD Pipeline\n\n### 11.1 GitHub Actions Deployment Flow\n\n```\n┌─────────────────────────────────────────────────────────────────────────────┐\n│                         CI/CD PIPELINE                                       │\n│                                                                              │\n│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐    ┌─────────────┐   │\n│  │   Push to   │───►│   Lint &    │───►│   TypeCheck │───►│    Test     │   │\n│  │   main/     │    │   Format    │    │   (tsc)     │    │   (vitest)  │   │\n│  │   feature/* │    │   (eslint)  │    │             │    │             │   │\n│  └─────────────┘    └─────────────┘    └─────────────┘    └──────┬──────┘   │\n│                                                                   │          │\n│                                                                   ▼          │\n│  ┌────────────────────────────────────────────────────────────────────────┐  │\n│  │  DEPLOY MATRIX (parallel, per service)                                  │  │\n│  │  ┌─────────┐  ┌─────────┐  ┌─────────┐  ┌─────────┐  ┌─────────┐      │  │\n│  │  │ gateway │  │webhook- │  │ tenants │  │ connector│  │  ...    │      │  │\n│  │  │         │  │ ingress │  │         │  │  sync   │  │         │      │  │\n│  │  │wrangler │  │wrangler │  │wrangler │  │wrangler │  │wrangler │      │  │\n│  │  │ deploy  │  │ deploy  │  │ deploy  │  │ deploy  │  │ deploy  │      │  │\n│  │  └─────────┘  └─────────┘  └─────────┘  └─────────┘  └─────────┘      │  │\n│  │                                                                         │  │\n│  │  Rollback: If any deploy fails, auto-rollback to previous version       │  │\n│  │  Canary: 10% traffic → 50% → 100% over 15 minutes (gateway only)        │  │\n│  └────────────────────────────────────────────────────────────────────────┘  │\n│                                                                   │          │\n│                                                                   ▼          │\n│  ┌────────────────────────────────────────────────────────────────────────┐  │\n│  │  POST-DEPLOY VERIFICATION                                               │  │\n│  │  • Health check: GET /health on every service                           │  │\n│  │  • Discovery contract test: Verify /api/v1/discovery schema             │  │\n│  │  • MCP smoke test: Connect, list tools, invoke ping                     │  │\n│  │  • E2E: Connect Salesforce → sync → propose → approve (Customer-Zero)   │  │\n│  └────────────────────────────────────────────────────────────────────────┘  │\n└─────────────────────────────────────────────────────────────────────────────┘\n```\n\n### 11.2 GitHub Actions Workflow\n\n```yaml\n# .github/workflows/deploy.yml\nname: Deploy — IntegrateWise Continuity Bridge\n\non:\n  push:\n    branches: [main]\n  pull_request:\n    branches: [main]\n    types: [closed]\n\nenv:\n  NODE_VERSION: '22'\n  PNPM_VERSION: '9'\n  WRANGLER_VERSION: '3'\n\njobs:\n  # ── Stage 1: Quality Gates ──\n  lint:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n      - uses: pnpm/action-setup@v3\n        with: { version: ${{ env.PNPM_VERSION }} }\n      - uses: actions/setup-node@v4\n        with: { node-version: ${{ env.NODE_VERSION }}, cache: 'pnpm' }\n      - run: pnpm install --frozen-lockfile\n      - run: pnpm lint\n\n  typecheck:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n      - uses: pnpm/action-setup@v3\n      - uses: actions/setup-node@v4\n        with: { node-version: ${{ env.NODE_VERSION }}, cache: 'pnpm' }\n      - run: pnpm install --frozen-lockfile\n      - run: pnpm -r typecheck\n\n  test:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n      - uses: pnpm/action-setup@v3\n      - uses: actions/setup-node@v4\n        with: { node-version: ${{ env.NODE_VERSION }}, cache: 'pnpm' }\n      - run: pnpm install --frozen-lockfile\n      - run: pnpm -r test\n\n  # ── Stage 2: Deploy Matrix ──\n  deploy:\n    needs: [lint, typecheck, test]\n    if: github.ref == 'refs/heads/main'\n    runs-on: ubuntu-latest\n    strategy:\n      matrix:\n        service:\n          - gateway\n          - webhook-ingress\n          - tenants\n          - connector\n          - connector-sync\n          - normalizer\n          - pipeline\n          - twin-orchestrator\n          - l2\n          - intelligence\n          - knowledge\n          - govern\n          - store\n          - act\n          - hermes\n          - workflow\n          - mcp-connector\n          - continuity\n          - telemetry\n          - think\n      fail-fast: false\n\n    steps:\n      - uses: actions/checkout@v4\n      - uses: pnpm/action-setup@v3\n      - uses: actions/setup-node@v4\n        with: { node-version: ${{ env.NODE_VERSION }}, cache: 'pnpm' }\n\n      - name: Install dependencies\n        run: pnpm install --frozen-lockfile\n\n      - name: Build service\n        run: pnpm --filter ${{ matrix.service }} build\n\n      - name: Deploy to Cloudflare\n        uses: cloudflare/wrangler-action@v3\n        with:\n          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}\n          accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}\n          workingDirectory: services/${{ matrix.service }}\n          command: deploy --env ${{ github.ref == 'refs/heads/main' && 'production' || 'staging' }}\n\n      - name: Verify health\n        run: |\n          curl -sf https://${{ matrix.service }}.integratewise.ai/health || \\\n          curl -sf https://${{ matrix.service }}-staging.integratewise.ai/health || \\\n          echo \"Health check endpoint not yet exposed\"\n\n  # ── Stage 3: Post-Deploy E2E ──\n  e2e:\n    needs: deploy\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n      - uses: pnpm/action-setup@v3\n      - uses: actions/setup-node@v4\n      - run: pnpm install --frozen-lockfile\n      - run: pnpm e2e:smoke\n        env:\n          TEST_TENANT_ID: ${{ secrets.TEST_TENANT_ID }}\n          TEST_JWT: ${{ secrets.TEST_JWT }}\n```\n\n### 11.3 Semantic Versioning & Rollback\n\n| Artifact  | Version Source                            | Rollback Mechanism                                    |\n| --------- | ----------------------------------------- | ----------------------------------------------------- |\n| Workers   | `package.json` version + git SHA          | `wrangler deploy --rollback` or previous SHA redeploy |\n| D1 Schema | Migration files in `infra/d1-migrations/` | D1 backups (auto) + manual migration reversal         |\n| KV Data   | Not versioned; TTL-based                  | Manual restore from D1 source-of-truth                |\n| R2 Blobs  | Not versioned; date-prefixed keys         | Lifecycle rules + manual restore                      |\n\n---\n\n## 12. Local Development Stack\n\n### 12.1 Development Environment\n\n```\n┌─────────────────────────────────────────────────────────────────────────────┐\n│                         LOCAL DEV STACK                                      │\n│                                                                              │\n│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐    ┌─────────────┐   │\n│  │   pnpm      │    │  Wrangler   │    │  Miniflare  │    │  Local D1   │   │\n│  │  workspace  │◄──►│   CLI       │◄──►│  (local     │◄──►│  (sqlite)   │   │\n│  │             │    │  (dev)      │    │  Workers)   │    │             │   │\n│  └─────────────┘    └─────────────┘    └─────────────┘    └─────────────┘   │\n│         │                                                                  │\n│         ▼                                                                  │\n│  ┌────────────────────────────────────────────────────────────────────────┐│\n│  │  LOCAL SERVICES (all 26 stubs)                                         ││\n│  │  $ pnpm dev  → starts Wrangler dev server for each service             ││\n│  │  $ pnpm dev:gateway  → gateway only                                    ││\n│  │  $ pnpm dev:all  → parallel dev (requires 16GB+ RAM)                   ││\n│  └────────────────────────────────────────────────────────────────────────┘│\n│         │                                                                  │\n│         ▼                                                                  │\n│  ┌────────────────────────────────────────────────────────────────────────┐│\n│  │  LOCAL MCP BRIDGE                                                      ││\n│  │  scripts/integratewise-mcp-bridge.mjs                                  ││\n│  │  stdio → SSE bridge for local Cursor/Claude testing                    ││\n│  └────────────────────────────────────────────────────────────────────────┘│\n│         │                                                                  │\n│         ▼                                                                  │\n│  ┌────────────────────────────────────────────────────────────────────────┐│\n│  │  MOCK PROVIDERS                                                        ││\n│  │  • Nango dev mode (localhost:3009)                                     ││\n│  │  • Local Salesforce mock (msw handlers)                                ││\n│  │  • Local Stripe webhook simulator                                      ││\n│  └────────────────────────────────────────────────────────────────────────┘│\n└─────────────────────────────────────────────────────────────────────────────┘\n```\n\n### 12.2 Local Development Commands\n\n```bash\n# Root workspace commands (package.json scripts)\n{\n  \"scripts\": {\n    \"dev\": \"concurrently \\\"pnpm:dev:*\\\"\",\n    \"dev:gateway\": \"wrangler dev apps/gateway/src/index.ts --port 8787\",\n    \"dev:web\": \"pnpm --filter web dev\",\n    \"dev:mcp\": \"wrangler dev apps/mcp-server/src/index.ts --port 8788\",\n\n    \"dev:services\": \"concurrently \\\"pnpm:dev:service:*\\\"\",\n    \"dev:service:act\": \"wrangler dev services/act/src/index.ts --port 8790\",\n    \"dev:service:pipeline\": \"wrangler dev services/pipeline/src/index.ts --port 8791\",\n    \"dev:service:normalizer\": \"wrangler dev services/normalizer/src/index.ts --port 8792\",\n    \"dev:service:continuity\": \"wrangler dev services/continuity/src/index.ts --port 8793\",\n    \"dev:service:workflow\": \"wrangler dev services/workflow/src/index.ts --port 8794\",\n    \"dev:service:twin\": \"wrangler dev services/twin-orchestrator/src/index.ts --port 8795\",\n\n    \"db:migrate\": \"wrangler d1 migrations apply integratewise-spine --local\",\n    \"db:migrate:prod\": \"wrangler d1 migrations apply integratewise-spine --remote\",\n    \"db:seed\": \"tsx scripts/seed-local-db.ts\",\n\n    \"test\": \"vitest\",\n    \"test:e2e\": \"playwright test\",\n    \"test:smoke\": \"tsx scripts/smoke-test.ts\",\n\n    \"lint\": \"eslint . --ext .ts,.tsx\",\n    \"typecheck\": \"tsc -b\",\n\n    \"deploy:all\": \"pnpm -r deploy\",\n    \"deploy:gateway\": \"wrangler deploy apps/gateway/wrangler.toml\",\n    \"deploy:frontend\": \"wrangler pages deploy apps/web/dist\",\n\n    \"mcp:local\": \"node scripts/integratewise-mcp-bridge.mjs\",\n    \"mcp:test\": \"tsx scripts/test-mcp-connection.ts\"\n  }\n}\n```\n\n### 12.3 Local Configuration (wrangler.toml)\n\n```toml\n# wrangler.toml (local dev override)\n[env.development]\nname = \"integratewise-gateway-dev\"\ncompatibility_date = \"2026-06-01\"\n\n# Local D1 (sqlite file)\n[[d1_databases]]\nbinding = \"DB\"\ndatabase_name = \"integratewise-spine-local\"\ndatabase_id = \"local\"\n\n# Local KV (in-memory)\n[[kv_namespaces]]\nbinding = \"KV_DISCOVERY\"\nid = \"local-discovery\"\n\n# Local Queues (in-memory)\n[[queues.producers]]\nbinding = \"PIPELINE_QUEUE\"\nqueue = \"local-pipeline\"\n\n[[queues.consumers]]\nqueue = \"local-pipeline\"\nmax_batch_size = 10\n```\n\n---\n\n## 13. Per-App Deployment Subsets\n\n### 13.1 Deployment Dependency Graph\n\nNot all services need to deploy together. The dependency graph determines safe subset deploys.\n\n```\n┌─────────────────────────────────────────────────────────────────────────────┐\n│                     DEPLOYMENT DEPENDENCY GRAPH                              │\n│                                                                              │\n│   Tier 0 (Ingress) — No upstream deps                                        │\n│   ├── gateway          [deploy: independent]                                 │\n│   ├── webhook-ingress  [deploy: independent]                                 │\n│   └── apps/web         [deploy: independent, Pages]                          │\n│                                                                              │\n│   Tier 1 (Tenant & Sync) — Depends on Tier 0 bindings                        │\n│   ├── tenants          [deploy: after gateway]                               │\n│   ├── connector        [deploy: after tenants]                               │\n│   ├── connector-sync   [deploy: after connector + normalizer]                │\n│   ├── normalizer       [deploy: after pipeline]                              │\n│   ├── loader           [deploy: after connector + connector-sync]            │\n│   └── spine-v2         [deploy: after pipeline]                              │\n│                                                                              │\n│   Tier 2 (Projection) — Depends on Tier 1 + D1 schema                        │\n│   ├── pipeline         [deploy: after D1 migrations]                         │\n│   ├── store            [deploy: after pipeline]                              │\n│   ├── l2               [deploy: after store + intelligence]                  │\n│   ├── intelligence     [deploy: after knowledge + pipeline]                  │\n│   ├── knowledge        [deploy: after pipeline + Vectorize]                  │\n│   ├── govern           [deploy: after pipeline + workflow]                   │\n│   ├── act              [deploy: after pipeline + connector]                  │\n│   └── twin-orchestrator[deploy: after pipeline + think + knowledge]          │\n│                                                                              │\n│   Tier 3 (Runtime) — Depends on Tier 2                                       │\n│   ├── hermes           [deploy: after act + pipeline]                        │\n│   ├── triage           [deploy: after hermes + continuity]                   │\n│   ├── workflow         [deploy: after pipeline + govern]                     │\n│   ├── iw-agent-runtime [deploy: after think + mcp-connector]               │\n│   └── mcp-connector    [deploy: after gateway + pipeline]                    │\n│                                                                              │\n│   Tier 4 (Supporting) — Depends on all above                                 │\n│   ├── continuity       [deploy: after pipeline + knowledge]                  │\n│   ├── telemetry        [deploy: after all — fire-and-forget]                 │\n│   ├── think            [deploy: after pipeline + knowledge]                  │\n│   ├── agent-registry   [deploy: after connector + mcp-connector]             │\n│   ├── billing          [deploy: after tenants + pipeline]                    │\n│   ├── admin            [deploy: after tenants]                               │\n│   └── folder-watcher   [deploy: after pipeline + mcp-connector]              │\n└─────────────────────────────────────────────────────────────────────────────┘\n```\n\n### 13.2 Safe Subset Deploys\n\n| Subset           | Services                                           | Trigger              | Risk                           |\n| ---------------- | -------------------------------------------------- | -------------------- | ------------------------------ |\n| **Hotfix**       | Single service                                     | Critical bug         | Low — no schema changes        |\n| **Frontend**     | `apps/web` + `apps/mcp-server`                     | UI release           | Low — no backend deps          |\n| **Spine Update** | `pipeline` + `normalizer` + `spine-v2`             | Schema change        | Medium — D1 migration required |\n| **Capability**   | `act` + `hermes` + `workflow`                      | New provider adapter | Medium — test outbound calls   |\n| **AI Update**    | `think` + `twin-orchestrator` + `iw-agent-runtime` | Model change         | Low — swappable adapter        |\n| **Full Release** | All 26                                             | Major version        | High — full e2e required       |\n| **Infra Only**   | D1 migrations + KV config + Vectorize              | Index change         | High — backup first            |\n\n### 13.3 Deployment Verification per Subset\n\n```typescript\n// scripts/verify-deploy.ts\n\nexport interface DeployVerification {\n  subset: string;\n  services: string[];\n  checks: {\n    health: boolean; // GET /health on each service\n    bindings: boolean; // Service binding RPC ping\n    queueDepth: boolean; // No unprocessed backlog\n    d1Schema: boolean; // Schema version matches code\n    discovery: boolean; // /api/v1/discovery returns valid schema\n    mcpSmoke: boolean; // MCP connection + tool list\n    e2eHappyPath: boolean; // Full sync → propose → approve\n  };\n}\n\n  hotfix: {\n    subset: \"hotfix\",\n    services: [\"act\"], // example\n    checks: {\n      health: true,\n      bindings: true,\n      queueDepth: true,\n      d1Schema: false,\n      discovery: false,\n      mcpSmoke: false,\n      e2eHappyPath: false,\n    },\n  },\n  spine: {\n    subset: \"spine\",\n    services: [\"pipeline\", \"normalizer\", \"spine-v2\"],\n    checks: {\n      health: true,\n      bindings: true,\n      queueDepth: true,\n      d1Schema: true,\n      discovery: true,\n      mcpSmoke: false,\n      e2eHappyPath: true,\n    },\n  },\n  full: {\n    subset: \"full\",\n    services: [\"all\"],\n    checks: {\n      health: true,\n      bindings: true,\n      queueDepth: true,\n      d1Schema: true,\n      discovery: true,\n      mcpSmoke: true,\n      e2eHappyPath: true,\n    },\n  },\n};\n```\n\n---\n\n## 14. Security Boundary Annotations\n\n### 14.1 Trust Boundaries by Primitive\n\n```\n┌─────────────────────────────────────────────────────────────────────────────┐\n│  PRIMITIVE          │  TRUST LEVEL    │  ISOLATION MECHANISM                │\n├─────────────────────────────────────────────────────────────────────────────┤\n│  Workers (compute)  │  Untrusted      │  Sandboxed V8 isolate per request   │\n│  D1 (relational)    │  Trusted        │  tenant_id prefix on every index    │\n│  KV (cache)         │  Trusted        │  tenant_id in every key             │\n│  DO (stateful)      │  Trusted        │  idFromName(tenant_id + suffix)     │\n│  Queues (async)     │  Trusted        │  tenant_id in every message         │\n│  R2 (blobs)         │  Trusted        │  tenant_id in every object key      │\n│  Vectorize (vector) │  Trusted        │  tenant_id filter on every query    │\n├─────────────────────────────────────────────────────────────────────────────┤\n│  Service Bindings   │  Trusted        │  Internal network only; no external │\n│                     │                 │  ingress possible                   │\n│  Secrets (CF)       │  Critical       │  Encrypted at rest; runtime inject  │\n│  Nango Vault        │  Critical       │  Per-tenant encryption; no x-tenant │\n└─────────────────────────────────────────────────────────────────────────────┘\n```\n\n### 14.2 Security Gates by Layer\n\n| Layer          | Gate                              | Enforcement Point                    | Failure Mode                 |\n| -------------- | --------------------------------- | ------------------------------------ | ---------------------------- |\n| **Identity**   | JWT validation                    | `gateway`                            | 401 Unauthorized             |\n| **Identity**   | `tenant_id` extraction from claim | `gateway`                            | 403 Forbidden                |\n| **Identity**   | RBAC scope check                  | `tenants` service                    | 403 Forbidden                |\n| **Ingress**    | Rate limiting                     | `gateway` (Cloudflare Rate Limiting) | 429 Too Many Requests        |\n| **Ingress**    | CORS whitelist                    | `gateway`                            | 403 Forbidden                |\n| **Ingress**    | Webhook signature verification    | `webhook-ingress`                    | 401 Unauthorized             |\n| **Capability** | `WHERE tenant_id = ?`             | Every D1 query                       | 403 Forbidden (fail-loud)    |\n| **Capability** | Parameterized queries (Drizzle)   | `packages/spine-schema`              | SQL injection blocked        |\n| **Continuity** | Governance confidence gate        | `govern`                             | Proposal queued or discarded |\n| **Continuity** | HITL DO scoping                   | `govern`                             | 403 if DO ID mismatch        |\n| **Provider**   | Credential wall                   | `act` adapters                       | 401 if credentials missing   |\n| **Provider**   | Tool whitelist                    | `act` adapters                       | 403 if tool not in catalog   |\n| **All**        | Audit log write                   | `pipeline` / `telemetry`             | HALT if write fails          |\n\n---\n\n## 15. Integration Points with Adjacent Domains\n\n### 15.1 Upstream Dependencies (What This Domain Needs)\n\n| Adjacent Domain         | Interface                                 | Consumed By                       |\n| ----------------------- | ----------------------------------------- | --------------------------------- |\n| **Identity & Auth**     | JWT claims (`tenant_id`, `scopes`, `jti`) | Gateway, all service bindings     |\n| **Spine Schema**        | Drizzle ORM schema, `withTenant()` helper | All D1-accessing services         |\n| **Provider Adapters**   | Adapter registry map, credential types    | `act`, `connector-sync`           |\n| **Capability Contract** | Discovery schema, capability names        | Gateway routing, MCP tool catalog |\n\n### 15.2 Downstream Consumers (What This Domain Provides)\n\n| Adjacent Domain     | Interface                                    | Provided By                                                        |\n| ------------------- | -------------------------------------------- | ------------------------------------------------------------------ |\n| **OODA Engine**     | Queue messages (PIPELINE_QUEUE, ACT_QUEUE)   | `normalizer` → `pipeline` → `twin-orchestrator` → `govern` → `act` |\n| **Twin / ADK**      | DO state persistence, context snapshots      | `twin-orchestrator` DO                                             |\n| **Governance**      | HITL DO, audit log tables                    | `govern` service + D1 `governance_audit_log`                       |\n| **Knowledge / RAG** | Vectorize index, embedding storage           | `knowledge` service + Vectorize                                    |\n| **Observability**   | Telemetry queue, R2 blobs, Workers Analytics | `telemetry` service                                                |\n| **Ecosystem**       | Service bindings map, MCP connector endpoint | `mcp-connector`, `agent-registry`                                  |\n\n### 15.3 Cross-Domain Flow: First Connection (Revisited)\n\n```\n[Identity Domain]          [This Domain]           [Capability Domain]\n       │                          │                         │\n       │  JWT issued              │                         │\n       │─────────────────────────►│                         │\n       │                          │                         │\n       │                          │  D1: tenant init        │\n       │                          │  KV: session cache      │\n       │                          │  DO: twin provisioned   │\n       │◄─────────────────────────│                         │\n       │                          │                         │\n       │  Connect Salesforce      │                         │\n       │─────────────────────────►│                         │\n       │                          │  Queue: CONNECTOR_SYNC  │\n       │                          │  Worker: connector-sync │\n       │                          │  Worker: normalizer     │\n       │                          │  Worker: pipeline       │\n       │                          │  D1: entities written   │\n       │                          │  Vectorize: embeddings  │\n       │                          │────────────────────────►│\n       │                          │                         │  Capability: analyze_account\n       │                          │◄────────────────────────│\n       │                          │  Queue: ACT_QUEUE       │\n       │                          │  Worker: act            │\n       │                          │  Adapter: Nango         │\n       │                          │  Provider: Salesforce   │\n       │◄─────────────────────────│  Writeback: pipeline    │\n       │  Proposed insight        │                         │\n```\n\n---\n\n## 16. Operational Runbooks\n\n### 16.1 Health Check Endpoints\n\nEvery service MUST expose:\n\n```typescript\n// Standard health response\ninterface HealthResponse {\n  service: string;\n  version: string;\n  status: \"healthy\" | \"degraded\" | \"unhealthy\";\n  checks: {\n    database?: { status: string; latencyMs: number };\n    cache?: { status: string; latencyMs: number };\n    queue?: { status: string; depth: number };\n    upstream?: { status: string; services: string[] };\n  };\n  timestamp: string;\n}\n```\n\n### 16.2 Alerting Thresholds\n\n| Metric                 | Warning    | Critical   | Action                          |\n| ---------------------- | ---------- | ---------- | ------------------------------- |\n| Queue depth (PIPELINE) | > 100      | > 1000     | Scale consumer concurrency      |\n| Queue depth (ACT)      | > 50       | > 500      | Circuit break provider calls    |\n| D1 query latency p99   | > 500ms    | > 2000ms   | Check index usage, query plan   |\n| DO alarm lag           | > 30s      | > 5min     | Inspect DO hibernation, restart |\n| KV cache miss rate     | > 20%      | > 50%      | Warm cache, check TTL           |\n| Error rate (5xx)       | > 1%       | > 5%       | Rollback to previous version    |\n| R2 egress cost         | > $100/day | > $500/day | Audit blob access patterns      |\n\n---\n\n## 17. Glossary\n\n| Term                    | Definition                                                                                     |\n| ----------------------- | ---------------------------------------------------------------------------------------------- |\n| **Service Binding**     | Cloudflare Workers RPC mechanism — one Worker calls another directly over the internal network |\n| **Durable Object (DO)** | Cloudflare's stateful compute primitive with transactional storage and alarms                  |\n| **Spine**               | The Adaptive Spine — the single source of truth for entity context, written only by `pipeline` |\n| **OODA**                | Observe-Orient-Decide-Act — the decision cycle spanning Capability and Continuity layers       |\n| **Twin**                | The ambient AI reasoning engine, implemented as a DO, not a separate layer                     |\n| **Credential Wall**     | The security boundary where per-tenant provider credentials are fetched and never exposed      |\n| **DLQ**                 | Dead Letter Queue — where failed messages go after max retries                                 |\n| **SSOC**                | Stable Single Object Context — the canonical entity identification system                      |\n\n---\n\n**END OF DOCUMENT**\n\n_IntegrateWise Continuity Bridge v2.0 — Deployment Architecture and Service Topology. This document is the definitive reference for Cloudflare infrastructure primitives, service mesh topology, CI/CD, and local development. All 26 services, 5 queue types, 3 D1 databases, 6 KV namespaces, 3 R2 buckets, 1 Vectorize index, and 5 Durable Object classes are specified here._\n"}