{"slug":"strategy/product-strategy/SERVICE_ARCHITECTURE_REPORT","title":"IntegrateWise Live - Service Architecture Report","section":"strategy","sectionLabel":"Strategy","status":"unclassified","type":"document","path":"strategy/product-strategy/SERVICE_ARCHITECTURE_REPORT.mdx","bytes":40782,"description":null,"updated":null,"source":"integratewise/Integratewise-docs-wiki","content":"\n# Generated: 2026-05-25\n\n# Based on: Reading every .ts file in each service's src/ directory\n\n---\n\n## 1. ACT SERVICE (services/act/)\n\n**Files:** src/index.ts, src/act.test.ts\n**What it does:** Action Execution Layer - the final stage of the cognitive loop: Think → Govern → HITL → ACT → REPEAT. Executes approved actions through connectors, re-ingests results through pipeline, and sends outcome feedback to Think service.\n\n**Imports:** hono, hono/cors\n**Database:** Supabase (REST API for truth) + D1 (edge cache for audit_logs)\n**Tables READ:** actions, action_proposals\n**Tables WRITE:** audit_logs (D1), actions (Supabase PATCH), engagement_log (Supabase POST)\n**External APIs:** None directly (uses service bindings)\n**Routes:**\n\n- GET /health\n- POST /execute — Execute an action (MANDATORY approval token validation)\n- GET /proposals/:situation_id — Get action proposals for a situation\n\n**Service Bindings Used:** GOVERN (check), THINK (feedback), CONNECTOR (execute), PIPELINE (re-ingestion), STORE\n**Real logic?** YES - Fully implemented with governance double-check, approval token enforcement, connector execution, pipeline re-ingestion, engagement logging, and outcome learning.\n**TODO/FIXME/HACK:** None found\n\n---\n\n## 2. ADMIN SERVICE (services/admin/)\n\n**Files:** src/index.ts, src/admin.test.ts\n**What it does:** Full CRUD API for tenant management, user management, system health, newsletter subscribers, contact form submissions, support tickets, and support feedback (CSAT/NPS). Integrates with Zendesk for ticket creation.\n\n**Imports:** hono, hono/cors, @neondatabase/serverless (neon)\n**Database:** Neon PostgreSQL (DATABASE_URL)\n**Tables READ:** tenants, subscriptions, tenant_users, workspaces, connectors, iq_sessions, newsletter_subscribers, contact_submissions, support_tickets\n**Tables WRITE:** tenants, workspaces, tenant_users, subscriptions, newsletter_subscribers, contact_submissions, support_tickets\n**External APIs:** Zendesk API (ticket creation via REST)\n**Routes:**\n\n- GET /, GET /health\n- GET /v1/tenants — List all tenants with pagination\n- GET /v1/tenants/:tenantId — Get tenant details\n- POST /v1/tenants — Create tenant (with workspace + owner + trial subscription)\n- PATCH /v1/tenants/:tenantId — Update tenant\n- DELETE /v1/tenants/:tenantId — Soft/hard delete tenant\n- GET /v1/tenants/:tenantId/users — List users\n- POST /v1/tenants/:tenantId/users — Add user\n- PATCH /v1/tenants/:tenantId/users/:userId — Update user\n- DELETE /v1/tenants/:tenantId/users/:userId — Remove user\n- GET /v1/tenants/:tenantId/workspaces — List workspaces\n- POST /v1/tenants/:tenantId/workspaces — Create workspace\n- POST /v1/newsletter/subscribe, POST /v1/public/newsletter — Subscribe to newsletter\n- GET /v1/newsletter/subscribers — List subscribers (admin)\n- POST /v1/contact-submissions, POST /v1/public/contact — Submit contact form\n- GET /v1/contact-submissions — List submissions (admin)\n- POST /v1/support/tickets, POST /v1/support-tickets — Create support ticket\n- GET /v1/support-tickets — List tickets (admin)\n- GET /v1/support-tickets/:ticketId — Get ticket\n- PATCH /v1/support-tickets/:ticketId — Update ticket\n- POST /v1/support/feedback, POST /v1/support/csat, POST /v1/support/nps — Submit feedback\n\n**Real logic?** YES - Full CRUD with JWT validation, admin role checking, Zendesk integration, pagination, filtering.\n**TODO/FIXME/HACK:** None found\n\n---\n\n## 3. AGENTS SERVICE (services/agents/)\n\n**Files:** src/index.ts, src/agents.test.ts\n**What it does:** Agent Colony - multi-agent orchestration system using Cloudflare Workflows. Implements 6 specialized AI agents (Orchestrator, Research, Analyst, Writer, Planner, Executor) that collaborate to complete complex tasks. Uses Cloudflare Workers AI (@cf/meta/llama-3.1-70b-instruct).\n\n**Imports:** hono, cloudflare:workers (WorkflowEntrypoint, WorkflowEvent, WorkflowStep)\n**Database:** Supabase (agent_registry truth) + D1 (agent_colony_runs edge cache)\n**Tables READ:** agent_colony_runs (D1)\n**Tables WRITE:** agent_colony_runs (D1)\n**External APIs:** Knowledge service (search), Spine service (entity data), Think service (proposals), Govern service (approvals), Act service (execution)\n**Routes:**\n\n- GET /health\n- POST /colony/run — Start new agent colony task\n- GET /colony/:instanceId — Get colony run status\n- POST /agent/:agentType — Quick single-agent execution\n- GET /colony/history/:tenantId — Get colony run history\n\n**Service Bindings Used:** THINK, GOVERN, KNOWLEDGE\n**Real logic?** YES - Full agent implementation with AI-powered thinking, knowledge base queries, Spine entity lookups, proposal creation, governance approval, and execution through Act service.\n**TODO/FIXME/HACK:** None found\n\n---\n\n## 4. BILLING SERVICE (services/billing/)\n\n**Files:** src/index.ts, src/billing-service.ts, lib/_.ts, lib/**tests**/_.ts\n**What it does:** Subscription management, usage tracking, Stripe/RazorPay integration, webhook handling with signature verification, entitlement enforcement, SKU-based checkout, and invoice management.\n\n**Imports:** hono, hono/cors\n**Database:** Supabase (REST API - SINGLE SOURCE OF TRUTH) + D1 (edge cache) + KV (webhook replay dedup)\n**Tables READ:** subscriptions, usage_records, invoices, product_skus, tenant_subscriptions, payment_transactions\n**Tables WRITE:** subscriptions, usage_records, invoices, payment_transactions\n**External APIs:** Stripe API (checkout sessions), RazorPay API (orders)\n**Routes:**\n\n- GET /, GET /health\n- GET /v1/plans — List active plans\n- GET /v1/plans/:planId — Get plan details\n- GET /v1/subscriptions/:tenantId — Get subscription\n- POST /v1/subscriptions — Create subscription\n- PUT /v1/subscriptions/:tenantId — Update subscription\n- POST /v1/usage — Record usage\n- GET /v1/usage/:tenantId — Get usage\n- GET /v1/invoices/:tenantId — Get invoices\n- POST /webhooks/stripe — Stripe webhook (with signature verification)\n- POST /webhooks/razorpay — RazorPay webhook (with signature verification)\n- GET /v1/entitlements/:tenantId — Check entitlements\n- GET /v1/billing/plans — List product SKUs\n- POST /v1/billing/checkout — Create checkout session\n\n**Real logic?** YES - Full implementation with webhook signature verification (Stripe + RazorPay), idempotent webhook processing (KV + local cache), HMAC-based signature verification, entitlement calculation, SKU-based checkout.\n**TODO/FIXME/HACK:** None found\n\n---\n\n## 5. CONNECTOR SERVICE (services/connector/)\n\n**Files:** src/index.ts, src/sync-producer.ts, src/sync-consumer.ts, src/token-refresh.ts, src/types.ts, src/entitlement-gate.ts, src/routes/internal.ts, src/connector.test.ts\n**What it does:** Consolidated Connector Worker that merges loader + mcp-connector + store. Handles webhook reception, connector polling, MCP tool server, file storage, and action execution write-back. Routes requests to appropriate sub-service.\n\n**Imports:** hono (indirectly via sub-services), @integratewise/types, @integratewise/accelerators, @integratewise/lib\n**Database:** Supabase (REST API) + D1 (EDGE_DB for MCP) + KV (MCP_IDEMPOTENCY) + R2 (FILES)\n**Tables READ:** Various via sub-services\n**Tables WRITE:** Various via sub-services\n**External APIs:** External tool APIs via loader adapters\n**Routes:**\n\n- GET /, GET /health\n- /api/v1/connector/\\* — MCP tool server routes\n- /api/v1/loader/\\* — Loader routes (webhooks, connectors, OAuth)\n- /files/_, /upload/_ — Store routes\n- POST /api/v1/connector/execute — Execute action via connector\n- /internal/\\* — Internal routes\n- Cron: every 5 minutes — Connector polling\n\n**Queue Consumers:** PIPELINE_QUEUE, KNOWLEDGE_QUEUE\n**Real logic?** YES - Full consolidation of 3 services, with entitlement-gated sync producer, token refresh, idempotent webhook processing, and action execution with pipeline re-ingestion.\n**TODO/FIXME/HACK:** None found\n\n---\n\n## 6. CONNECTOR-SYNC SERVICE (services/connector-sync/)\n\n**Files:** src/index.ts\n**What it does:** Universal Connector Sync Service - scheduled + on-demand sync for ALL connector providers (30+ providers). Schema-driven: entity types resolved from tenant_spine_config. Supports creamy (initial), full, and delta sync phases.\n\n**Imports:** hono, hono/cors, @integratewise/types\n**Database:** Supabase (REST API for tenant_spine_config, sync_checkpoints) + KV (CONNECTOR_STATUS)\n**Tables READ:** tenant_spine_config, sync_checkpoints\n**Tables WRITE:** sync_checkpoints\n**External APIs:** None directly (queues jobs to SYNC_QUEUE)\n**Routes:**\n\n- GET /health\n- POST /api/sync/:tenantId — Trigger sync for tenant/provider\n- GET /api/status/:tenantId — Get sync status for all providers\n- GET /api/status/:tenantId/:provider — Get provider-specific status\n- Cron: every 6 hours — Sync all active connectors\n- Queue: connector-sync — Process sync jobs\n\n**Supported Providers:** hubspot, salesforce, stripe, quickbooks, chargebee, github, google-analytics, mixpanel, linear, jira, pipedrive, freshsales, close, gmail, outlook, intercom, slack, notion, zendesk, tableau, google-drive, zoho-crm, freshdesk, front, helpscout, kustomer, whatsapp-business\n**Real logic?** YES - Full schema-driven sync with entity type resolution from tenant_spine_config, cursor-based delta sync, creamy/full/delta phases, checkpoint tracking in Supabase, status tracking in KV.\n**TODO/FIXME/HACK:** None found\n\n---\n\n## 7. CONTINUITY SERVICE (services/continuity/)\n\n**Files:** src/index.ts, src/types.ts, src/couchdb.ts, src/continuity.test.ts\n**What it does:** CouchDB Memory Layer - session event write (append-only), session read (events + checkpoints), session listing (by user, status, tags), triage integration (promote to canonical layer), TTL cleanup.\n\n**Imports:** hono, hono/cors, zod, ./couchdb (CouchDB client)\n**Database:** CouchDB (session*memory*{tenantId} databases)\n**Tables READ:** session containers, session events, continuity checkpoints (all CouchDB)\n**Tables WRITE:** session containers, session events, continuity checkpoints (all CouchDB)\n**External APIs:** None (uses KNOWLEDGE service binding for triage promotion)\n**Routes:**\n\n- GET /health\n- POST /v1/continuity/events — Write event (core)\n- GET /v1/continuity/sessions — List sessions\n- GET /v1/continuity/sessions/:id — Read session + events\n- POST /v1/continuity/sessions/:id/resume — Resume session\n- POST /v1/continuity/sessions/:id/close — Close session\n- POST /v1/continuity/sessions/:id/triage — Triage session\n- GET /v1/continuity/sessions/:id/events — Get session events\n- GET /v1/continuity/checkpoints/:sessionId — Get checkpoints\n- Cron: TTL cleanup — Delete expired sessions\n\n**Queue Consumers:** TASKS_QUEUE (async triage promotion)\n**Real logic?** YES - Full CouchDB implementation with Mango queries, view queries, TTL management, checkpoint creation, session lifecycle (active → closed → triage), and async triage promotion via queue.\n**TODO/FIXME/HACK:** None found\n\n---\n\n## 8. GATEWAY SERVICE (services/gateway/)\n\n**Files:** src/index.ts, src/gateway.test.ts\n**What it does:** Single Entry Point for ALL requests into the workspace. Validates JWTs, resolves tenant context, injects trusted headers, applies rate limiting, and routes requests to the correct service. Implements the full routing table for the entire system.\n\n**Imports:** hono (indirectly), imports admin/billing/tenants apps directly\n**Database:** Supabase (REST API for tenant resolution) + KV (RATE_LIMITS, SESSIONS, CONNECTOR_STATUS, SIGNAL_CACHE, METRICS)\n**Tables READ:** None directly (delegates to sub-services)\n**Tables WRITE:** None directly\n**External APIs:** None (pure routing layer)\n**Routes:** (Full routing table - 40+ route mappings)\n\n- /api/v1/billing/\\* → INTERNAL_BILLING (billing app)\n- /api/v1/tenants/\\* → INTERNAL_TENANTS (tenants app)\n- /api/v1/support/\\* → INTERNAL_SUPPORT (admin app)\n- /api/v1/analytics/\\* → BFF (workflow)\n- /api/v1/agents/\\* → INTELLIGENCE (intelligence)\n- /api/v1/connectors/\\* → CONNECTOR\n- /api/v1/connector/\\* → CONNECTOR\n- /api/v1/loader/\\* → CONNECTOR\n- /api/v1/pipeline/\\* → PIPELINE\n- /api/v1/intelligence/\\* → INTELLIGENCE\n- /api/v1/cognitive/\\* → INTELLIGENCE or BFF (various)\n- /api/v1/knowledge/\\* → KNOWLEDGE\n- /api/v1/workspace/\\* → BFF (workflow)\n- /api/v1/l2/\\* → L2\n- /ws, /sse, /stream → BFF\n- /admin/\\* → INTERNAL_ADMIN (admin app)\n- /oauth/\\* → INTERNAL_TENANTS (tenants app)\n- /webhooks/\\* → WEBHOOK_INGRESS or CONNECTOR\n\n**Real logic?** YES - Full gateway implementation with JWT validation, tenant context resolution, rate limiting, CORS, path rewriting, webhook routing (provider-specific), connector sync status fallback, and service binding routing.\n**TODO/FIXME/HACK:** None found\n\n---\n\n## 9. GOVERN SERVICE (services/govern/)\n\n**Files:** src/index.ts, src/types.ts, src/policies.ts, src/workflow.ts, src/audit.ts, src/governance-engine.ts, src/policies.test.ts\n**What it does:** Policy engine and approval workflows. Manages governance policies, checks if actions can be executed, handles approve/reject workflows with approval tokens, and maintains audit trails.\n\n**Imports:** hono, hono/cors, hono/logger, hono/secure-headers, zod\n**Database:** Neon PostgreSQL (DATABASE_URL via policies.ts/workflow.ts/audit.ts)\n**Tables READ:** governance_policies, governance_audit_log, governance_workflow_items (inferred from functions)\n**Tables WRITE:** governance_policies, governance_audit_log, governance_workflow_items\n**External APIs:** None\n**Routes:**\n\n- GET /health\n- GET /v1/policies — List policies\n- GET /v1/policies/:id — Get policy\n- POST /v1/policies — Create policy\n- PUT /v1/policies/:id — Update policy\n- DELETE /v1/policies/:id — Deactivate policy\n- POST /v1/check — Check if action can be executed\n- POST /v1/approve — Approve action\n- POST /v1/reject — Reject action\n- GET /v1/pending — Get pending actions\n- GET /v1/audit — Get audit log\n- GET /v1/audit/summary — Get audit summary\n\n**Real logic?** YES - Full governance engine with policy CRUD, action checking with role-based access, approval workflow with approval tokens (HMAC-signed), audit logging with correlation IDs, and internal service authentication.\n**TODO/FIXME/HACK:** None found\n\n---\n\n## 10. HERMES SERVICE (services/hermes/)\n\n**Files:** src/index.ts, src/executor.ts, src/orchestrator.ts, src/stream.ts, src/types.ts\n**What it does:** Orchestration Intelligence Worker - executes approved actions via n8n workflows or Durable Objects, provides SSE streaming of execution status, and manages workflow deployment to n8n.\n\n**Imports:** hono, hono/cors, zod\n**Database:** KV (EXECUTION_META, RATE_LIMIT) + Durable Objects (STREAM_HUB)\n**Tables READ:** None (uses KV for task metadata)\n**Tables WRITE:** None (uses KV for task metadata)\n**External APIs:** n8n API (workflow execution, deployment, health check)\n**Routes:**\n\n- GET /health\n- POST /execute — Execute approved action\n- GET /stream/:taskId — SSE stream of execution status\n- POST /orchestrate — Orchestrate workflow\n- POST /workflows — Deploy workflow to n8n\n- PATCH /workflows/:id/active — Activate/deactivate workflow\n- GET /tasks/:taskId — Get task status\n\n**Queue Consumers:** OUTCOMES_QUEUE (execute_task messages)\n**Real logic?** YES - Full execution engine with n8n integration, Durable Object SSE streaming, task lifecycle management, workflow deployment, and queue-based async execution.\n**TODO/FIXME/HACK:** None found\n\n---\n\n## 11. INTELLIGENCE SERVICE (services/intelligence/)\n\n**Files:** src/index.ts, src/signal-analyzer.ts, src/intelligence.test.ts\n**What it does:** Consolidated Intelligence Worker that merges think + act + govern + agents + cognitive-brain. Routes requests to appropriate sub-service. Processes signal queue messages with TypeScript-native signal analysis (via SignalAnalyzer from @integratewise/types), manages HITL approval workflows, and handles intelligence event processing.\n\n**Imports:** Imports think/act/govern/agents sub-services directly, SignalAnalyzer from @integratewise/types\n**Database:** Supabase (REST API for actions, signals) + D1 (entity360_cache)\n**Tables READ:** entity360_cache (D1), actions, signals (Supabase)\n**Tables WRITE:** actions (Supabase), signals (Supabase)\n**External APIs:** OpenRouter (optional, via OPENROUTER_API_KEY for S7 sanity checks)\n**Routes:** (Delegates to sub-services based on path)\n\n- /health\n- /act/\\* → actApp\n- /policies/_, /approve/_, /audit/\\* → governApp\n- /colony/_, /agents/_ → agentsApp\n- /v1/cognitive/_, /v1/brainstorm, /v1/twin/_, /v1/insights → cognitiveBrain\n- Default → thinkWorker\n\n**Queue Consumers:** signals, intelligence-events, intelligence-act, ops-dlq\n**Real logic?** YES - Full consolidation with signal processing, Python AI analysis integration, Govern→HITL approval enforcement (KT Note Rule 5), action proposal creation, and outcome learning.\n**TODO/FIXME/HACK:** None found\n\n---\n\n## 12. KNOWLEDGE SERVICE (services/knowledge/)\n\n**Files:** src/index.ts, src/chunking/_.ts, src/embedding/_.ts, src/search/_.ts, src/synthesis/_.ts, src/iq-hub.ts, src/memory-consolidator.ts, src/triage-bot.ts, src/embeddings.ts, src/services/_.ts, server/src/_.ts\n**What it does:** Semantic search, document chunking, embedding management, triage bot (Cloudflare AI), memory consolidation, IQ Hub for MCP sessions, and knowledge ingestion pipeline.\n\n**Imports:** hono, @neondatabase/serverless (neon), zod, hono/cors, @integratewise/connector-utils, OpenAI/OpenRouter APIs\n**Database:** Neon PostgreSQL (DATABASE_URL) + Supabase (optional for spine config)\n**Tables READ:** triage_results, document_chunks, session_embeddings, knowledge_documents, topics, triage_sessions (inferred)\n**Tables WRITE:** triage_results, document_chunks, session_embeddings, knowledge_documents, topics\n**External APIs:** OpenAI API (embeddings), OpenRouter API (embeddings), Cloudflare AI (triage bot)\n**Routes:**\n\n- GET /health\n- POST /knowledge/search — Semantic search (vector/keyword/hybrid)\n- POST /knowledge/search/sessions — Session search\n- POST /knowledge/ingest — Ingest document\n- POST /knowledge/embed/session — Embed session summary\n- GET /v1/knowledge/inbox — Triage inbox (pending/deferred items)\n- PATCH /v1/knowledge/triage/:id — Approve/discard/defer triage item\n- GET /v1/triage/approved — Get approved triage items\n- POST /v1/triage/session — Triage session (Cloudflare AI)\n- /iq/\\* — IQ Hub (MCP session capture → Triage → Consolidation)\n- Cron: memory consolidation — Consolidate approved triage items\n\n**Queue Consumers:** TASKS_QUEUE (immediate consolidation triggers)\n**Real logic?** YES - Full implementation with document chunking, embedding generation (OpenAI/OpenRouter), vector search (pgvector), hybrid search, triage bot (Cloudflare AI), memory consolidation, and IQ Hub for MCP session capture.\n**TODO/FIXME/HACK:**\n\n- Line 2050: \"Tenant-scoped consumer (CONSOLIDATED_AGENT_TODO D.19): skip messages without tenant_id\"\n- Line 273 (chunker.ts): \"TODO: list preservation (extractLists) – currently unused by the chunker flow.\"\n\n---\n\n## 13. L2 SERVICE (services/l2/)\n\n**Files:** src/index.ts, src/l2.test.ts\n**What it does:** L2 Cognitive Layer Backend - read/write service over the spine for AI-derived insights, recommendations, and decision tracking. Uses KV for persistence when available, falls back to demo data.\n\n**Imports:** hono, hono/cors\n**Database:** KV (L2_INSIGHTS namespace)\n**Tables READ:** KV (insights, recommendations, dismissed items)\n**Tables WRITE:** KV (insights, recommendations, decisions, dismissed items)\n**External APIs:** None\n**Routes:**\n\n- GET /health, GET /api/v1/l2/health\n- GET /api/v1/l2/insights — Get AI-derived insights for a view\n- GET /api/v1/l2/recommendations — Get recommendations\n- POST /api/v1/l2/recommendations/:id/decision — Record approve/reject decision\n- POST /api/v1/l2/events — Ingest events (dismiss actions)\n\n**Real logic?** PARTIAL - Has real KV-backed logic for insights, recommendations, decisions, and dismissals. Falls back to demo data when KV is unavailable. The demo data is seeded, not hardcoded per se.\n**TODO/FIXME/HACK:** None found\n\n---\n\n## 14. LOADER SERVICE (services/loader/)\n\n**Files:** src/index.ts, src/pipeline.ts, src/pipeline-stages.ts, src/types.ts, src/lib/_.ts, src/handlers/_.ts, src/jobs/_.ts, scripts/_.ts\n**What it does:** Schema-Driven Extraction - handles creamy layer sync (Phase 1), background sync (Phase 2 - needed/delta), and scheduled polling. Extracts data from connectors based on tenant_spine_config schema.\n\n**Imports:** hono, zod, @neondatabase/serverless (neon), @integratewise/connectors (universalSync), @integratewise/types, token-refresh\n**Database:** Neon PostgreSQL (DATABASE_URL for tenant_spine_config, sync_jobs) + KV (CONNECTOR_STATUS for job state)\n**Tables READ:** tenant_spine_config, sync_jobs, tenant_onboarding_state\n**Tables WRITE:** sync_jobs, tenant_onboarding_state\n**External APIs:** External tool APIs via universalSync connector adapters\n**Routes:**\n\n- POST /internal/creamy — Start Creamy layer sync (Phase 1)\n- GET /internal/creamy/:jobId — Get Creamy job status\n- POST /internal/background-sync — Start background sync (Phase 2)\n- POST /internal/sync — General sync trigger\n- POST /internal/webhook/:provider — Webhook handler\n- GET /internal/status/:tenantId — Sync status\n- Cron: every 5 minutes — Scheduled connector polling\n\n**Queue Consumers:** PIPELINE_QUEUE, KNOWLEDGE_QUEUE\n**Real logic?** YES - Full schema-driven extraction with token refresh, universal connector sync, creamy/full/delta phases, pipeline queue integration, and job state management in KV.\n**TODO/FIXME/HACK:** None found\n\n---\n\n## 15. MCP-CONNECTOR SERVICE (services/mcp-connector/)\n\n**Files:** src/index.ts, src/handlers/tools.ts, src/handlers/coda-proxy.ts, src/lib/\\*.ts, src/index.test.ts\n**What it does:** MCP Tool Server - provides 12 tools for Knowledge Bank operations and Figma integration. Handles AI session memory capture with entity linking, auto-embedding, and triage bot integration.\n\n**Imports:** hono, hono/cors, zod, @integratewise/connector-utils, ./lib/logging, ./handlers/tools, ./handlers/coda-proxy\n**Database:** D1 (DB for ai_sessions, ai_session_memories) + KV (MCP_IDEMPOTENCY)\n**Tables READ:** ai_sessions, ai_session_memories (D1)\n**Tables WRITE:** ai_sessions, ai_session_memories (D1)\n**External APIs:** Figma API (via FIGMA_ACCESS_TOKEN), Knowledge service (via binding for embedding/triage)\n**Routes:**\n\n- GET /, GET /health\n- GET /config/mcp-server — MCP server configuration\n- GET /tools — Tool discovery\n- POST /invoke — Tool invocation\n- GET /test/figma — Test Figma connectivity\n- POST /v1/mcp/save_session_memory — Save AI session memory\n- POST /v1/mcp/capture_session — Enhanced session capture with entity linking\n- GET /v1/mcp/sessions — List captured sessions\n\n**Tools Available:** kb.write_session_summary, kb.write_article, kb.get_artifact, kb.list_recent, kb.search, kb.topic_upsert, kb.topic_list, figma.get_file, figma.get_components, figma.get_node, figma.export_image, figma.get_comments\n**Real logic?** YES - Full MCP tool server with 12 tools, Figma integration, session memory capture, entity linking, auto-embedding via Knowledge service binding, and triage bot integration.\n**TODO/FIXME/HACK:** None found\n\n---\n\n## 16. NORMALIZER SERVICE (services/normalizer/)\n\n**Files:** src/index.ts, src/types.ts, src/normalize.ts, src/dlq.ts, src/identity-mapper.ts, src/idempotency.ts, src/normalizer-accelerator.ts, src/schemas/index.ts, src/identity-resolution-api.ts, src/normalize.test.ts\n**What it does:** 8-Stage Pipeline (KT Note §7) - mandatory normalization pipeline that ALL data must pass through before becoming canonical truth in the Spine. Stages: Analyze → Classify → Filter → Refine → Extract → Validate → Sanity → Sectorize.\n\n**Imports:** @integratewise/types (resolveTenantAdaptiveSchema, SchemaAccessor, etc.), @supabase/supabase-js, ./identity-resolution-api\n**Database:** Supabase (REST API + @supabase/supabase-js for quarantine, identity resolution) + KV (SCHEMA_CACHE)\n**Tables READ:** pipeline_quarantine, spine_schema_registry, identity resolution tables\n**Tables WRITE:** pipeline_quarantine (Supabase)\n**External APIs:** OpenRouter (optional, via OPENROUTER_API_KEY for S7 sanity checks)\n**Routes:**\n\n- GET /health\n- GET /api/v1/pipeline/status — Pipeline status\n- /v1/identity/\\* — Identity Resolution API\n\n**Queue Consumers:** PIPELINE_QUEUE (8-stage processing), DLQ_QUEUE (dead letters)\n**Real logic?** YES - Full 8-stage pipeline with schema-driven filtering, field normalization, canonical mapping, sanity scoring (≥70 required), quarantine management, identity resolution, and DLQ handling with retries.\n**TODO/FIXME/HACK:** None found\n\n---\n\n## 17. PIPELINE SERVICE (services/pipeline/)\n\n**Files:** src/index.ts, src/pipeline.test.ts\n**What it does:** Consolidated Pipeline Worker that merges normalizer + spine-v2. The ONLY service with Spine write credentials. Handles 8-stage pipeline processing and Spine SSOT reads/writes.\n\n**Imports:** @supabase/supabase-js, @integratewise/types, imports normalizer and spine-v2 sub-services\n**Database:** Supabase (createClient for spine queries, REST API) + D1 (CACHE_DB) + KV (CACHE, SIGNAL_CACHE, METRICS) + R2 (SPINE_STORAGE)\n**Tables READ:** spine_schema_registry, entities (public), plus all schema-specific tables (spine.account, sales.deal, etc.)\n**Tables WRITE:** All schema-specific tables via spine-v2\n**External APIs:** None (uses service bindings)\n**Routes:**\n\n- GET /health\n- GET /api/v1/pipeline/status — Pipeline status\n- GET /api/v1/spine/entities — List entities (with filtering, pagination)\n- GET /api/v1/spine/entities/:entityType/:id — Get single entity\n- POST /api/v1/spine/:entityType — Write entities to spine\n- GET /api/v1/spine/schema/:entityType — Get schema fields\n- GET /api/v1/entity360/:entityType/:id — Entity 360 view\n- POST /api/v1/entity360/batch — Entity 360 batch\n- POST /api/write — Generic write endpoint (used by Act service re-ingestion)\n\n**Queue Consumers:** PIPELINE_QUEUE (routes to normalizer), ACCELERATOR_QUEUE\n**Real logic?** YES - Full spine routing with 100+ entity type → schema.table mappings, upsert logic, completeness scoring, Entity 360 assembly, and schema field observation.\n**TODO/FIXME/HACK:** None found\n\n---\n\n## 18. SPINE-V2 SERVICE (services/spine-v2/)\n\n**Files:** src/index.ts, src/entity360-assembler.ts, src/spine-v2.test.ts\n**What it does:** Spine SSOT (Single Source of Truth) - entity type → schema.table router with 100+ entity type mappings. Handles spine-routed writes, entity 360 assembly, and schema field observation.\n\n**Imports:** @supabase/supabase-js, @integratewise/types, ./entity360-assembler\n**Database:** Supabase (createClient with schema routing) + KV (CACHE) + D1 (CACHE_DB) + R2 (SPINE_STORAGE)\n**Tables READ:** All schema-specific tables (spine.account, sales.deal, cs.renewal, etc.) + public.entities (fallback)\n**Tables WRITE:** All schema-specific tables via upsert/insert + public.entities (fallback)\n**External APIs:** None\n**Routes:**\n\n- GET /health\n- POST /v1/spine/:entityType — Write entities (schema-routed)\n- GET /v1/spine/entities — List entities\n- GET /v1/spine/entities/:entityType/:id — Get single entity\n- GET /v1/spine/entity360/:entityType/:id — Entity 360 view\n- POST /v1/spine/entity360/batch — Entity 360 batch\n\n**Real logic?** YES - Full entity type routing with 100+ mappings across 15+ schemas (spine, sales, marketing, revops, cs, support, eng, product, finance, legal, hr, sc, svc, bizops, it, procurement, industry\\_\\*), entity 360 assembly, and schema field observation.\n**TODO/FIXME/HACK:** None found\n\n---\n\n## 19. STORE SERVICE (services/store/)\n\n**Files:** src/index.ts, src/store.test.ts\n**What it does:** File storage service using D1 + R2. Handles file uploads, R2 storage, processing pipeline, and triggers Knowledge ingestion.\n\n**Imports:** hono, zod, hono/cors, hono/secure-headers\n**Database:** Supabase (REST API for files table) + D1 (edge cache, not directly used in index.ts) + R2 (R2_BUCKET for file storage)\n**Tables READ:** files (Supabase)\n**Tables WRITE:** files (Supabase)\n**External APIs:** Knowledge service (via binding for document ingestion)\n**Routes:**\n\n- GET /\n- POST /store/files — Initiate file upload\n- PUT /store/files/:id/upload — Upload file content to R2\n- GET /store/files/:id — Get file details\n- GET /store/files — List files\n- POST /v1/store/upload — Gateway-facing multipart upload\n\n**Real logic?** YES - Full file upload flow with R2 storage, Supabase metadata tracking, and async Knowledge ingestion trigger via service binding.\n**TODO/FIXME/HACK:** None found\n\n---\n\n## 20. TENANTS SERVICE (services/tenants/)\n\n**Files:** src/index.ts, src/types.ts, src/context.ts, src/oauth-configs.ts, src/flow-c-config.ts\n**What it does:** Multi-tenant context resolution, tenant CRUD, invitation system, SSO/OAuth configuration, connector management, workspace management, and tenant management API.\n\n**Imports:** hono, hono/cors, @neondatabase/serverless (neon), @integratewise/connectors (getSerializableCatalog), @integratewise/types, @integratewise/lib/crypto\n**Database:** Neon PostgreSQL (DATABASE_URL) + Supabase (REST API for tenant_spine_config)\n**Tables READ:** tenants, subscriptions, tenant_users, workspaces, connectors, tenant_spine_config, tenant_onboarding_state\n**Tables WRITE:** tenants, workspaces, tenant_users, connectors, tenant_spine_config, tenant_onboarding_state\n**External APIs:** None directly (triggers connector-sync via service binding)\n**Routes:**\n\n- GET /health\n- GET /context — Get tenant context\n- GET /resolve/:slug — Resolve tenant from slug\n- GET /limits/:plan — Get plan limits\n- GET /v1/tenants/:tenantId — Get tenant details\n- PATCH /v1/tenants/:tenantId — Update tenant settings\n- GET /v1/tenants/:tenantId/workspaces — List workspaces\n- POST /v1/tenants/:tenantId/workspaces — Create workspace\n- DELETE /v1/tenants/:tenantId/workspaces/:workspaceId — Delete workspace\n- GET /v1/tenants/:tenantId/users — List users\n- POST /v1/tenants/:tenantId/invitations — Invite user\n- POST /v1/invitations/accept — Accept invitation\n- GET /v1/tenants/:tenantId/connectors — List connectors\n- POST /v1/tenants/:tenantId/connectors — Register connector\n- DELETE /v1/tenants/:tenantId/connectors/:provider — Disconnect connector\n- GET /oauth/:provider — OAuth redirect\n- GET /oauth/:provider/callback — OAuth callback\n- POST /api/v1/tenants/:tenantId/spine-config — Update spine config\n\n**Service Bindings Used:** CONNECTOR_SYNC (trigger initial hydration)\n**Real logic?** YES - Full tenant management with plan limits, invitation system with tokens, OAuth flow (HubSpot, Salesforce, GitHub, Slack, Stripe, Notion), connector registration with initial hydration trigger, and spine config management.\n**TODO/FIXME/HACK:**\n\n- Line 66: \"TODO: Implement D1 buffer initialization\" (in initializeD1Buffer function)\n\n---\n\n## 21. THINK SERVICE (services/think/)\n\n**Files:** src/index.ts, src/engine.ts, src/actions.ts, src/ai-provider.ts, src/context.ts, src/fusion.ts, src/narrative.ts, src/semantic-lookup.ts, src/tenant-config.ts, src/twin-triggers.ts, src/entity360-client.ts, src/cognitive-brain.ts, src/cognitive-routes/_.ts, src/use-cases/_.ts, src/\\*.test.ts\n**What it does:** Think Engine (Layer 2) - signal analysis, situation detection, entity analysis, brainstorm layer, success intelligence routing, digital twin, and cognitive brain. Routes signals to appropriate sections based on entity type.\n\n**Imports:** hono, zod, hono/cors, hono/secure-headers, @integratewise/types, SignalEngine, tenant-config\n**Database:** Supabase (REST API for signals, situations, action_proposals) + D1 (edge cache)\n**Tables READ:** signals, situations, action_proposals, entity360_cache (D1)\n**Tables WRITE:** action_proposals (via Supabase)\n**External APIs:** OpenRouter (optional, via OPENROUTER_API_KEY for S7 sanity checks), OpenAI/OpenRouter (via OPENAI_API_KEY/OPENROUTER_API_KEY)\n**Routes:**\n\n- GET /health\n- GET /v1/signals — Signals feed\n- GET /v1/success/intelligence — Success intelligence (schema-filtered)\n- GET /v1/situations — Situations feed\n- POST /v1/think/analyze — Analyze entity\n- GET /v1/accelerator/health-score — Health score accelerator\n- GET /v1/accelerator/engagement — Engagement accelerator\n- GET /v1/accelerator/risk — Risk accelerator\n- POST /v1/propose — Create action proposal\n- POST /v1/outcome/feedback — Outcome feedback (learning)\n- /v1/twin/\\* — Digital twin routes (via cognitive-brain)\n- /v1/brainstorm — Brainstorm routes (via cognitive-brain)\n- /v1/insights/\\* — Insights routes (via cognitive-brain)\n- /v1/cognitive/\\* — Cognitive routes (via cognitive-brain)\n\n**Real logic?** YES - Full implementation with signal routing to 9 success intelligence sections (renewals, risks, support, usage, technical_health, tasks, stakeholders, integrations, insights), role-based lens filtering, schema-aware entity analysis, and cognitive brain integration.\n**TODO/FIXME/HACK:** None found\n\n---\n\n## 22. WEBHOOK-INGRESS SERVICE (services/webhook-ingress/)\n\n**Files:** src/index.ts, src/handlers/slack-workflow.ts\n**What it does:** Receives webhooks from external systems (HubSpot, Salesforce, Stripe, GitHub, Slack) and broadcasts real-time updates. Verifies webhook signatures, deduplicates deliveries, forwards to pipeline, and broadcasts via Stream Gateway.\n\n**Imports:** hono, hono/cors, @integratewise/types (resolveEntityTypeAlias)\n**Database:** KV (WEBHOOK_LOG, WEBHOOK_SECRETS, CONNECTOR_STATUS)\n**Tables READ:** KV (tenant mappings)\n**Tables WRITE:** KV (webhook logs, delivery dedup)\n**External APIs:** None (receives webhooks, doesn't call external APIs)\n**Routes:**\n\n- GET /health\n- POST /webhooks/hubspot — HubSpot webhook (with signature verification)\n- POST /webhooks/salesforce — Salesforce webhook\n- POST /webhooks/stripe — Stripe webhook (with signature verification)\n- POST /webhooks/github — GitHub webhook (with signature verification)\n- POST /webhooks/slack-workflow — Slack Workflow Builder step\n- POST /webhooks/slack/interactivity — Slack interactivity payloads\n\n**Queue Consumers:** PIPELINE_QUEUE (forward webhook data to 8-stage normalization)\n**Real logic?** YES - Full webhook handling with provider-specific signature verification (HMAC for HubSpot/Stripe/GitHub, Slack signing secret), idempotent delivery via KV, tenant resolution from portal IDs/installation IDs, and pipeline forwarding.\n**TODO/FIXME/HACK:** None found\n\n---\n\n## 23. WORKFLOW SERVICE (services/workflow/)\n\n**Files:** src/index.ts, src/views.ts, src/analytics.ts, src/stream-gateway.ts, src/tenant-spine-config.ts, src/durable-objects/hitl.ts, src/transformers/\\*.ts, src/workflow.test.ts, src/analytics.test.ts\n**What it does:** Backend-for-Frontend (BFF) - workspace runtime, HITL approval queue, analytics, real-time streaming (SSE/WebSocket via Durable Objects), spine initialization, connector registration, schema templates, and onboarding state management.\n\n**Imports:** hono (indirectly via stream-gateway), @integratewise/types, @integratewise/connectors, Durable Objects (HITLGate, SignalStreamDO, PresenceDO, RoomDO)\n**Database:** Supabase (REST API + createClient for spine queries, schema registry) + D1 (ANALYTICS_DB for analytics) + KV (CONNECTION_META, RATE_LIMIT, CONNECTOR_STATUS)\n**Tables READ:** spine_schema_registry, connectors, tenant_spine_config, tenant_onboarding_state, entities (public + schema-specific)\n**Tables WRITE:** tenant_spine_config, tenant_onboarding_state, spine_schema_registry\n**External APIs:** OpenRouter (optional, via OPENROUTER_API_KEY for S7 sanity checks)\n**Routes:**\n\n- GET /health\n- POST /api/v1/workspace/initialize — Initialize workspace\n- GET /api/v1/workspace/tenant-config — Get tenant spine config\n- GET /api/v1/workspace/link-knowledge-ui — Knowledge UI read policy\n- GET /api/v1/workspace/ai-context — AI context URLs\n- POST /api/v1/workspace/python/analyze — Python analyze proxy\n- GET /api/v1/workspace/projection/:dept — Spine projection\n- GET /api/v1/workspace/readiness — Readiness buckets\n- POST /api/v1/workspace/register-connector — Register connector\n- GET /api/v1/workspace/dashboard — Dashboard\n- GET /api/v1/workspace/entities — Entity list\n- GET /api/v1/workspace/goals — Goals and metrics\n- GET /api/v1/cognitive/hitl/queue — HITL approval queue\n- POST /api/v1/cognitive/hitl/queue — Approve/deny action\n- GET /api/v1/cognitive/hitl/history — Approval history\n- /hitl/\\* — Durable Object HITL endpoints\n- GET /api/v1/cognitive/audit — Audit trail\n- GET /stream/events — SSE stream (legacy)\n- /stream/_, /ws/_, /sse/\\* — Stream gateway (Durable Objects)\n- /analytics/_, /api/v1/analytics/_ — Analytics endpoints\n- GET /api/v1/cognitive/evidence/\\* — Evidence trail\n- POST /api/v1/workspace/initialize-spine — Initialize adaptive spine\n- GET /api/v1/workspace/schema-template — Schema template preview\n- GET /api/v1/workspace/onboarding-state — Onboarding state\n- POST /api/v1/workspace/complete-onboarding — Complete onboarding\n- POST /api/v1/workspace/hydrate-connectors — Hydrate connectors\n- GET /api/v1/workspace/progress — Sync progress (JSON/SSE)\n- GET /api/v1/workspace/completeness — Spine completeness scoring\n- /api/v1/workspace/cs/_, /api/v1/workspace/csm/_, /api/v1/workspace/tam/_, /api/v1/workspace/success/_ — Workspace L1 routes\n- GET /api/v1/workspace/navigation — Navigation\n- GET /api/v1/workspace/space/:type — Space\n- GET /api/v1/workspace/view/:viewId — View\n- GET /api/v1/workspace/hydration/manifest — Hydration manifest\n- GET /api/v1/workspace/connectors — Workspace connectors\n\n**Durable Objects:** HITLGate (approval gate), SignalStreamDO (real-time signals), PresenceDO (user presence), RoomDO (collaboration rooms)\n**Queue Consumers:** ACT_QUEUE (action execution)\n**Real logic?** YES - Full BFF implementation with 30+ endpoints, Durable Objects for real-time streaming and HITL, analytics aggregation, schema template generation, onboarding state management, and workspace L1/L2 routing.\n**TODO/FIXME/HACK:**\n\n- Line 2327: \"TODO: Connect to Supabase Realtime and forward events\"\n\n---\n\n## SUMMARY\n\n### Total Services: 23\n\n### Service Categories:\n\n1. **Gateway/Entry:** Gateway (single entry point)\n2. **Data Ingestion:** Connector, Connector-Sync, Loader, Webhook-Ingress, MCP-Connector, Store\n3. **Data Processing:** Normalizer (8-stage pipeline), Pipeline (consolidated normalizer+spine), Spine-V2 (SSOT router)\n4. **Intelligence:** Think, Act, Govern, Agents, Intelligence (consolidated), Hermes\n5. **Knowledge:** Knowledge, Continuity (CouchDB memory)\n6. **Workspace Runtime:** Workflow (BFF), L2 (Cognitive Layer)\n7. **Infrastructure:** Admin, Tenants, Billing\n\n### Database Usage:\n\n- **Supabase PostgreSQL:** Primary truth database (most services)\n- **Neon PostgreSQL:** Admin, Tenants, Knowledge, Govern (via @neondatabase/serverless)\n- **CouchDB:** Continuity (session memory)\n- **D1 (Cloudflare):** Edge cache across most services\n- **KV (Cloudflare):** Caching, rate limiting, idempotency, status tracking\n- **R2 (Cloudflare):** File storage (Store, Spine-V2)\n\n### Consolidated Workers (v3.6 Architecture):\n\n- **Connector** = Loader + MCP-Connector + Store\n- **Pipeline** = Normalizer + Spine-V2\n- **Intelligence** = Think + Act + Govern + Agents + Cognitive-Brain\n\n### External API Integrations:\n\n- Stripe (billing)\n- RazorPay (billing)\n- Zendesk (support tickets)\n- Figma (design tools via MCP)\n- n8n (workflow orchestration via Hermes)\n- OpenAI/OpenRouter (AI embeddings)\n- Python Intelligence Service (signal analysis)\n- Cloudflare AI (triage bot)\n\n### Real vs Placeholder:\n\n- **ALL 23 services have REAL logic** - none are pure placeholders\n- The L2 service has some demo seed data but real KV-backed logic\n- All TODO/FIXME comments are minor (6 total across entire codebase)\n\n### TODO/FIXME/HACK Found:\n\n1. `tenants/src/index.ts:66` — \"TODO: Implement D1 buffer initialization\"\n2. `knowledge/src/index.ts:2050` — \"Tenant-scoped consumer (CONSOLIDATED_AGENT_TODO D.19)\"\n3. `knowledge/src/chunking/chunker.ts:273` — \"TODO: list preservation (extractLists)\"\n4. `workflow/src/index.ts:2327` — \"TODO: Connect to Supabase Realtime and forward events\"\n5. `loader/src/handlers/ai-relay.ts:4` — \"TODO: Move AIRelayWebhookSchema to @integratewise/types\"\n6. `webhook-ingress/src/handlers/slack-workflow.ts:60,69` — \"TODO: Store/query mapping in tenant_spine_config\"\n"}