{"slug":"architecture/one-full-prompt","title":"IntegrateWise Continuity Bridge — One Full Prompt to Replit","section":"architecture","sectionLabel":"Architecture","status":"unclassified","type":"document","path":"architecture/one-full-prompt.mdx","bytes":32660,"description":null,"updated":null,"source":"integratewise/Integratewise-docs-wiki","content":"\n> **Status: SUPERSEDED BUILD HANDOFF.** This prompt must not be used as a current\n> implementation source. Its product name, Descope authority, UI layers and\n> storage assumptions are historical. Start from\n> [`ARCHITECTURE_LOCK.md`](./ARCHITECTURE_LOCK.md) and\n> [`CONSOLIDATED_PRODUCT_PLATFORM_CONTRACT_v1.2.md`](./CONSOLIDATED_PRODUCT_PLATFORM_CONTRACT_v1.2.md).\n\n> **Canonical Reference:** [CANONICAL_PLATFORM_ARCHITECTURE.md](../architecture/CANONICAL_PLATFORM_ARCHITECTURE.md)  \n> _This document is downstream of the canonical architecture. Refer to the canonical source for current truth._\n\n> **Original handoff claim (superseded):** This was once treated as a build\n> handoff. It no longer overrides the frozen architecture.\n\n---\n\n## 1. The One-Liner (What We Are Building)\n\n**The OODA Engine for Business Continuity.**\n\nA multi-tenant continuity bridge that preserves organizational context, memory, governance, and execution across all tools, humans, and AI agents — through one stable continuity contract. Consumers (humans, ChatGPT, Claude, Cursor) connect once. The Bridge connects to everything else.\n\n**Doctrine:** _Truth you own. AI you rent. Approval in between._\n\n**Core Loop (OODA):** Every tool, every user, every AI agent runs the same four-phase decision cycle:\n\n1. **Observe** — Read from the Spine (unified context)\n2. **Orient** — Assemble Entity360 + Memory + Knowledge\n3. **Decide** — Propose action, score confidence, govern\n4. **Act** — Execute approved action, writeback to Spine, compound memory\n\n**The product is not a platform.** It is a **Continuity Bridge**. The category is **The Operational Continuity Platform**.\n\n---\n\n## 2. What Exists (The Live Repo)\n\nYou are continuing from the `integratewise-live/` codebase. It contains:\n\n- **19 of 26 services** as Cloudflare Workers (with `wrangler.toml`)\n- **Vite + React frontend** (`apps/web`) with shadcn/ui\n- **MCP connector** (`services/mcp-connector/`) with test endpoint\n- **Massive connector catalog** (`packages/connectors/` — 50+ providers)\n- **Normalizer** (`services/normalizer/`) with NA0-NA5 pipeline skeleton\n- **Governance** (`services/govern/`) with confidence gate\n- **Think** (`services/think/`) — cognitive brain engine\n- **Supabase deeply entangled** as current relational store\n- **Marketing page bloat** (50+ pages in frontend that belong on Webflow)\n\n**You do NOT start from zero.** You complete, cleanup, and deploy what exists.\n\n---\n\n## 3. The Cleanup (Do This First)\n\nRun these commands immediately. Do not build new features until this is done.\n\n```bash\n# 1. Delete marketing page bloat (moves to Webflow, not in app)\nrm -rf apps/web/src/components/landing/\nrm -rf apps/web/src/components/landing/v2/\nrm -rf apps/web/src/components/landing/v3/\nrm -rf apps/web/src/components/marketing-site/\nrm -rf apps/web/src/components/site/\nrm -rf apps/web/src/components/marketing/\nrm -rf apps/web/src/components/landing/ui/\n\n# 2. Delete migration artifacts\nrm -rf apps/web/src/shims/\nrm -rf apps/web/test-results/\nrm -f apps/web/SHIM_MODULES_CREATED.md\n\n# 3. Delete legacy Node.js servers (Worker is canonical)\nrm -rf services/knowledge/server/\n\n# 4. Delete empty/minimal packages\nrm -rf packages/hub/\nrm -rf packages/website/\n\n# 5. Delete old architecture docs (superseded by this prompt)\nrm -f ARCHITECTURE_OVERVIEW.md ARCHITECTURE_OVERVIEW_CORRECTED.md \\\n  BUSINESS_OPS_SCHEMA_PLAN.md CONNECTOR_CS_SUPPORT_REPORT.md \\\n  CONNECTOR_IMPLEMENTATION_REPORT.md IMPLEMENTATION_SUMMARY.md \\\n  REPOSITORY_MAP.md REPOSITORY_TREE.txt CLAUDE.md AGENTS.md \\\n  WORK_COMPLETE_SUMMARY.md bitbucket-pipelines.yml \\\n  bitbucket-pipelines-production.yml\n\n# 6. Delete Clerk traces (auth migration incomplete)\nrm -f sql-migrations/flow-a/029_clerk_auth_schema.sql\n\n# 7. Remove .env from git (SECURITY P0)\ngit rm --cached .env 2>/dev/null || true\necho \".env\" >> .gitignore\necho \".env.*\" >> .gitignore\n\n# 8. Remove build artifacts from git\nfind . -name \"tsconfig.tsbuildinfo\" -exec git rm --cached {} \\;\necho \"*.tsbuildinfo\" >> .gitignore\n\n# 9. Consolidate duplicate packages\n# packages/tenancy/ → merge into services/tenants/ or packages/types/\n# packages/webhooks/ → merge into services/webhook-ingress/\n# packages/connector-contracts/ + packages/connector-utils/ → merge into packages/connectors/\n# packages/db/ (supabase.ts) → migrate to packages/lib/db-gate.ts, then delete\n\n# 10. Commit\ngit add -A\ngit commit -m \"chore: canonical cleanup — delete marketing bloat, migration artifacts, Clerk traces, .env, build artifacts. Consolidate duplicate packages.\"\n```\n\n---\n\n## 4. The Architecture (4 Layers, 26 Services)\n\n### 4.1 Conceptual Layers (Trust Boundaries)\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, Cursor), apps, tools                                     | One MCP connection, one JWT, one web workbench         |\n| **Continuity Bridge** | Public interface: identity, auth, discovery, projections, capabilities, governance entry, events | Identity, Discovery, Projections, Capabilities, Events |\n| **Continuity Kernel** | Internal context substrate: Spine, Memory, Knowledge, Context, Governance, Workflow              | Nothing. Consumers never import internal topology.     |\n| **Provider Fabric**   | Replaceable external execution: SaaS, databases, APIs, queues, agents                            | Nothing. Entirely behind the Kernel.                   |\n\n### 4.2 The 26 Services (Physical Topology)\n\nAll 26 are Cloudflare Workers with `wrangler.toml`. All wired into `gateway` as service bindings.\n\n#### Tier 0 — Ingress & Routing\n\n| Service           | Worker Name             | Purpose                                                          | Binding Name      |\n| ----------------- | ----------------------- | ---------------------------------------------------------------- | ----------------- |\n| `gateway`         | `integratewise-gateway` | Single entry; JWT validation; tenant routing; rate-limit         | N/A (entry)       |\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 Name     |\n| ---------------- | ------------------- | --------------------------------------- | ---------------- |\n| `tenants`        | `iw-tenants`        | Multi-tenant context, RBAC, plan limits | `TENANTS`        |\n| `connector-sync` | `iw-connector-sync` | Orchestrates connector sync             | `CONNECTOR_SYNC` |\n| `normalizer`     | `iw-normalizer`     | 8-stage NA0–NA5 pipeline                | `NORMALIZER`     |\n\n#### Tier 2 — Projection & Rendering\n\n| Service             | Worker Name            | Purpose                                    | Binding Name        |\n| ------------------- | ---------------------- | ------------------------------------------ | ------------------- |\n| `pipeline`          | `iw-pipeline`          | **ONLY writer to the Spine**               | `PIPELINE`          |\n| `twin-orchestrator` | `iw-twin-orchestrator` | **OODA Engine** — persistent per-user DO   | `TWIN_ORCHESTRATOR` |\n| `l2`                | `iw-l2`                | Department × industry overlay projections  | `L2`                |\n| `intelligence`      | `iw-intelligence`      | Analytics, insights, signal generation     | `INTELLIGENCE`      |\n| `knowledge`         | `iw-knowledge`         | Knowledge base, docs, semantic search      | `KNOWLEDGE`         |\n| `govern`            | `iw-govern`            | Governance rules engine, approval gates    | `GOVERN`            |\n| `store`             | `iw-store`             | Persistence for projections                | `STORE`             |\n| `act`               | `iw-act`               | Action execution / write-back to providers | `ACT`               |\n\n#### Tier 3 — Capability Runtime & Orchestration\n\n| Service            | Worker Name        | Purpose                                    | Binding Name       |\n| ------------------ | ------------------ | ------------------------------------------ | ------------------ |\n| `hermes`           | `iw-hermes`        | Message queue + execution engine (DO)      | `HERMES`           |\n| `triage`           | `iw-triage`        | Confidence routing + active-memory decay   | `TRIAGE`           |\n| `workflow`         | `iw-workflow`      | Durable orchestration (pause, retry, saga) | `WORKFLOW`         |\n| `iw-agent-runtime` | `iw-agent-runtime` | MCP-compliant AI agent execution           | `IW_AGENT_RUNTIME` |\n| `mcp-connector`    | `iw-mcp-connector` | MCP bridge: external agents → scoped Spine | `MCP_CONNECTOR`    |\n\n#### Tier 4 — Supporting\n\n| Service          | Worker Name         | Purpose                                      | Binding Name     |\n| ---------------- | ------------------- | -------------------------------------------- | ---------------- |\n| `agent-registry` | `iw-agent-registry` | Catalog of available agents                  | `AGENT_REGISTRY` |\n| `billing`        | `iw-billing`        | Usage tracking + plan enforcement            | `BILLING`        |\n| `admin`          | `iw-admin`          | Platform admin, tenant mgmt                  | `ADMIN`          |\n| `loader`         | `iw-loader`         | Cold-start pre-loader, Nango webhook handler | `LOADER`         |\n| `folder-watcher` | `iw-folder-watcher` | DO filesystem watcher                        | `FOLDER_WATCHER` |\n| `continuity`     | `iw-continuity`     | Memory consolidation + decay                 | `CONTINUITY`     |\n| `telemetry`      | `iw-telemetry`      | Traces, metrics, observability               | `TELEMETRY`      |\n| `think`          | `iw-think`          | LLM reasoning orchestration                  | `THINK`          |\n| `connector`      | `iw-connector`      | OAuth callback handler (Nango)               | `CONNECTOR`      |\n| `spine-v2`       | `iw-spine-v2`       | Spine normalization & graph                  | `SPINE_V2`       |\n\n### 4.3 The 17-Layer Physical Stack (0–16)\n\n| #   | Layer                       | Services                                                           | Storage                                                 |\n| --- | --------------------------- | ------------------------------------------------------------------ | ------------------------------------------------------- |\n| 0   | **Tenant Lifecycle**        | `tenants`, `loader`, `admin`                                       | D1 `tenants`, `tenant_spine_config`                     |\n| 1   | **Customer Ecosystem**      | `connector`, `connector-sync`, `agent-registry`                    | Nango vault, `connectors` table                         |\n| 2   | **Surface Layer**           | `apps/web`, `apps/mcp-server`                                      | Cloudflare Pages, R2 assets                             |\n| 3   | **Gateway Layer**           | `gateway`                                                          | N/A — pure routing                                      |\n| 4   | **Identity & Organization** | `tenants` (RBAC)                                                   | D1 `rbac_roles`, `rbac_permissions`                     |\n| 5   | **Continuity Bridge**       | `connector-sync`, `normalizer`, `mcp-connector`, `webhook-ingress` | D1 `sync_jobs`, `normalizer_state`, KV Discovery cache  |\n| 6   | **Adaptive Spine**          | `pipeline`                                                         | D1 `entities`, `relationships`, `spine_audit_log`       |\n| 7   | **Context Assembly**        | `intelligence`, `knowledge`                                        | Vectorize, AI Search, KV context cache                  |\n| 8   | **Shared Memory**           | `continuity`, `triage`                                             | D1 `memory` (active/staging/archived), KV decay         |\n| 9   | **Capability Engine**       | `iw-agent-runtime`, `think`                                        | OpenRouter API, KV model config                         |\n| 10  | **Governance Layer**        | `govern`                                                           | D1 `governance_audit_log`, `action_proposals`           |\n| 11  | **Capability Runtime**      | `hermes`, `workflow`, `act`, `mcp-connector`                       | Durable Objects, Queues (`ACT_QUEUE`, `PIPELINE_QUEUE`) |\n| 12  | **Projection Registry**     | `l2`, `store`                                                      | D1 `projections`, `projection_registry`                 |\n| 13  | **Registry Layer**          | `agent-registry`, `intelligence`                                   | D1 `capability_registry`, `endpoint_registry`, KV cache |\n| 14  | **Continuity Engine**       | `continuity`, `twin-orchestrator`                                  | D1 `continuity_graph`, KV session handoffs              |\n| 15  | **Data & Infrastructure**   | `telemetry`, `folder-watcher`                                      | D1 `audit_logs`, R2 telemetry, Workers Analytics        |\n| 16  | **Endpoint Registry**       | `gateway` (serves), `intelligence` (updates)                       | KV + D1 `endpoint_registry`                             |\n\n**Cross-cutting:** Security (WAF, TLS, CF Secrets, Zero Trust), Observability, Reliability (idempotency, retries, DLQ, backpressure), Compliance (audit & lineage, retention, encryption, tenant isolation).\n\n---\n\n## 5. The OODA Engine (Core Mental Model)\n\nEvery tool, every user, every AI agent runs this loop:\n\n```\nOBSERVE ──► ORIENT ──► DECIDE ──► ACT ──► (memory compounds) ──► OBSERVE...\n```\n\n### Phase 1: OBSERVE\n\n- **What:** Ingest signals from webhooks, sync polls, user actions, file changes\n- **Who:** `webhook-ingress`, `connector-sync`, `folder-watcher`\n- **Output:** Raw payload → `PIPELINE_QUEUE`\n\n### Phase 2: ORIENT\n\n- **What:** Assemble Entity360 + Memory + Knowledge into context\n- **Who:** `normalizer` (NA0–NA5), `intelligence` (Context Assembly), `knowledge` (RAG)\n- **Output:** Normalized entity + enriched context\n\n### Phase 3: DECIDE\n\n- **What:** Twin reasons, proposes action, governance scores confidence\n- **Who:** `twin-orchestrator` (OODA engine), `govern` (confidence gate)\n- **Rules:**\n  - ≥ 0.85 → Auto-approve → `ACT_QUEUE`\n  - 0.70 – 0.85 → My Desk review → human approves/rejects\n  - < 0.70 → Discard → `spine_audit_log` (discard reason)\n\n### Phase 4: ACT\n\n- **What:** Execute approved action, writeback to Spine, update memory\n- **Who:** `act` (execution), `integration-router` (provider adapter), `continuity` (memory promotion)\n- **Output:** Outcome written to Spine → compounding memory for next loop\n\n**The Twin runs this loop continuously (hourly cron) for every user.** The workbench runs it on every interaction. Every connected tool runs it on every event. The difference is speed: tool = milliseconds, Twin = minutes, user = seconds.\n\n---\n\n## 6. The Two Planes (North / South)\n\n```\nConsumers → [Gateway] → Spine → [Integration Router] → Provider Tools\n             (North)                   (South)\n```\n\n**North Plane (Ingress):** `gateway` + `mcp-connector` (inbound MCP). All consumers enter here. JWT validation. Tenant routing. Discovery. Rate-limit.\n\n**South Plane (Egress):** `act` + Integration Router. Only service that touches external APIs. Adapter selection: Nango (OAuth-mature), MCP (AI-native), Native (direct REST). Entity360 context injected on outbound.\n\n**Rule:** Neither plane talks to the other except **through the Spine**.\n\n---\n\n## 7. MCP Pool (Bidirectional, First-Class)\n\n### 7.1 Inbound MCP Pool (North Plane)\n\n**Endpoint:** `mcp.integratewise.ai/v1/mcp` (SSE/stdio)\n**Role:** AI assistants (ChatGPT, Claude, Cursor, Perplexity) connect **to us** to read scoped Spine/Memory.\n**Primary ingress:** This is the **primary** front door. Traditional SaaS webhooks are secondary.\n\n**Server implementation:**\n\n```typescript\n// services/mcp-connector/src/index.ts (inbound MCP server)\n\n\nconst app = new Hono();\n\n// SSE endpoint for MCP transport\napp.post(\"/sessions\", async (c) => {\n  const jwt = await verifyGatewayJWT(c.req.header(\"Authorization\"));\n  const tenantId = jwt.tenant_id; // FROM JWT CLAIM, never client payload\n  const scope = await getMCPToolCatalog(tenantId); // from Discovery\n  return c.json({ sessionId, tools: scope, readOnly: true });\n});\n\napp.post(\"/invoke\", async (c) => {\n  const { sessionId, tool, params } = await c.req.json();\n  const sessionTenant = await resolveTenantFromSession(sessionId); // KV lookup\n  const jwtTenant = c.get(\"jwt\").tenant_id;\n\n  // P0: Cross-tenant session reuse = 403 (fail-loud, not 404)\n  if (jwtTenant !== sessionTenant) {\n    return c.json({ error: \"Cross-tenant access denied\" }, 403);\n  }\n\n  // Read-only default. Write requires governance approval.\n  const result = await executeCapability(tenantId, tool, params);\n  await auditLog({ via: \"mcp\", tenantId, tool, outcome: result });\n  return c.json(result);\n});\n\n// P0: Every endpoint requires Bearer JWT\n// P0: x-tenant-id extracted from JWT, never from client payload\n// P0: Tool catalog filtered by Discovery (tenant sees only their capabilities)\n// P0: Every invocation logged to spine_audit_log\n```\n\n**Consumer Config (the ONLY MCP entry users need):**\n\n```json\n{\n  \"mcpServers\": {\n    \"integratewise\": {\n      \"type\": \"sse\",\n      \"url\": \"https://mcp.integratewise.ai/v1/mcp\",\n      \"headers\": {\n        \"Authorization\": \"Bearer ${input:integratewise_jwt}\"\n      },\n      \"description\": \"IntegrateWise Continuity Bridge — OODA Engine for Business Continuity\"\n    }\n  },\n  \"inputs\": [\n    {\n      \"id\": \"integratewise_jwt\",\n      \"type\": \"promptString\",\n      \"description\": \"IntegrateWise Gateway JWT — from Settings → API Keys\",\n      \"password\": true\n    }\n  ]\n}\n```\n\n**Key rule:** One entry. Not 21. Not 5. One. The Bridge routes to 20+ providers internally.\n\n### 7.2 Outbound MCP Pool (South Plane)\n\nInside Integration Router. We connect **to provider MCP servers** (Salesforce MCP, Slack MCP, GitHub MCP). Entity360 context injected before outbound call.\n\n---\n\n## 8. Frontend: One Full UI (Not Marketing Pages)\n\n### 8.1 Tech Stack\n\n- **Vite** (not Next.js, not Replit)\n- **React 18** + **TypeScript**\n- **shadcn/ui** (installed, used in `components/ui/`)\n- **Tailwind CSS**\n- **Deploy target:** Cloudflare Pages (`wrangler.toml` in `apps/web/`)\n- **API client:** `@integratewise/sdk` (packages/sdk/) — capability-first, NEVER direct Supabase calls\n\n### 8.2 What to Build (8 Lenses, Not 12)\n\nThe workbench has **8 projections** (lenses). Not 12 departments. The 12 department directories in `components/domains/` map to these 8:\n\n| Canonical Lens   | Maps From (existing dirs)                       | Workbench Route           |\n| ---------------- | ----------------------------------------------- | ------------------------- |\n| **Sales**        | `domains/sales/`, `domains/salesops/`           | `/workbench/sales`        |\n| **CS**           | `domains/account-success/`                      | `/workbench/cs`           |\n| **Finance**      | `domains/finance/`                              | `/workbench/finance`      |\n| **Executive**    | `domains/revops/`, `domains/bizops/`            | `/workbench/executive`    |\n| **Architecture** | `domains/product-engineering/`                  | `/workbench/architecture` |\n| **Operations**   | `domains/business-ops/`, `domains/procurement/` | `/workbench/operations`   |\n| **Personal**     | `domains/personal/`                             | `/workbench/personal`     |\n| **Developer**    | `domains/it-admin/`                             | `/workbench/developer`    |\n\n**Delete or merge:** `marketing/`, `student-teacher/`, `service/` (map to CS or Operations).\n\n### 8.3 Core Components to Build/Wire\n\n| Component        | Purpose                                              | Data Source                                        |\n| ---------------- | ---------------------------------------------------- | -------------------------------------------------- |\n| `Entity360`      | Complete view of any entity (account, deal, contact) | Gateway SDK → `spine.entity.get`                   |\n| `TwinRail`       | Inline proposal panel (right side)                   | Gateway SDK → `twin.propose`                       |\n| `ProposalCard`   | Approve/Modify/Dismiss                               | Gateway SDK → `governance.decide`                  |\n| `SignalFeed`     | Real-time notifications                              | WebSocket or polling → `signal.list`               |\n| `MyDesk`         | Approval queue (0.70–0.85 proposals)                 | Gateway SDK → `proposal.list` + `proposal.approve` |\n| `CommandPalette` | Quick actions, search                                | Gateway SDK → `discovery` + `capability.invoke`    |\n| `DomainSidebar`  | Role-based navigation                                | Gateway SDK → `discovery.projections`              |\n\n### 8.4 Hooks to Implement\n\n```typescript\n// hooks/useDiscovery.ts\n// Called once on app load. Cached 5 minutes.\n// Returns: identity, tenant, workspace, projections, capabilities, features, limits\n\n// hooks/useEntity360.ts\n// Fetches complete entity view across all connected tools\n\n// hooks/useTwinProposal.ts\n// Submits to Twin, receives proposal with confidence\n\n// hooks/useCapability.ts\n// Generic capability invoker (NEVER direct Supabase)\n```\n\n---\n\n## 9. The Swappable Layers (7× Agnostic Moat)\n\nEvery infrastructure layer is swappable. The Integration Manager owns the adapter selection.\n\n| Dimension            | Default                       | Swappable To                         | Adapter File                     |\n| -------------------- | ----------------------------- | ------------------------------------ | -------------------------------- |\n| **Frontend**         | Vite + React (Pages)          | Next.js, Electron, React Native, iOS | `packages/lib/ui-adapter.ts`     |\n| **Auth**             | Gateway JWT + API Keys        | Clerk, Stack, Descope, Auth0         | `packages/lib/auth-adapter.ts`   |\n| **Relational Store** | Supabase PostgreSQL (current) | Neon, RDS, PlanetScale, HyperDrive   | `packages/lib/db-gate.ts`        |\n| **Cache**            | Cloudflare KV                 | Redis, Upstash, DynamoDB             | `packages/lib/cache-adapter.ts`  |\n| **Queue**            | Cloudflare Queues             | SQS, RabbitMQ, Kafka                 | `packages/lib/queue-adapter.ts`  |\n| **AI / Model**       | OpenRouter (gpt-5-mini)       | Claude, Grok, Gemini, Ollama         | `packages/lib/openrouter.ts`     |\n| **Deployment**       | Cloudflare Workers            | Vercel, Lambda, Fly.io, K8s          | `packages/lib/deploy-adapter.ts` |\n\n**Current state:** `packages/lib/` already has `db-gate.ts`, `openrouter.ts`, `cache.ts`. Build the adapter interfaces to formalize swappability.\n\n---\n\n## 10. Database Schema (D1 + PostgreSQL via HyperDrive)\n\n### 10.1 D1 (Operational + Cache)\n\n- `spine_entities` — Canonical entities (see §14 of FINAL_E2E_SYSTEM.md)\n- `governance_audit_log` — Immutable approval decisions\n- `memory` — Active/staging/archived tiers\n- `tenant_spine_config` — Per-tenant config\n- `endpoint_registry` — Living API contract\n- `rbac_roles`, `rbac_permissions` — Access control\n\n**Rule:** Every query has `WHERE tenant_id = ?`. Cross-tenant = 403 (fail-loud).\n\n### 10.2 PostgreSQL (Relational Graph — via HyperDrive or Supabase)\n\n- The **Spine relational graph** (complex relationships, historical analytics) runs on PostgreSQL.\n- Accessed through `packages/lib/db-gate.ts` (adapter pattern).\n- Current: Supabase. Future: HyperDrive, Neon, RDS.\n- **Migration path:** D1 for hot paths (<10ms), PostgreSQL for analytical queries and complex joins.\n\n---\n\n## 11. Security Posture (P0 Blockers — Close Before Live)\n\n| #   | Vulnerability                    | Fix                                                                               | Owner Service             |\n| --- | -------------------------------- | --------------------------------------------------------------------------------- | ------------------------- |\n| 1   | **Cross-tenant data leak**       | `WHERE tenant_id = ?` on every query. 403 fail-loud.                              | ALL services              |\n| 2   | **Tenant-id spoofing**           | Extract `tenant_id` from JWT claim only. Strip client-provided `x-tenant-id`.     | `gateway`                 |\n| 3   | **Tenant middleware no-op**      | Enforce service bindings carry `tenant_id` implicitly.                            | `gateway`                 |\n| 4   | **HITL DO global singleton**     | `idFromName(tenant_id + user_id)`, not `\"global\"`                                 | `govern`                  |\n| 5   | **Invitation cross-tenant scan** | Add `WHERE tenant_id = ?` to invitation lookup                                    | `tenants`                 |\n| 6   | **Hardcoded secrets**            | Move to Cloudflare Secrets. Rotate any leaked.                                    | `admin`                   |\n| 7   | **`.env` committed**             | `git rm --cached`, add `.gitignore`, scan history                                 | `admin`                   |\n| 8   | **SQL injection**                | Use Drizzle ORM or parameterized queries. No raw string concat.                   | `continuity`, `knowledge` |\n| 9   | **MCP-JWT bypass**               | Require `Authorization: Bearer <jwt>` on `/tools`, `/invoke`, `/mcp`, `/sessions` | `mcp-connector`           |\n| 10  | **Auth root thrashing**          | Freeze on API Keys + JWT. Remove Clerk/Stack/Descope imports.                     | `gateway`                 |\n\n**Audit rule:** Audit write failure stops the operation. No silent drops.\n\n---\n\n## 12. GTM Motion (Sign Up → Live in < 5 Minutes)\n\n### 12.1 Distribution\n\n- **Primary:** MCP app in ChatGPT Store, Claude connectors, Perplexity apps\n- **Secondary:** Web landing (Webflow, not in app) → `app.integratewise.ai`\n- **Tertiary:** Direct API signup for enterprise\n\n### 12.2 Signup Flow\n\n1. User clicks \"Add IntegrateWise\" in ChatGPT\n2. MCP connects to `mcp.integratewise.ai/v1/mcp`\n3. User authenticates (Google/GitHub/email) → Gateway issues JWT\n4. Schema AI (gpt-5-mini) hydrates tenant: entity types, relationships, RBAC\n5. D1 partition created, `tenant_spine_config` row, memory tables\n6. User sees Discovery response: \"Connect Salesforce\" (one-click Nango)\n7. **Target:** signup → workspace < 5 min; first tool < 10 min; normalizer p99 < 2s\n\n### 12.3 Customer-Zero Kill Shot\n\n- **Two apps:** Salesforce + Slack, read-only, approval-required, 90-day retention\n- **Win:** VP CS answers \"what's our risk?\" without opening Salesforce or Slack\n- **Land-and-expand:** 3rd app = \"enable\" toggle, not a project\n\n---\n\n## 13. Build Order (What to Do in Sequence)\n\n### Week 1: Cleanup + Foundation\n\n- [ ] Run all cleanup commands (§3)\n- [ ] Close P0 #1–10 (security)\n- [ ] Wrap all Supabase queries behind `db-gate.ts`\n- [ ] Delete `packages/supabase/` (after migration)\n- [ ] Verify `pnpm -r build` passes\n- [ ] Verify `pnpm -r typecheck` passes\n\n### Week 2: Core Services\n\n- [ ] Build `twin-orchestrator` DO (OODA engine)\n- [ ] Build `hermes` (message queue wrapper around Queues)\n- [ ] Build `triage` (confidence routing)\n- [ ] Wire `twin-orchestrator` → `govern` → `act` → Spine\n- [ ] Implement `useDiscovery`, `useEntity360`, `useTwinProposal` hooks\n\n### Week 3: MCP + Frontend\n\n- [ ] Harden MCP-JWT on all inbound endpoints\n- [ ] Build `TwinRail`, `ProposalCard`, `SignalFeed` components\n- [ ] Delete all marketing pages from frontend\n- [ ] Consolidate 12 departments → 8 lenses\n- [ ] Deploy frontend to Cloudflare Pages\n\n### Week 4: Integration + Polish\n\n- [ ] Build Integration Manager (adapter selection layer)\n- [ ] Test end-to-end: Salesforce → Normalizer → Spine → Twin → Govern → Act → Writeback\n- [ ] Performance: p99 < 2s for normalizer, < 10ms for Entity360 cache hit\n- [ ] Deploy all services via `wrangler deploy`\n- [ ] CI/CD: GitHub Actions → typecheck → test → deploy\n\n---\n\n## 14. Reference Documents (In Repo)\n\n| Document              | Purpose                              | Location                           |\n| --------------------- | ------------------------------------ | ---------------------------------- |\n| `FINAL_E2E_SYSTEM.md` | Canonical architecture specification | `/docs/FINAL_E2E_SYSTEM.md`        |\n| `L1_REALITY_CHECK.md` | Audit of actual codebase vs. canon   | `/docs/L1_REALITY_CHECK.md`        |\n| `REALITY_AUDIT.md`    | Detailed repo structure analysis     | `/docs/REALITY_AUDIT.md`           |\n| `OODA_ENGINE.md`      | OODA loop formalization              | **To be created from this prompt** |\n\n---\n\n## 15. The One Command to Deploy\n\n```bash\n# After cleanup and build:\npnpm -r build\npnpm deploy:gateway\npnpm deploy:mcp-server\npnpm deploy:workbench\npnpm deploy:workers  # all 26\n\n# Verify:\ncurl https://mcp.integratewise.ai/v1/health\ncurl https://api.integratewise.ai/api/v1/discovery -H \"Authorization: Bearer $JWT\"\n```\n\n---\n\n## 16. What NOT to Build\n\n| Do NOT Build                             | Why                                             | Where It Goes Instead                                                                                                          |\n| ---------------------------------------- | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |\n| Marketing pages (landing, pricing, blog) | Bloats app, slows deploy                        | Webflow (`integratewise.ai`)                                                                                                   |\n| Marketplace UI                           | We list in THEIR marketplaces (ChatGPT, Claude) | Not our app                                                                                                                    |\n| Partner portal                           | Not needed for CZ                               | Future, not now                                                                                                                |\n| Per-app OAuth flows                      | Nango handles this                              | `services/connector/`                                                                                                          |\n| Frontend → direct DB calls               | Violates architecture                           | Always through Gateway SDK                                                                                                     |\n| Clerk / Stack Auth                       | Auth root thrashing                             | Gateway JWT (internal) + Descope (canonical external identity + outbound authorization authority); Nango dormant compatibility |\n| Next.js migration                        | Already on Vite                                 | Vite is canonical                                                                                                              |\n| 12 department lenses                     | Canon locks 8                                   | Merge 12 → 8                                                                                                                   |\n\n---\n\n## 17. Closing Statement\n\n**Build the OODA Engine.**\n\nObserve everything. Orient into context. Decide with confidence. Act with governance. Compound memory every cycle. Deploy to Cloudflare. One MCP connection. One JWT. One Bridge.\n\n**The last auth for endless continuity.**\n\n---\n\n_Version: 1.0.0-CANONICAL_  \n_Date: 2026-07-02_  \n_Status: LOCKED — all §14 conflicts resolved_  \n_Handoff target: Replit agent for live deployment_\n"}