Skip to main content

BizOSaaS Lean Rebuild — Master Task Tracker

Updated: March 18, 2026 (Route Conflict Fixed, CORS, Social Auth, WWW Redirects Fixed) Source: Consolidated from bizosaas_platform_rebuild_analysis.md, conversational_commerce_strategy.md, comprehensive_gap_analysis.md, ecosystem_growth_ecommerce_strategy.md, llm_strategy_recommendation.md, extended_llm_strategy.md, end_to_end_onboarding_flow.md, onboarding_multi_tenant_gap_analysis.md, implementation_plan.md, openclaw_multimedia_analysis.md, service_catalog.md, service_tier_strategy.md, and prior task.md + Legacy Code Audit (March 13, 2026). Strategy: "5 containers, 2 languages, 1 database engine." Tech Replacements: OpenTelemetry/Grafana → SigNoz | n8n/Temporal → BullMQ | Vault → Infisical | EspoCRM → Built-in CRM | WordPress/Wagtail → Next.js + Payload CMS (recommended) | Neo4j → pgvector + recursive CTEs | Lago → RETAINED for Metered/Usage Billing alongside Stripe/Razorpay (see Phase 9A)

⚠️ Architecture Decisions Pending Review:

  • Payload CMS vs Next.js MDX: Recommend Payload CMS (TypeScript, PostgreSQL-native, multi-tenant) for internal brands + future client websites. See Phase 9B.
  • Lago Metered Billing: Retain Lago OR use Stripe Meter API. Decision required before Phase 9A.
  • Senior AI Assistant (OpenClaw+): Research complete — recommend proceeding as Phase 10 product (see analysis below).

🟢 Phase 0: Observability Migration (SigNoz)

Goal: Replace the fragmented Grafana/Loki/Prometheus/Tempo/OTel stack with unified SigNoz. Source: bizosaas_platform_rebuild_analysis.md §E, llm_strategy_recommendation.md, extended_llm_strategy.md

  • Infrastructure Setup
    • Finalize infrastructure/docker-compose.signoz.yml (ClickHouse, SigNoz Query Service, Frontend)
    • Deploy SigNoz to Dokploy
    • Configure OTLP endpoint in .env.example
    • Create infrastructure/configs/otel-collector-signoz.yaml with SigNoz exporter
  • Service Instrumentation
    • Update apps/ai-service to export traces and metrics via OTLP to SigNoz
    • Integrate LLMCostTracker with Event Bus (for real-time telemetry)
    • Instrument Next.js app with OpenTelemetry SDK → SigNoz
    • Instrument BullMQ workers with trace propagation
  • Dashboards & Alerts
    • Create Master Platform Dashboard in SigNoz (request latency, error rates, throughput)
    • Port LLM Cost Tracking metrics to SigNoz (from extended_llm_strategy.md Task 6)
    • Create Agent Performance Dashboard (per-agent latency, success rate)
    • Setup critical alerts (5xx spike, worker queue depth, DB connection pool)
  • Remove Legacy Stack
    • Remove Grafana/Loki/Prometheus/Tempo configs from v1-archive
    • Remove old OTel collector configs that target the legacy stack

🏗️ Phase 1: Foundation & Monorepo

Goal: Establish the lean monorepo structure with shared packages and single docker-compose. Source: bizosaas_platform_rebuild_analysis.md §3-5, comprehensive_gap_analysis.md §1

  • Fix platform_settings table missing error
  • Refactor MFA setup to Gold Standard (native Better-Auth)
  • Debug MFA 500 error during enablement
    • Verify database schema (user columns and two_factor table uses text IDs)
    • Fix authClient baseURL for local testing
    • Refactor lib/auth.ts plugin imports
    • Resolve auth sign-in/email 500 Internal Server Error (origin-aware baseURL)
  • Admin Portal Stability Hardening
    • Fixed media table missing tenant_id causing 500s in Admin Dashboard
    • Synchronized startup.mjs with Gold Standard MFA requirements
    • Verified auth.ts clock-skew tolerance (window: 1)
  • Fix seed_users_v2.ts column names and seed production data
  • Push all fixes to GitHub
  • Initial monorepo audit and rebuild plan
  • Create v2-rebuild Git branch
  • Move existing V1 codebase to v1-archive
  • Initialize Turborepo Monorepo (pnpm workspaces)
  • Shared Packages
    • Setup packages/ui (shadcn/ui + Tailwind v4)
    • Setup packages/db (PostgreSQL + Drizzle ORM)
    • Setup packages/config (shared ESLint, TSConfig, Tailwind config)
    • Setup packages/types (shared TypeScript types)
    • Setup packages/api-client (shared tRPC/Axios client)
  • Infrastructure
    • Create the ONE infrastructure/docker-compose.yml (5 services: web, ai-service, workers, postgres, redis)
    • Configure Caddy/Traefik reverse proxy with auto-SSL
    • Create infrastructure scripts: dev.sh, deploy.sh, migrate.sh, seed.sh, backup.sh
  • Secrets Migration
    • Migrate secrets from HashiCorp Vault to Infisical (managed)
    • Implement InfisicalAdapter (replacing Vault)
    • Update get_secret_service dependency to support Infisical
    • Refactor McpInstallationService to use SecretService instead of hardcoded VaultAdapter
  • Database Consolidation
    • Consolidate all data into single PostgreSQL 16 + pgvector instance
    • Eliminate MariaDB (EspoCRM) — port CRM data to PostgreSQL
    • Eliminate MySQL 5.7 (SEO Panel) — port SEO data to PostgreSQL
    • Replace Neo4j with pgvector + recursive CTEs / Apache AGE extension
    • Eliminate separate n8n/Temporal PostgreSQL instances — use schemas in main DB

🌐 Phase 2: Unified Frontend (Next.js 15)

Goal: Replace 4+ frontends with one multi-tenant Next.js app. Source: bizosaas_platform_rebuild_analysis.md §3A, comprehensive_gap_analysis.md §1-2

  • Core App
    • Initialize apps/web (Next.js 15, App Router, React 19, TailwindCSS v4)
    • Implement Multi-tenant middleware (domain/subdomain routing)
    • Implement Auth system (Better Auth with Drizzle adapter + session guard)
    • Setup Zustand for client state, TanStack Query v5 for server state
    • Implement React Hook Form + Zod validation
  • Portal Features
    • Port client-portal features into apps/web/(dashboard) — layout + overview scaffolded
    • Port admin-portal features into apps/web/(admin) — layout + overview + tenants scaffolded
    • Port business-directory into apps/web/(directory) — layout + homepage scaffolded
    • Build public marketing pages in apps/web/(marketing) — Home + Layout complete
    • Build auth pages in apps/web/(auth) — login + register complete
    • Build OpenClaw Assistant / Chat UI — Integrated into root layout
  • Multi-Tenant CMS & Website Provisioning
    • Implement AI-driven template/site JSON generation during onboarding
    • Implement dynamic theming per tenant (CSS variables from DB config) — Scaffolded ThemeProvider
    • White-labeling support (logo, colors, fonts per tenant)
    • Subdomain/custom domain routing via middleware (bizoholic.com, thrillring.com)
  • Built-in SEO Dashboard (Replaces SEO Panel)
    • Build SEO audit and keyword tracking dashboard — UI Scaffolded
    • Google Search Console integration (Via AI workflows)
    • On-page SEO recommendations engine (AI Site Audit endpoint)
  • CRM Module (Replaces EspoCRM)
    • Build contacts/deals/pipeline module in Next.js — UI Scaffolded
    • PostgreSQL CRM Schema Implementation (Contacts, Accounts, Deals, Activities)
    • Migrate EspoCRM data to PostgreSQL CRM schema (Completed)
    • Implement CRM API routes (CRUD contacts, deals, activities, accounts) and UI Views
    • CRM Maturity: Implement Leaderboard Snapshots, Real-time SSE Feed, and AI enrichment agents.
  • Billing Integration (Replaces Lago)
    • Implement Stripe/Razorpay billing
    • Research Lago + Stripe + Razorpay + PayPal + Paddle hybrid model
    • Implement Paddle Connector (MoR for Partner Marketplace)
    • Implement calculate_partner_payout logic in BillingService
    • Build subscription management UI — Complete
    • Build invoice/payment history UI — Complete
    • Implement metered billing for AI agent usage (AIaaS model per service_tier_strategy.md)
  • PWA Support
    • Integrate PWA capabilities (Manifest, Service Worker, Register component)

📚 Phase 2.5: Docusaurus Integration

Goal: Migrate and integrate the legacy Docusaurus docs site into the new monorepo. Source: Legacy v1-archive/docs/ (Docusaurus 3.7.0, React 19)

  • Migration to Monorepo
    • Create apps/docs in the monorepo workspace (Docusaurus 3.9)
    • Port strategy, master plan, and rebuild analysis docs into apps/docs/docs
    • Update pnpm-workspace.yaml to include apps/docs
    • Update docusaurus.config.ts: fix org name, repo name, edit URLs
    • Update navbar links (remove tutorial references, add Bizoholic links)
  • Content & Branding
    • Update branding assets (static/img/ — logo, favicon)
    • Migrate existing docs content (docs/ -> apps/docs/docs/)
    • Add API documentation for the AI Service endpoints (Auto-generated)
    • Integrate AI Agents to auto-update Docusaurus content via BullMQ
    • Add Connector documentation (setup guides for each integration) ✅
    • Add Platform onboarding guide for new tenants
    • Add Developer guides (contributing, local setup, architecture overview)
  • Deployment
    • Add apps/docs Dockerfile for containerized deployment
    • Add Docusaurus build to the Turborepo pipeline (turbo.json)
    • Deploy to docs.bizoholic.com via Dokploy
    • Add CI/CD workflow for docs deployment on push

🤖 Phase 3: AI Service Consolidation

Goal: Single, robust Python service for all agentic workflows. Source: bizosaas_platform_rebuild_analysis.md §3B, llm_strategy_recommendation.md, openclaw_multimedia_analysis.md

  • Initialize apps/ai-service (FastAPI)
  • Port 28+ CrewAI Agents
  • Port 74+ Connectors
  • Port RAG (pgvector) and KAG Service
  • Port OpenClaw Router & Agent Coordination
  • Connect AI Service to Next.js API
  • LLM Router & Cost Tracking (from llm_strategy_recommendation.md)
    • Enhance _get_llm_for_task() with LLM_PROFILES pattern (task-based model routing)
    • Create MediaServiceRouter for voice (ElevenLabs), image (Replicate/Stability), video (Replicate/HeyGen)
    • Implement LLMCostTracker with Redis hot-path
    • Add per-tenant LLM cost tracking (tenant_id, agent_name, model, tokens, cost_usd)
    • Implement fallback logic (primary model fails → auto-switch)
    • Create LLM Usage Dashboard API endpoints (get_global_daily())
  • Extended LLM Tasks (from extended_llm_strategy.md)
    • Implement Groq/Together AI direct SDK connectors (beyond OpenRouter)
    • Implement global CostTrackingCallbackHandler middleware for all agent calls
    • Implement Fine-tuning Worker & Data Flywheel pipeline
    • Build Tool Management API (AgentRole tool permissions per tenant)
    • Feed real-time token/cost data into OpenClaw live status feed
    • Implement Dynamic Tool Discovery (filter tools by tenant tier)
    • Implement PWA (Progressive Web App) for cross-platform "Native-like" experience
    • Implement Metered Usage & Quota management (Redis-based)
  • AI Agent Documentation Integration
  • AI agents automatically update technical/non-technical docs on Docusaurus
  • Admin dashboard (fleet management) can start/stop documentation agents

Integration Bridges & Dynamic Connectivity

  • Introduce WebhookBridgeConnector for Zapier, Make.com, n8n
  • Implement "Bridge Strategy": Use external visual builders as immediate connectivity layer
  • Add "Setup Bridge" wizard in Connector Marketplace (Guided UI)
  • Implement usage tracking for bridge-mediated actions
  • Build "AI Agent Fleet Management" in admin dashboard
  • Build native Shopify & Amazon MCF connectors (Enterprise focus)
  • Code Quality
    • Resolve Pyright/Pyre linting errors in ai-service
    • Implement robust error handling & retries in BaseConnector
    • Integrate UsageManager (Redis) into ConnectorService
    • Integrate BillingService (Postgres) into ConnectorService
    • Implement Billing Dashboard UI in client portal
    • Implement SigNoz tracing for all connector operations
    • Fix NoneType errors on redis_client in background tasks
    • Verify EventBus domain events (Redis Streams) ✅
  • Multi-Modal Content Pipeline (Verified) ✅
    • Verify text generation pipeline ✅
    • Verify image generation pipeline ✅
    • Verify video scripting pipeline ✅
    • Verify audio/TTS pipeline ✅

⚡ Phase 4: Workflows & Workers (BullMQ)

Goal: Replace Temporal/n8n with lightweight BullMQ workers. Source: bizosaas_platform_rebuild_analysis.md §3B, comprehensive_gap_analysis.md §3, implementation_plan.md

  • Setup Redis + BullMQ infrastructure
  • Temporal → BullMQ Migration
    • Convert 29+ Temporal workflows to BullMQ jobs (29/29 complete)
    • Implement HITL API routes (src/app/api/proposals) and UI components (WorkflowProposals.tsx)
    • Implement HITL state persistence (BullMQ job → pending in PostgreSQL → trigger new workflow job upon approval)
    • Test HITL approval flow and Approval Center UI
    • Migrate Silent Discovery to BullMQ
    • Implement digital-marketing-360 Master Workflow in BullMQ
  • Worker Implementation (from bizosaas_platform_rebuild_analysis.md §4)
    • email.worker.ts — Email sending (React Email + Resend)
    • billing.worker.ts — Invoice generation, subscription sync
    • analytics.worker.ts — Analytics data sync
    • discovery.worker.ts — Silent discovery background jobs
    • content.worker.ts — Content pipeline (text, image, video generation)
    • product-sync.worker.ts — Multi-platform product sync (Shopify, Amazon, eBay)
    • seo.worker.ts — Automated SEO audits and optimization
    • social-media.worker.ts — Scheduled posting, engagement sync, Unified Inbox
    • reporting.worker.ts — Automated ROI and performance reports
    • trading-backtest.worker.ts — Historical backtesting for QuantTrade
    • agent-task.worker.ts — Resilient generic AI agent tasks (KAG, code review)
    • onboarding.worker.ts — Automated tenant setup and provisioning
    • documentation.worker.ts — AI-driven Docusaurus manual updates
    • apps/workers/src/index.ts — Main entrypoint bootstrapping all workers
    • apps/workers/package.json + tsconfig.json — Workers app scaffolded
  • OpenClaw Integration
    • Implement OpenClaw Bridge as a worker (conversational UI → agent orchestration)
    • WebSocket integration for real-time OpenClaw chat (Next.js ↔ Python AI via openclaw.py)
    • Test OpenClaw Assistant end-to-end ✅
  • n8n Replacement
    • Audit existing n8n workflows and port critical ones to BullMQ + cron
    • Remove n8n infrastructure (container, DB)

🟢 Phase 5: Onboarding & Multi-Tenancy

Goal: Seamless non-technical onboarding with robust multi-tenant architecture. Source: onboarding_multi_tenant_gap_analysis.md, end_to_end_onboarding_flow.md, comprehensive_gap_analysis.md §2

  • Schema Synchronization
    • Port tenants and partner_managed_tenants tables to Drizzle schema
    • Synchronize Drizzle schema with Billing/Tenant models
    • Add tier field (SMALL, PARTNER, ENTERPRISE) to tenants table
    • Add settings JSON field for onboarding metadata persistence
  • Seamless Onboarding (Magic Discovery)
    • Develop OnboardingService logic
    • Implement Unified Authorization Hub (Google, Meta, Amazon OAuth)
    • Implement Marketplace OAuth Migration (Amazon SP-API, eBay, Etsy via OAuthMixin)
    • Implement Global Service Credentials (platform-level Client IDs in Infisical)
    • Add Amazon/eBay/Etsy to Magic Discovery flow in onboarding.py
    • Implement Multi-Platform Product Sync (Shopify, Amazon, eBay)
  • Partner Management
    • Implement X-Act-As-Tenant header for partner context switching
    • Verify BullMQ workers receive and respect tenant_id in job payloads
    • Implement Partner Ranking & Dynamic Capacity Scoring (from ecosystem_growth_ecommerce_strategy.md)
    • Implement tier-based resource allocation (dedicated workers/rate limits per tier)
  • Autonomous Website Provisioning (from comprehensive_gap_analysis.md §2)
    • AI-driven site config JSON generation during onboarding
    • Next.js middleware for tenant.bizosaas.com subdomain routing
    • Dynamic rendering of tenant sites from DB config

📡 Phase 6: 360° Channel Coverage & Market Dominance

Goal: Achieve 100% market coverage across all 8 pillars. Source: conversational_commerce_strategy.md, service_catalog.md, service_tier_strategy.md

Pillar 1: Foundational Presence ✅

  • Google Search Console integration
  • Google Business Profile / Local SEO
  • Website (Next.js headless)

Pillar 2: Awareness & Video ✅

  • Meta (Facebook/Instagram) Ads
  • TikTok Ads
  • YouTube Ads
  • Connected TV (CTV) Programmatic (Heuristics implemented in PredictiveAnalytics) — Marked complete; full CTV API integration deferred to enterprise tier

Pillar 3: High-Intent Discovery ✅

  • Google/Bing SEM
  • Generative Engine Optimization (GEO) Worker (ChatGPT/Perplexity/Gemini)
  • Answer-Engine Optimizer (AEO) for Perplexity/Gemini/Copilot

Pillar 4: Personal Messaging ✅

  • WhatsApp Business API Connector
  • Telegram Bot API Connector
  • Snapchat Ads & AR Lens Connector
  • SMS Marketing (Twilio)
  • Voice Marketing (Twilio Voice + AI Voice)

Pillar 5: Community & Advocacy ✅

  • Discord Community Management Connector
  • Reddit Community Management Connector
  • Slack B2B Community integration
  • LinkedIn Creator Ads (B2B Creator Connector)
  • Substack newsletter integration
  • Employee Advocacy tools — Worker ready; UI scaffolding task added to Phase 9C

Pillar 6: Retail & Performance ✅

  • Amazon SP-API Marketplace
  • eBay Marketplace
  • Etsy Marketplace
  • Pinterest Ads & Organic Pins
  • Walmart Connect & Instacart Ads (retail media networks)
  • Uber Ads integration
  • Affiliate management — Logic ready in BillingService; dashboard UI task added to Phase 9C

Pillar 7: Global Regionalization ✅

  • Moj/Josh/ShareChat (Vernacular Video) Connectors
  • Dialect AI support bots — Multi-language prompts ready; integration into Support Ticket system (Phase 9D)

Pillar 8: Retention & Data Moats ✅

  • First-Party Data Vault (Consent-Led Marketing)
  • Klaviyo email integration
  • Beehiiv/HubSpot newsletter automation (beehiiv_connector.py) ✅
  • GA4 Server-Side tracking & Media Mix Modeling (via PredictiveAnalytics) — Logic complete
  • Privacy-first analytics (server-side tracking) — Add PostHog server-side SDK to Next.js API routes (Phase 9E)

Unified DM Inbox ✅

  • Aggregate messages from FB, IG, WhatsApp, Telegram for AI Agent handling (unified_inbox.py) ✅

🧠 Phase 7: Agentic Autonomy & Advanced Automation

Goal: Self-correcting agents, cross-client learning, and predictive optimization. Source: implementation_plan.md §8, ecosystem_growth_ecommerce_strategy.md, end_to_end_onboarding_flow.md

  • Agentic Self-Correction
    • Implement AutonomyManager for agentic loop-backs on connector errors
    • Implement Predictive ROI scoring for CTV and Social Search campaigns
    • Implement AI Agent Reinforcement Learning for cross-channel spend optimization (rl_optimizer.py)
  • Cross-Client Learning
    • Implement CrossClientLearningEngine (anonymized performance insights across tenants)
    • Implement effectiveness scoring for content and campaign strategies
  • Ecosystem Growth (from ecosystem_growth_ecommerce_strategy.md) ✅
    • Implement LeadGen Agent for autonomous partner/client acquisition
    • Implement automated outreach via digital-marketing-360 for BizOSaaS itself (lead_gen_service.py)
    • Implement self-service "Magic Link" onboarding (zero human interaction)
    • Implement "Biz-Store" with Stripe Checkout for digital services / partner gigs (biz_store.py)
    • Implement revenue sharing model (5-15% platform fee, usage-based payouts)

🧪 Phase 8: Verification, Internal Clients & Launch

Goal: End-to-end testing, internal client migration, production deployment. Source: bizosaas_platform_rebuild_analysis.md §7, original task.md

  • End-to-End Testing
    • Test full onboarding flow (Coreldove D2C brand scenario) ✅
    • Verify partner ranking and client allocation ✅
    • Test OpenClaw Assistant WebSockets end-to-end ✅
    • Test HITL approval flow (pause → notify → review → resume) ✅
    • Test multi-tenant routing (subdomain, custom domain)
      • Create walkthrough.md with demo recordings
    • Implement unique database constraints (schema.ts)
    • Implement sync-unified-inbox background job (worker.py)
  • Internal Client Migration
    • Implement bulk_tenant_migration logic in MigrationService
    • Port Business Directory
    • Port ThrillRing (Gaming Service) as internal test client
    • Port QuantTrade (Trading Service) as internal test client
  • CI/CD (from bizosaas_platform_rebuild_analysis.md §3D)
    • Consolidate to 2 GitHub Actions workflows: ci.yml (lint+test+typecheck) + deploy.yml (build+push+deploy)
    • Remove legacy CI/CD workflows (effectively done by implementing new unified ones)
    • GHCR image build for: web, ai-service, workers, docs
  • Production Deployment
    • Infrastructure setup on KVM2 Server (Docker Compose provided in infrastructure/)
    • Production deployment via Dokploy (CI/CD ready)
    • Fix Docker Build ECONNREFUSED issues via force-dynamic routes
    • Data migration from old platform (via bulk_tenant_migration logic)
    • DNS configuration for all domains — Use Cloudflare API + domain.worker.ts for automation (Phase 9F)
    • SSL certificate setup (Managed by Dokploy/Traefik)
    • Final Sanity Check: "Onboarding → Connected Services → Data Sync → AI Strategy"
  • Shell Script Cleanup
    • Reduce 196 shell scripts to ~10 essential ones (consolidated in infrastructure/scripts/)

🔍 Phase 9: Legacy Gap Remediation & Product Decisions

Goal: Port identified legacy features not yet in the rebuild, finalize key architecture decisions, and launch planned new products. Source: Legacy code audit of v1-archive/bizosaas-brain-core/brain-gateway/ (March 13, 2026)

[!IMPORTANT] Legacy API inventory identified 64 FastAPI routers and 50+ services in v1 that were audited for rebuild coverage. The following require action.

9A: 🏦 Metered Billing — Lago vs Stripe Meter (🔴 DECISION REQUIRED)

Background: The rebuild replaced Lago (Ruby, ~2.5GB RAM) with Stripe/Razorpay. However, Lago provides usage-based metered billing (per-AI-call, per-connector-action, per-GB) that Stripe's Meter API can replicate but with more setup. For a SaaS selling AI-as-a-service, metered billing is critical.

Decision Options:

  • Option A: Use Stripe Meter API — Zero extra containers, costs 0.5% of metered revenue above $10K MRR, natively integrated. Recommended for current scale.

  • Option B: Re-deploy Lago (self-hosted) — Full metered billing UI, higher RAM (~2.5GB), more control. Better when MRR > $50K.

  • Add Lago API, Redis, and UI to docker-compose.yml (SKIPPED: Decided to go with Stripe for now).

  • Install lago-python-client in ai-service. (SKIPPED)

  • Implement LagoConnector or update BillingService to sync tenants to Lago customers. (SKIPPED)

  • Create Lago Billable Metrics (e.g., ai_tokens_used, storage_gb, domains_purchased). (SKIPPED)

  • Connect UsageManager (Redis) to Lago events: flush usage stats periodically via lago.events().create(). (SKIPPED)

  • Implement Lago Webhook handler in ai-service to process invoice.created and subscription.terminated events. (SKIPPED)

  • Build Lago frontend iframe or native UI in the client portal for plan upgrades and usage viewing. (SKIPPED)

  • Link Lago to Stripe/Razorpay as the payment processor. (SKIPPED)

  • Configure Lago Plans and Coupons mirrored from Stripe Product Catalog. (SKIPPED)

  • Implement check_usage_limit in ai-service to enforce quota-based blocking of features. (Implemented via Stripe Meter API instead)

Tasks Required for Stripe Meter (Option A - Default):

  • BillingService already tracks per-tenant AI usage in Redis (UsageManager).
  • Implement MeteredUsageReporter — reads Redis usage buckets → sends to Stripe Meter API (flush_all_usage + BullMQ usage-flush job registered).
  • Add plan-based metered limits: SMALL (1000 AI calls/mo), PARTNER (10K), ENTERPRISE (unlimited) — check_usage_limit() + PLAN_AI_CALL_LIMITS dict in BillingService.
  • Build Usage Dashboard in client portal — real-time AI call consumption, cost projections.
  • Test metered billing end-to-end — apps/ai-service/tests/test_metered_billing_e2e.py covers: plan limits (SMALL/PARTNER/ENTERPRISE), 100 AI call simulation, over-limit enforcement, Stripe meter flush via MeteredUsageReporter.flush_all_usage(), and no-delta skip

9B: 🌐 Domain Marketplace — Real Registrar API Integration (🔴 HIGH)

Background: Legacy brain-gateway/app/api/domains.py (266 lines) and DomainPort were fully specified and ported to the new AI service but with mock implementations only. The domain marketplace was a planned revenue stream — users on eligible plans can search/purchase/manage domains directly within BizOSaaS, which are then assigned to their tenant website. Partners: Namecheap, Cloudflare Registrar, Porkbun, OpenSRS.

Plan eligibility: SMALL plan gets 1 free .com domain/year; PARTNER/ENTERPRISE get 3/unlimited.

  • Real Domain Provider Connectors
    • Implement NamecheapConnector — Namecheap API v2 for domain search, register, renew, DNS management.
    • Implement CloudflareRegistrarConnector — Cloudflare API for at-cost domain registration.
    • Implement PorkbunConnector — Porkbun API for low-cost domains.
    • Implement GoDaddyConnector — GoDaddy API for popular domain searches.
    • Implement OpenSRSConnector — OpenSRS API for wholesale domain management.
    • Create DomainProviderRegistry — provider selection by availability/price/margin.
    • Wire domains.py API in ai-service to real connectors (remove mock logic, replace with active integration).
    • Implement domain markup/margin logic (Namecheap: +36%, Porkbun: +25%, Cloudflare: +10%) mapped to BillingService.
  • Domain-to-Website Assignment
    • Check user's subscription tier to verify if a free domain is available — check_domain_allowance() in BillingService, wired into POST /api/domains/purchase.
    • Allow tenant to assign purchased domain to their provisioned Next.js tenant site — POST /api/domains/{id}/assign triggers assign_domain_activity.
    • Auto-configure Cloudflare DNS (A record → VPS IP) via Cloudflare API — assign_domain_activity handles this.
    • Auto-configure Dokploy custom domain via Dokploy MCP — assign_domain_activity uses DokployClient.create_domain().
    • Add domain assignment UI in dashboard (Domains → Assign to Site) — implemented DomainAssignmentModal.tsx with auto-config workflow (Cloudflare + Dokploy).
  • Domain Renewal Automation
    • Add Drizzle schema for domain_inventory and domain_search_history tables.
    • Implement domain-renewal.worker.ts in BullMQ — check expiry 30/15/7/1 days out → notify → auto-renew via API.
  • Admin Domain Dashboard
    • Build admin domain stats page (total domains, gross revenue, net profit, expiry map).
    • Provider configuration UI (set API keys, margin percentages per registrar).
  • Frontend Domain Marketplace UI
    • Build domain search page (/dashboard/domains/search) — query + TLD filters + availability results.
    • Build domain purchase flow (select → checkout via Stripe/Lago → confirm).
    • Build domain inventory page (/dashboard/domains) — list with status, expiry, DNS config button.

9C: 📋 Support Ticket System (🟡 MEDIUM)

Background: Legacy support.py (162 lines) implemented a full AI-assisted support ticket system with AI agent auto-triage (calls customer-support CrewAI agent via RAG). This was not ported to the new build.

  • Port Support Ticket System
    • Add Drizzle schema for support_tickets and ticket_messages tables
    • Create apps/ai-service/app/api/support.py route (already exists in v1 — port with Alembic models)
    • Ensure customer-support AI agent is wired via CrewAI in new ai-service
    • Build Support UI in client dashboard (/dashboard/support) — ticket list + create + thread view
    • Build Partner support view — apps/web/src/app/(dashboard)/partner/support/page.tsx — partner sees tickets across all managed tenants with status filter + stats
    • Build Admin support view — all tickets, assignment, escalation
    • Wire Dialect AI bots for multilingual support responses — language detection scaffold in apps/ai-service/app/services/support_email.py (detects Hindi, Tamil, Telugu, Marathi, Spanish, French, Arabic, Chinese)
    • Add email notification on new ticket + AI reply — send-support-ticket + send-support-ai-reply jobs added to apps/workers/src/email.worker.ts; dispatched in create_ticket via support_email.py

9D: 🛍️ Multi-Channel E-Commerce UI (🟡 MEDIUM)

Background: Legacy ecommerce.py (368 lines) provided unified multi-channel order/product/customer management across WooCommerce, Shopify, Amazon, eBay. The new AI service has the connectors but the frontend dashboard pages are missing.

  • E-Commerce Dashboard Pages (Next.js web app)
    • apps/web/src/app/(dashboard)/ecommerce/page.tsx — High-fidelity Hub implemented
    • Multi-channel summary dashboard (Shopify, Amazon, Wix, WooCommerce)
    • Product sync status tracking
    • Order performance metrics
    • Inventory sync real-time view
  • Employee Advocacy UI
    • apps/web/src/app/(dashboard)/dashboard/advocacy/ — content sharing queue, leaderboard
    • Employee invite flow for advocacy program enrollment
  • Affiliate Management UI
    • apps/web/src/app/(dashboard)/dashboard/affiliates/ — affiliate links, commissions, payouts
    • Wire to calculate_partner_payout in BillingService

9E: 📄 CMS Strategy — Payload CMS vs Next.js MDX (✅ DECISION CONFIRMED)

Background: The rebuild replaced Wagtail CMS with "Next.js CMS / MDX". However, for a multi-tenant SaaS providing client websites, a real headless CMS is needed.

Analysis & Recommendation: YES, proceed with Payload CMS generating Next.js ISR (Incremental Static Regeneration) sites.

  • For digital marketing (SEO, page speed), a static site is superior. Next.js ISR provides the speed of static sites but automatically rebuilds pages when a client updates content.

  • Payload CMS runs naturally inside the existing Next.js App Router, sharing the SAME PostgreSQL database via Drizzle. We gain a powerful self-service UI for our clients with ZERO new containers.

  • We will use this multi-tenant instance for internal brands (bizoholic.com, thrillring.com) first, then automated client portals.

    • Implement Payload CMS as a Next.js plugin within apps/web (Core Payload 3.0 configured).
    • Define shared Payload collections: Pages, Posts, Products, Media (Initial setup in config).
    • Implement tenant-scoped access control (each tenant can only see/edit their own content via checking req.user.tenant_id).
    • Setup ISR endpoints in Next.js to fetch data from Payload and cache it statically (lib/cms/api.ts).
    • Provision Payload CMS instance per new tenant during onboarding (onboarding.worker.tsprovision-cms-tenant job added).
    • Phase 1 Lean eCommerce (Stripe-Native via Payload CMS)
      • Add products collection: name, description, price, stripePriceId, image, status.
      • Add orders collection: tenantId, userId, stripeSessionId, amount, status.
      • Add StoreSection block to existing pages collection.
      • Create ProductCard.tsx component with Stripe Checkout trigger.
      • Implement api/checkout/route.ts (Create Stripe Session).
      • Implement api/webhooks/stripe/route.ts (Handle checkout.session.completed).
    • Migrate bizoholic.com and thrillring.com content to Payload database.

9F: 🔧 Infrastructure & Ops Remaining (🟡 MEDIUM)

  • DNS Configuration Automation
    • Implement Cloudflare API wrapper in apps/ai-service — full provision_tenant_domain, add_dns_record, create_zone, list_dns_records implemented in connectors/cloudflare.py.
    • domain.worker.ts already routes assign-domain jobs — now backed by real /api/domains/provision-dns endpoint that calls Cloudflare and persists zone_id + nameservers.
    • Added /api/domains/dns-status/{domain} endpoint for live DNS health check from the frontend.
  • Privacy-First Analytics
    • Add PostHog server-side SDK to Next.js API routes for privacy-compliant event tracking
    • Add cookie consent banner with PostHog opt-in/opt-out
    • Configure PostHog person profiles: no PII without consent
  • EventBus Verification (Redis Streams)
    • Deploy to VPS and verify Redis Streams event bus (EventBus in ai-service)
    • Test domain events: tenant.created, domain.purchased, content.published
  • Multi-Modal Content Pipeline (VPS-dependent)
    • Verify text generation pipeline (GPT-4o / Gemini 1.5)
    • Verify image generation pipeline (Replicate / Stability AI)
    • Verify video scripting pipeline (HeyGen / RunwayML)
    • Verify audio/TTS pipeline (ElevenLabs)
  • OpenClaw End-to-End Test
    • Deploy full stack to VPS and test OpenClaw WebSocket assistant from browser
    • Test real-time agent streaming responses
    • Test HITL pause → human approval → resume in OpenClaw chat
  • Full Onboarding Flow Test
    • Deploy VPS → run Coreldove D2C brand onboarding scenario end-to-end
    • Verify: Sign up → Connect Shopify → Silent Discovery → AI Strategy generated
    • Verify: Domain purchase → assign to provisioned website → SSL confirmed

9G: 📡 AI Agent Task Visibility (Real-Time Client Activity Feed) (🔴 HIGH PRIORITY)

Decision (March 2026): Drop Plane.so permanently. Build a native, zero-infra "AI Work Log" using the existing BullMQ + PostgreSQL + Server-Sent Events stack. This is a must-have trust and retention feature — clients must be able to see exactly what their AI agents are doing in real time.

Why this ranks above PostHog in priority: Every BullMQ worker already calls job.updateProgress(). We are discarding that data today. Persisting and surfacing it requires ~1 day of work and directly reduces churn by making the "black box" visible to clients.

Phase 1 — Implement Now (High Impact, Low Effort)

  • Database: agent_task_log table (packages/db/src/schema)

    • Drizzle schema: id, tenant_id, campaign_id (nullable), worker_name, job_id, task_type, status (pending | running | completed | failed), progress (0-100), summary (text), error (text), metadata (JSONB), started_at, completed_at, created_at
    • Run drizzle-kit generate and drizzle-kit migrate to apply schema
    • Add index on (tenant_id, created_at DESC) for dashboard queries
  • BullMQ Worker Instrumentation — update all active workers to write task log rows

    • content.worker.ts — log content-generation tasks (progress: 10% → 40% → 70% → 100%)
    • social-media.worker.ts — log social-post, social-schedule tasks
    • seo.worker.ts — log seo-audit, keyword-research tasks
    • email.worker.ts — log email-send, email-campaign tasks
    • agent-task.worker.ts — log kag-search, code-review tasks
    • discovery.worker.ts — log silent-discovery, competitor-analysis tasks
    • domain.worker.ts — log assign-domain, check-expirations tasks
    • Create shared helper apps/workers/src/lib/task-log.tslogTaskStart(), logTaskProgress(), logTaskComplete(), logTaskFail() functions to avoid code duplication
  • SSE API Endpoint — real-time task stream for the dashboard

    • apps/web/src/app/api/agent-tasks/stream/route.ts — Next.js route using ReadableStream / SSE
    • Poll agent_task_log every 2 seconds for new/updated rows scoped to tenant_id
    • Return only last 50 tasks (cap at 200 for history)
    • apps/web/src/app/api/agent-tasks/route.ts — REST GET endpoint for initial page load (no SSE)
  • Dashboard Component — "AI Activity Feed" widget

    • apps/web/src/components/dashboard/AgentActivityFeed.tsx — real-time task list
      • Renders task rows: icon | task_type | status (spinner / ✅ / ❌) | progress bar | elapsed time | summary
      • Groups by campaign if campaign_id is set
      • Auto-scrolls to latest task
      • Uses EventSource browser API to consume SSE stream
    • Add AgentActivityFeed to main dashboard overview page (/dashboard)
    • Add full-page task history view at /dashboard/activity
      • Filter by: date range, task type, status, campaign
      • Show error details for failed tasks (collapsible)
    • CRM Integration: Integrated CRM activities into the real-time SSE stream.

Phase 2 — After Launch (Polish & Power Features)

  • Campaign Timeline View — visualize all agent tasks grouped by campaign on a timeline
  • Task Replay — "Retry" button to re-queue a failed BullMQ job from the dashboard
  • Weekly AI Digest Email — BullMQ cron job that emails tenants a summary every Monday ("Here's what your AI agents did this week: 12 posts published, 4 SEO audits, 230 emails sent")
  • WebSocket Upgrade — replace SSE polling with persistent WebSocket if real-time latency becomes noticeable (evaluate after 100+ concurrent tenants)
  • Per-task Cost Attribution — link each task to a Stripe metered event so clients see cost-per-action
  • Agent Performance Metrics — success rate, avg task duration per agent type

🤖 Phase 10: Senior AI Assistant Product (OpenClaw+) (🕒 FUTURE BACKLOG)

Goal: Extend OpenClaw to serve senior citizens with voice-first, simplified AI assistance for everyday tasks: booking cabs, ordering medicine, paying bills, video calling.

[!NOTE] Research & Recommendation: The senior AI assistant market is a high-growth opportunity (India: 140M+ seniors by 2031; US: 55M+). Key competitors: Amazon Alexa, Google Assistant, but none are specifically optimized for non-technical seniors. Recommendation: YES, proceed to build the foundations, but do not derail Phase 8 core stability. Because the logic relies entirely on the existing OpenClaw bridge (WhatsApp Webhooks) and CrewAI agents, it's very easy to prototype natively inside the current monorepo. We will start laying the foundation for "Saathi AI" (or similar name) in parallel by creating new specific Agents (e.g., CabBookingAgent, MedicineAgent) while deploying the main B2B system.

10A: Product Definition & Architecture

  • Product Decision: Confirm product name ("Saathi AI" recommended — meaning "companion" in Hindi)
  • Market Research: Define ICP (Indian seniors 60+, Non-English speaking, tier-2/3 cities vs urban)
  • MVP Feature Set:
    • Voice-first interface (WhatsApp Voice Messages as primary input channel)
    • Cab booking (Ola, Uber integration via AI agent)
    • Medicine ordering (Apollo Pharmacy, 1mg, Netmeds API)
    • Bill payment (BBPS — Bharat Bill Payment System, UPI via Razorpay)
    • Video call setup (help start a WhatsApp/Google Meet call)
    • Emergency SOS (alert family members, share location)
    • Medication reminders (scheduled via BullMQ cron)
    • Family oversight dashboard (family members can view activity, set permissions)
  • Distribution: WhatsApp Business API (lowest barrier for senior adoption)

Phase 9G: Agent Task Transparency (Real-time Progress) [DONE]

  • Database & Model:
    • Review existing ClientTask model in apps/ai-service/app/models/client_task.py
    • Added progress_pct, activity_log, total_steps, completed_steps
  • Agent Integration:
    • Created TaskReporter utility in apps/ai-service
    • Integrated TaskReporter into BaseAgent for synchronized heartbeats
  • Real-time API:
    • Implemented SSE endpoint /api/ai/client-tasks/stream for live updates
    • Built /api/ai/client-tasks CRUD endpoints with filtering
  • Frontend UI:
    • Built AgentActivityFeed component with high-fidelity glassmorphism
    • Created dedicated /activity history page
    • Implemented real-time progress bars and forensic activity logs

10B: Technical Implementation

  • Extend apps/ai-service with SeniorAssistantAgent (CrewAI agent with simplified reasoning)
  • Implement voice message transcription (WhatsApp voice → Whisper API → text)
  • Implement multi-language support (Hindi, Tamil, Telugu, Kannada, Marathi at minimum)
  • Build WhatsApp Business webhook handler for incoming senior messages
  • Implement context persistence (Redis + PostgreSQL) for senior's ongoing tasks
  • Build family oversight API + dashboard in Next.js (/senior-dashboard)
  • Implement OlaConnector, UberConnector for cab booking
  • Implement MedicineOrderConnector (Apollo/1mg) — product search + order placement
  • Implement BBPSConnector for bill payments
  • Build simplified web UI as fallback (large fonts, high contrast, voice input button)
  • Implement senior-reminder.worker.ts — medication reminders, appointment alerts

10C: Monetization

  • B2C Freemium: Free basic tier (10 tasks/month), Pro ₹299/month (unlimited)
  • B2B Enterprise: Hospital chains, senior living communities, corporate elder care benefits
  • Affiliate revenue: Commission on cab bookings, medicine orders, bill payments
  • Family Premium: ₹199/month for oversight dashboard + priority support

📋 Priority Matrix (Updated)

PhasePriorityStatusDependencies
Phase 0: Observability (SigNoz)🔴 CRITICAL✅ DoneNone
Phase 1: Foundation & Monorepo🔴 CRITICAL✅ DoneNone
Phase 2: Unified Frontend🔴 HIGH🟡 Mostly DonePhase 1
Phase 2.5: Docusaurus🟡 MEDIUM✅ DonePhase 1
Phase 3: AI Service🔴 HIGH✅ DonePhase 0
Phase 4: Workflows (BullMQ)🔴 HIGH✅ DonePhase 1, 3
Phase 5: Onboarding & Multi-Tenancy🟡 MEDIUM✅ DonePhase 2, 4
Phase 6: Channel Coverage🟡 MEDIUM✅ DonePhase 3, 4
Phase 7: Agentic Autonomy🟢 LOW✅ DonePhase 3, 5, 6
Phase 8: Verification & Launch🔴 HIGH✅ Done (Build Unblocked)All above
Phase 9A: Metered Billing (Stripe)🔴 HIGH✅ DonePhase 2 Billing
Phase 9B: Domain Marketplace🔴 HIGH✅ Fully Done (UI + Automation)Phase 5, Billing
Phase 9C: Support Tickets🟡 MEDIUM✅ Ported (Backend + UI Done)Phase 3
Phase 9D: E-Commerce UI🟡 MEDIUM🟡 Connectors donePhase 2
Phase 9E: Payload CMS🟡 MEDIUM🔄 ApprovedPhase 2, 5
Phase 9F: Infra/Ops Remaining🔴 HIGH✅ DonePhase 8
Phase 9G: Task Dashboards🔴 HIGH✅ Done (Real-time Feed Integrated)Phase 4, 7
Phase 9H: Twilio Voice Calls🔴 HIGH✅ DonePhase 2
Phase 9I: Advanced Analytics🟡 MEDIUM✅ Done (channel aggregation + agentic insights)Phase 12
Phase 10: Saathi Financial Agent� HIGH🔄 Pivoted to Email IntelligencePhase 9
Phase 10: Saathi Financial Agent🔴 HIGH🔄 Pivoted to Email IntelligencePhase 9
Phase 9J: Platform Launch🔴 HIGH✅ DonePhase 9
Phase 9K: PostHog Integration🟡 MEDIUM✅ DonePhase 9
Phase 11: ERP & CRM Connectors🔴 HIGH✅ DonePhase 9 complete
Phase 13: Lifestyle Hub & Ad-SaaS🟡 MEDIUM🔄 Researching Geo-fencingPhase 10, Mobile
Phase 15: Launch Security (RLS, MFA)🔴 HIGH✅ Completed (RLS, MFA + Sentinel Active)Phase 1, 5
Phase 16: Enterprise Backlog🟢 LOW⚪ Not StartedPhase 15
  1. Phase 15 Coreldove Accelerator: Implement Google Drive inventory sync, Shopify/Amazon scanner, and SEO promotion engine.
  2. Phase 9D E-Commerce UI: Finalize the product/order dashboard (In Progress).
  3. Phase 10 Saathi Personal CFO: Implement Email-based transaction extraction and subscription optimization agents.
  4. Phase 13 Lifestyle Concierge: Build the Geo-fencing & Local Ad-Network foundation for businesses.
  5. Phase 9E Payload CMS Setup: Implement Payload inside the Next.js apps/web container.
  6. Phase 9F Outstanding Testing: Complete deferred tests when VPS is up.

🔒 Phase 15: Launch-Ready Security (SOC2 Prep)

Goal: Implement high-trust security with minimal developer friction for U.S. launch. Source: Architectural Review (March 21, 2026)

  • Data Isolation (RLS)
    • DONE: Fixed unique constraints on tenant_id across 19 core tables to allow multi-tenant data persistence.
    • Implement PostgreSQL Row Level Security (RLS) policies on core tables (user, contacts, deals).
    • Configure app.current_tenant transaction-level variables in Drizzle middleware.
  • Access Control (MFA)
    • Enable TOTP (Time-based One-Time Password) in better-auth.
    • Enforce MFA for admin and partner roles (Implemented in DashboardLayout via session check).
  • Secret Management
    • Verify .gitignore contains credentials.md.
  • Active Sentinel Shield (IDS & Threat Gating)
    • Intrusion Detection Service: Sliding window brute-force login and API anomaly detection in Redis sorted sets (ids_service.py).
    • Threat Scanner: Comprehensive pattern checking (XSS, SQL Injection, SSRF, Path Traversal, Prompt Injection) with Google Safe Browsing reputation syncing (threat_scanner.py).
    • Gateway Inspect Proxy: Real-time content filtering and HTML/script sanitization with automated admin alert creation (security_sentinel.py).
    • Dynamic Quarantine: Real-time IP isolation and self-learning signature ingestion loops (quarantine_service.py).
    • Infrastructure Restoration: VPS snapshot rollback, rogue Nginx service teardown, Cloudflare Edge proxy restriction in UFW rules, and credentials rotation.
  • Multi-Tenant Onboarding Audit
    • Create and deploy verify_onboarding.py supporting robust connections, schema checks, and simulated sandboxed executions for full platform readiness tracking.

🚀 Phase 16: Enterprise Scaling Backlog (Future)

Goal: Advanced security and automation for high-growth phase.

  • Just-In-Time (JIT) Admin Access: Automated approval workflow for cross-tenant support.
  • Application-Level Encryption: Field-level encryption for PII/PHI data.
  • Hardware MFA (WebAuthn): FIDO2/Passkey support for privileged accounts.

🛠️ Phase 17: CRM Maturity & Autonomous Operations (Q2 2026) [DONE]

Goal: Transform the CRM from a data store into an autonomous sales & growth engine. Source: CRM Maturity Audit (April 9, 2026)

  • Autonomous Intelligence (AI-First)
    • AI Enrichment: Automatic scraping of company/contact data on creation.
    • Behavioral Sync: Integrating website/platform events into the contact timeline.
    • AI Summarization: Daily natural language digests of sales activity.
  • Governance & Scale (Enterprise)
    • Team Scoping (RLS): Enforcing team-level data isolation via PostgreSQL policies.
    • Lead Rotation: Round-robin and capacity-based assignment logic.
    • Smart Lists: Dynamic, criteria-based list enrollment engine.
  • Automation & Workflows
    • Multiple Pipelines: Visual support for different sales/partnership cycles.
    • Trigger Engine: Linking CRM events (e.g., "Deal Won") to automated actions (e.g., Slack, ERP Sync).
    • ERP Connectivity: Live financial data (balance, invoices) inside Company accounts.

🔄 Technology Replacement Summary

RemovedReplaced ByRAM Saved
Grafana + Loki + Prometheus + Tempo + OTelSigNoz (self-hosted, OTLP native)~768MB
Temporal + UI + DBBullMQ (Redis-backed, TypeScript)~768MB
n8n + DBBullMQ + cron jobs~512MB
Lago (API + Frontend + Worker)Stripe/Razorpay + Stripe Meter API (pending decision)~2.5GB
EspoCRM (App + Nginx + Daemon + DB)Built-in CRM (PostgreSQL)~704MB
HashiCorp VaultInfisical (managed)~256MB
WordPress (Bizoholic Brand)Payload CMS in Next.js (recommended)~256MB
Wagtail CMSPayload CMS / MDX~256MB
SEO Panel + MySQLBuilt-in SEO Dashboard~384MB
Neo4jpgvector + recursive CTEs~256MB
4 separate frontends1 multi-tenant Next.js app~512MB
Total Savings~7GB RAM, ~27 fewer containers

Phase 11: 🏢 ERP & Business Software Connectors (🔴 HIGH PRIORITY)

Decision (March 2026): Proceed with immediate implementation of ERP connectors to transform the platform into a "Business Operating System." Prioritize "Financial Truth" integrations (Inventory, COGS, Profit) to enable Agentic AI to manage outcomes, not just tasks. Phase 1 target: US Small/Individual businesses + Global agencies.

11A: ERPNext / Frappe Connector

Background: ERPNext is a 100% open-source full-featured ERP (Accounting, AR/AP, Inventory, Payroll, GST). It is built on the Frappe Framework (Python + MariaDB) and exposes a full REST API. The BizOSaaS hub will connect to a client's existing ERPNext instance — we are NOT hosting or reselling ERPNext at this stage.

Use Cases Enabled by Connector:

  • Sync clients issued from BizOSaaS CRM → ERPNext as Customers
  • Create ERPNext Sales Invoices when a deal is marked "Won" in BizOSaaS
  • Pull outstanding AR (Accounts Receivable) into the BizOSaaS dashboard
  • Push payment received events from Stripe → ERPNext Payment Entry (auto-reconciliation)
  • Trigger ERPNext Payroll Run from BizOSaaS HR module (future)

Implementation Tasks:

  • apps/ai-service/app/connectors/erpnext.pyERPNextConnector class
    • validate_credentials — verify API Key + API Secret
    • get_customer(name) — High-level method added
    • create_customer(data) — High-level method added
    • create_invoice(data) — High-level method added
    • get_invoice(name) — High-level method added
    • sync_data(resource_type, params) — generic syncer
    • perform_action(action, payload) — dispatcher
  • Connector Registration — add ERPNextConnector to ConnectorRegistry
  • Auth Schemabase_url, api_key, api_secret (stored in SecretService per tenant)
  • Frontend UI — Add ERPNext card to Connectors settings page with field inputs and test connection button
  • BullMQ Worker Jobsync-erpnext-invoice job in billing.worker.ts triggered on Stripe payment success
  • Webhook Receiver — FastAPI endpoint to receive ERPNext Frappe webhooks (e.g., payment entry submitted → update BizOSaaS deal)

Dependency Note: None — ERPNext connector is purely REST-based. No new containers or infrastructure required.


11B: Bitrix24 Connector

Background: Bitrix24 is a CRM, project management, and communication platform with 12M+ users (dominant in India, LATAM, Eastern Europe). It offers a full REST API (/rest/ endpoint) and supports inbound webhooks. The connector enables a powerful CRM → ERP automation loop.

Use Cases Enabled by Connector:

  • Pull Bitrix24 CRM Deals into BizOSaaS pipeline dashboard
  • When deal stage = "Won" in Bitrix24 → auto-create Sales Invoice in BizOSaaS or ERPNext
  • Push AI-generated content/campaigns from BizOSaaS → Bitrix24 CRM activities
  • Sync Bitrix24 contacts → BizOSaaS CRM (bidirectional)
  • Trigger Bitrix24 task creation from BizOSaaS project management module

Implementation Tasks:

  • apps/ai-service/app/connectors/bitrix24.pyBitrix24Connector class
    • validate_credentials — GET {base_url}/rest/profile with API token
    • get_deals(filter, select) — GET crm.deal.list
    • update_deal_stage(deal_id, stage) — POST crm.deal.update
    • get_contacts(filter) — GET crm.contact.list
    • create_contact(data) — POST crm.contact.add
    • create_activity(data) — POST crm.activity.add (log AI campaign actions)
    • sync_data(resource_type, params) — generic syncer for Deals, Contacts, Companies
    • perform_action(action, payload) — dispatcher: update_deal, create_contact, add_activity
  • Connector Registration — add Bitrix24Connector to ConnectorRegistry
  • Auth Schemabase_url (e.g. https://company.bitrix24.com) + access_token (OAuth2 or webhook key)
  • Inbound Webhook — FastAPI /api/webhooks/bitrix24 endpoint to receive deal stage change events
  • Frontend UI — Add Bitrix24 card to Connectors settings page
  • n8n-style Trigger Job — BullMQ sync-bitrix24-deals cron job (every 15 min) in discovery.worker.ts

Dependency Note: None — purely REST-based connector.


11C: Odoo ERP Connector (🔴 HIGH)

Implementation Tasks:

  • apps/ai-service/app/connectors/odoo.pyOdooConnector class (DONE with Customer/Invoice methods)
  • Agent Integration: Enable CampaignOptimizerAgent to use Odoo tools to pause/start ad budgets based on stock.

11D: Zoho Books / One Connector (🔴 HIGH)

Implementation Tasks:

  • apps/ai-service/app/connectors/zoho_books.pyZohoBooksConnector class (DONE with Customer/Invoice methods)
  • Agent Integration: Enable ReportingAgent to generate "Real ROI" reports (Spend vs Net Profit).

11E: QuickBooks Online Connector (🔴 HIGH)

Implementation Tasks:

  • apps/ai-service/app/connectors/quickbooks.pyQuickBooksConnector class (DONE with Customer/Invoice methods)
  • Agent Integration: Enable FinancialAgent to predict cash flow based on ad performance and expenses.

11F: ERPNext ERP Connector (🔴 HIGH)

Implementation Tasks:

  • apps/ai-service/app/connectors/erpnext.pyERPNextConnector class (DONE with Customer/Invoice methods)
  • Inbound Webhook: Receive Stock change events to trigger ad pausing.
  • Agent Integration: Sync with InventoryAgent for real-time stock-based budget allocation.

11C: Additional Planned Business Software Connectors (Future Backlog)

These are identified market demand connectors. Add to backlog only. No implementation until Phase 11A and 11B are complete and validated.

ConnectorTypePrimary Use CaseStatus
Zoho BooksAccountingIndian SMB alternative to ERPNext for accounting✅ DONE
Zoho CRMCRMCompetitor to Bitrix24, large India install base✅ DONE
QuickBooks OnlineAccountingWestern SMB accounting, US/UK/AU markets✅ DONE
Tally PrimeAccountingDominant in Indian SMB (GST + accounting)✅ DONE
OdooFull ERPOpen-source alternative to ERPNext✅ DONE
HubSpot CRMCRMDominant for agency + digital marketing clients✅ DONE
PipedriveCRMSales-first CRM, popular for SMB✅ DONE
FreshbooksInvoicingFreelancer/agency invoicing✅ DONE
XeroAccountingUK/ANZ/NZ SMB accounting✅ DONE
SAP Business OneERPMid-market enterprise ERP (partnership model)✅ DONE
Microsoft Dynamics 365Full ERP/CRMEnterprise, activate only with Microsoft partnership✅ DONE

Implementation Approach for all connectors: Follow the BaseConnector interface pattern already established. Each connector requires:

  1. A Python class in apps/ai-service/app/connectors/{name}.py
  2. Registration in ConnectorRegistry
  3. Auth credentials stored securely in SecretService (per tenant)
  4. A frontend settings card in the Connectors UI
  5. Specific BullMQ jobs for scheduled sync (if bidirectional)

11G: Partnership & Reseller Track (Activate only if MRR > $10k)

Do not spend any time on this now. Document only for future reference.

  • Evaluate Frappe Cloud reseller program — resell ERPNext hosted sites at margin (Frappe Cloud charges $5/site, resell at $25-49/site)
  • Evaluate Bitrix24 Partner Program — referral commissions on new Bitrix24 accounts
  • Evaluate Odoo Partnership — Silver/Gold partner program for implementation
  • Define "BizOSaaS ERP Bundle" product tier (ERP + AI + Content + Social) — only after 3+ clients request full ERP

Phase 9H: 📞 Real-time Comms & Voice (New)

Goals: Enable AI agents to perform outbound sales calls and handle incoming customer queries via VOIP.

9H.1: Outbound Calling (Twilio)

  • Implement make_call action in TwilioConnector
  • Build TwiML generation service for dynamic agent scripts
  • Integrate Real-time Call Transcription (Deepgram/AssemblyAI) for HITL monitoring

9H.2: VOIP Integration

  • Implement make_call action in WhatsAppConnector (Cloud API VOIP)
  • Create simple browser-based "Softphone" UI for partners to take over calls

Phase 9I: 📊 Advanced Aggregate Analytics (Gemini 2026 Strategy)

Goals: Provide a "Single Source of Truth" dashboard for clients to see absolute marketing ROI.

9I.1: Channel Aggregation

  • Map GA4 + Search Console + Ad Spending (Meta/Google) into a unified PostgreSQL schema
    • apps/ai-service/app/models/marketing_analytics.pyMarketingMetric model (date + channel + spend + revenue + ROAS per row)
    • apps/ai-service/app/api/marketing_analytics.py/api/analytics/unified, /api/analytics/insights, /api/analytics/ingest endpoints
  • Implement MarketingAnalyticsDashboard component in Next.js
    • apps/web/src/components/analytics/MarketingAnalyticsDashboard.tsx — cross-channel KPI cards, channel breakdown table with ROAS bar charts, AI insights panel
    • apps/web/src/app/(dashboard)/dashboard/analytics/page.tsx — wired dashboard page

9I.2: Agentic Insights

  • Connect AIAnalyticsService to the aggregated data store
  • Implement AgenticInsightGenerator — "Your TikTok ROAS is 5x higher than Meta; shall I move 40% budget?"
    • apps/ai-service/app/services/agentic_insights.py — rule-based + LLM-ready engine comparing ROAS/CPA across channels
  • Add White-Label Reporting — Automated monthly text summaries with agency branding via /api/analytics/white-label-report
  • Add sync-marketing-analytics BullMQ scheduled job in discovery.worker.ts

Phase 10: 🏦 Saathi Personal CFO (Email Intelligence) (🕒 FUTURE BACKLOG)

Decision (March 2026): Pivot from generic booking agents to a high-retention "Personal CFO" model. Usage of OAuth-compliant Email Parsing replaces SMS scanning to ensure App Store/Play Store compliance across iOS and Android.

10A: Universal Financial Transaction Listener

  • Connector Enhancement: Add readonly-metadata scopes to Gmail/Outlook connectors.
  • Keyword Scout: Build a heuristic agent that identifies emails from "HDFC", "Stripe", "PayPal", "Amazon", "Uber" based on sender whitelist.
  • AI Extraction Engine: Use the data_extraction LLM profile to parse HTML/PDF bank alerts into structured JSON:
    • amount, currency, merchant_name, category, timestamp.
  • Privacy Guard: Implement "Transient Extraction" — AI processes the email body in memory, saves ONLY the transaction object, and immediately discards the raw email source.

10B: Subscription & Wealth Agentic Logic

  • SaaS Optimizer Agent: Identify recurring themes (e.g., "$12.99 monthly from Netflix") and provide a "Suggest Optimization" action.
  • Net Worth aggregation: Agent logic to sum up account balances detected via monthly statement summaries.

10C: Mobile Hub Foundation (Expo)

  • Apps/Mobile Init: Create a new /apps/mobile directory using Expo Router.
  • Auth Bridge: Shared Clerk/NextAuth integration for biometric (FaceID) login.
  • Activity Feed: A real-time timeline of transactions "spotted" by the AI.

Phase 13: 📍 Lifestyle Hub & Hyper-Local Ad-Network (🕒 FUTURE BACKLOG)

Goal: Convert "Expense Tracking" into "Direct Savings" for users while charging businesses for high-intent walk-ins and direct push notifications.

13A: Geo-fencing & Direct Push

  • Location Engine: Implement high-accuracy background location (user opted-in) via Expo Location.
  • City-based Broadcasts: Admin ability to send push notifications to a specific cluster (e.g., "All users currently in Hyderabad").
  • Business Ad-SaaS: A self-service portal (or AI-driven) where local restaurants can pay to broadcast a 1-hour flash deal to users within 2km.

13B: Event & Movie Ticketing

  • Event Connectors: Integrate with BookMyShow / Ticketmaster APIs to show "Trending Events Near You".
  • In-app Booking: Use the Agent to book tickets directly using the platform's payment intent.
  • Revenue Share: Implement commission tracking for every ticket sold via the Saathi Agent.

13C: Admin Dashboard - Lifecycle Manager

  • Promotions CMS: Build a Promotions collection in Payload CMS to manage global and local offers.
  • Campaign Analytics: Track "Notification Sent" → "Store Walk-in" conversion for merchant billing.

Phase 14: 📦 E-Commerce Autonomy (Sourcing & Fulfillment) (🕒 FUTURE BACKLOG)

Goal: Fully autonomous B2B sourcing and portal-to-portal fulfillment. This creates a "Zero-Touch" dropshipping empire.

14A: B2B Sourcing Agents

  • IndiaMart Scraper: Built-in scraper for IndiaMart to find wholesalers and compare prices.
  • TradeIndia Scraper: Parallel agent for TradeIndia spec/price extraction.
  • Arbitrage Scout: AI logic to compare IndiaMart wholesale prices vs. Amazon/Flipkart retail prices for high-margin opportunities.

14B: Robotic Process Automation (RPA) Fulfillment

  • Wukusy (Deodap) RPA: OpenClaw-based browser automation to log into Wukusy, enter customer details, and draft orders.
  • Amazon Business Connector: Direct API/RPA integration to source from Amazon Business for fulfillment.
  • "Click-to-Ship" Interface: One-button approval on BizOSaaS dashboard that triggers the RPA flow.

Phase 15: 🚀 Coreldove Marketing Accelerator (🔴 CURRENT MISSION)

Goal: Focus purely on "Growth & Management" for Coreldove. The user handles physical fulfillment manually while the AI handles the Digital Sales Engine.

15A: Inventory & Channel Intelligence

  • Google Drive Syncer: Implement a worker that polls a specific Google Drive folder for inventory.csv/xlsx daily. ✅ DONE
  • Multi-Platform Scanner: Onboard Coreldove by scanning products from:
    • Shopify Store — product-sync.worker.ts Ready ✅
    • Amazon Smartbiz / Marketplace — product-sync.worker.ts Ready ✅
    • Flipkart Seller Dashboard — Build Connector & Service mapping ✅
  • Legacy Sync: Ready for SKU/Title matching across platforms.

15B: The AI Sales Machine

  • Content SEO Optimizer: AI agent that rewrites listing titles and descriptions on Shopify/Amazon for higher organic rank. ✅ Ported
  • Multi-Channel Ad-Agent: Synchronized ad campaigns across Meta, Google, and Amazon Ads for the same product set. ✅ DONE
  • Lead Magnet Generator: Auto-generate social media "Viral Reels" scripts and static ads based on inventory stock levels (Implemented in ViralReelsService) ✅

15C: HITL Fulfillment Bridge

  • Manual Fulfillment UI: Dashboard view that aggregates orders from all channels and provides a "Mark as Processed on Wukusy" button. ✅ Scaffolded
  • Status Tracker: tracking_id and courier fields added to Order model in ecommerce_port.py and exposed via list_multi_channel_orders API. ✅ Backend Done

🕵️ Legacy Code Audit Summary (March 13, 2026)

Audited: v1-archive/bizosaas-brain-core/brain-gateway/app/ — 64 API routers, 50 services

Legacy FileStatus in RebuildAction Required
api/domains.py (266 lines)✅ CompleteReal registrar APIs integrated (Namecheap, CF, Porkbun, OpenSRS)
api/support.py (162 lines)❌ Not ported🔴 Port to new ai-service + build UI (Phase 9C)
api/cms.py (680 lines)✅ Ported🟡 Replace WordPress connector with Payload CMS (Phase 9E)
api/ecommerce.py (368 lines)✅ CompleteE-Commerce Hub UI and connectors fully implemented
api/crm.py (21K)✅ Ported🟡 Migrate EspoCRM data (Phase 2)
api/marketing.py✅ Ported✅ Complete
api/analytics_admin.py✅ Ported✅ Complete
api/billing.py✅ Ported🔴 Add metered billing (Phase 9A)
api/onboarding.py (47K!)✅ Ported🟡 E2E test on VPS (Phase 9F)
api/gaming.py✅ Ported (ThrillRing)✅ Complete
api/quanttrade.py✅ Ported✅ Complete
services/revenue_service.py✅ CompleteWired to domain marketplace and search
migrations/003_revenue_and_domains.sql🟡 Schema pending🟡 Add to Drizzle schema (Phase 9B)
ports/domain_port.py✅ CompleteReal adapters implemented
api/workflow_governance.py (9KB)✅ Ported (BullMQ HITL)✅ Complete
api/experience.py✅ Present✅ Complete
api/feature_orchestrator.py✅ Present✅ Complete
services/alert_system.py (9KB)✅ Present✅ Complete
services/predictive_analytics.py✅ Present✅ Complete

Net Gap Count: 2 major (Support Tickets, Domain real APIs) + 3 medium (Metered Billing, E-Commerce UI, Payload CMS)


🚀 Phase 9J: Platform Launch (Bizoholic, ThrillRing, Directory) & QuantTrade Frontend (🟢 PRIORITY NEXT)

Goals: Launch the 3 core tenant sites dynamically on Payload CMS, overhaul onboarding with BizBot, fix dashboard 404s, and build the internal QuantTrade frontend. Source: Approved implementation plan (Mar 15, 2026)

9J.1: Payload CMS Core Schema

  • Add SiteConfig collection for global branding/nav
  • Add Services, CaseStudies, TeamMembers, FAQs for bizoholic.com
  • Add GameNews, ForumCategories, ForumThreads, ForumReplies, Leaderboard for thrillring.com
  • Add Tournaments, TournamentRegistrations, AffiliateProducts, GameReviews for thrillring.com
  • Add GamingCompanies, DeveloperProfiles, GameProfiles (with ratings, rankings, metadata) for thrillring.com
  • Add DirectoryCategories, BusinessListings, BusinessReviews, LocalNews for directory.bizoholic.com

9J.2: Multi-Tenant Frontend (apps/web/[domain])

  • Update [domain]/page.tsx and layout.tsx to fetch from Payload instead of JSON ✅
  • Build bizoholic.com pages (Home, Services, Case Studies, About, Blog) — Payload Schema & Dynamic Routing Ready
  • Build thrillring.com pages (Home, News, Forum, Leaderboard, Tournaments, Store, Game/Dev Profiles) — Payload Schema & Dynamic Routing Ready
  • Build directory.bizoholic.com pages (Home, Category landing with enrichment, Business profile) — Payload Schema & Dynamic Routing Ready
  • Create content-aggregation.worker.ts for automated news, developer data, and social fetching ✅

9J.3: AI Onboarding & BizBot

  • Rename OpenClaw to BizBot across the codebase (chat widget, API prefix, prompts) ✅
  • Implement Dual-Mode Onboarding UI (/get-started): Choice between Guided Form and BizBot Chat ✅
  • Wire BizBot Chat to dynamically ask discovery questions and process user responses during onboarding. ✅

9J.4: Dashboard & Admin 404 Fixes

  • Wire top 5 dashboard pages (analytics, connectors, contacts, billing, support) to real ai-service APIs.
  • Build missing master-admin pages (billing, analytics, settings) ✅

9J.5: QuantTrade Frontend (Internal)

  • Create secure frontend route at app.bizoholic.com/quant (using apps/web/src/app/(dashboard)/dashboard/quant)
  • Configure middleware.ts routing if necessary and ensure route is RBAC protected (internal admins/master only)
  • Build UI for tracing/live strategy monitoring, historical backtester, portfolio risk analysis, and exchange connector statuses.

9J.6: Partner & Analytics Architecture

  • Configure Payload CMS with whitelabel-branding and api-keys global collections for UI-based management
  • Integrate DashboardLayout with custom white-label branding dynamically (app.bizoholic.com / admin.bizoholic.com)
  • Enable Docs visibility controls in Payload CMS (docs.bizoholic.com gating)
  • Draft business strategy artifact for lightweight PostHog Cloud analytics and Partner-first GTM scaling strategy ✅
  • Inject PostHog Cloud Environment token securely into frontend Next.js environment ✅

Phase 9K: 📊 PostHog Cloud Analytics Integration (Gemini 2026 Strategy)

Goals: Use PostHog as the unified analytics engine and Data Warehouse, implementing multi-tenancy via Groups.

9K.1: Server-Side Foundation

  • apps/ai-service/app/services/posthog_service.py — Implement HogQL query execution and source management.
  • apps/ai-service/app/api/marketing_analytics.py — Refactor to proxy queries to PostHog HogQL.

9K.2: Onboarding & Connection

  • apps/ai-service/app/services/onboarding_service.py — Add logic to automatically link external ad sources to PostHog.
  • apps/web/src/components/connectors/SetupConnectorWizard.tsx — Wire to trigger PostHog source linking.

9K.3: Client Dashboard Wiring

  • apps/web/src/components/analytics/MarketingAnalyticsDashboard.tsx — Fetch and display real multi-tenant data from PostHog via AI-Service.
  • apps/ai-service/app/api/bizbot.py — Add tool for BizBot to query channel ROI from PostHog.

9L: 🔐 Enterprise Auth & Social Login Integration

Goals: Enable frictionless signup and login via social providers (Google, GitHub, LinkedIn, Microsoft) and prepare for Enterprise SSO (SAML/OIDC).

9L.1: Server-Side Provider Configuration

  • apps/web/src/lib/auth.ts — Add socialProviders configuration to betterAuth (Google, GitHub, LinkedIn, Microsoft).
  • Environment Variables — Project updated to use GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, LINKEDIN_CLIENT_ID/SECRET, and MICROSOFT_CLIENT_ID/SECRET.
  • Account Linking — Configure automatic account linking for matching email addresses across providers.

9L.2: Social Login UI Implementation

  • apps/web/src/app/(auth)/login/page.tsx — Add Social Login button group (Google, GitHub, LinkedIn, Microsoft) with premium glassmorphism styling.
  • apps/web/src/app/(auth)/register/page.tsx — Integration of social signup to allow one-click account creation.
  • Auth Feedback — Implement loading states and error handling for OAuth redirects.

9L.3: Multi-Tenant & Onboarding Integration

  • Onboarding Redirect — Ensure users signing up via Social Login are correctly redirected to the /onboarding flow if they don't have a linked tenant (Handled in DashboardLayout).
  • Default Role Assignment — Made tenantId nullable in user table; updated /api/onboarding/magic to create and link tenants on-the-fly.

9L.4: Enterprise SSO Preparation (Roadmap)

  • Research better-auth plugins for SAML/OIDC (Enterprise SSO).
  • Draft schema for organization-level SSO settings (Started with nullable tenantId allowing loose user-tenant association).

Phase 16: 🤖 AI Agent Architecture Refinement (New)

Goals: Clean up architectural debt in the CrewAI agent ecosystem, consolidate redundant agents, and provide implementations for stubbed components to prepare for robust workflows.

16A: Resolve Agent Duplication

  • Audit Original vs Core Agents: Reconcile original service-level agents (like ProductSourcingAgent) against the refined 20-Core Architecture agents (e.g., RefinedProductSourcingAgent).
  • Deprecate Unused Roles: Remove redundant files and merge any missing capabilities into the primary "Refined" versions used by MasterOrchestratorAgent.

16B: Stub Implementation & Wire-up

  • Implement Analytics Agents: Add valid prompts, tools, and CrewAI agent definitions for ReportGeneratorAgent, DataVisualizationAgent, ROIAnalysisAgent, TrendAnalysisAgent, InsightSynthesisAgent, and PredictiveAnalyticsAgent.
  • Implement Workflow Crews: Provide real Crew configurations for the currently stubbed ProductLaunchCrew, CompetitorAnalysisCrew, MarketResearchCrew, ContentStrategyCrew, ReputationManagementCrew, and LeadQualificationCrew.

16C: Orchestrator Alignment

  • Update IntelligentRouter logic to strictly point to the updated, consolidated list of agents.
  • Validate HierarchicalCrewOrchestrator execution paths with the new implementations.

Phase 17: 🐳 Production Deployment Fix (March 2026)

Updated: March 18, 2026
Priority: CRITICAL — Must be resolved before any VPS deployment
Status: ✅ RESOLVED — Commit bb5f5230c pushed to v2-rebuild

[!IMPORTANT] Root Cause (FIXED March 18, 2026): Next.js build was failing with Error: You cannot define a route with the same specificity as a optional catch-all route ("/admin" and "/admin[[...segments]]"). The fix was deleting the obsolete apps/web/src/app/(payload)/admin/[[...segments]]/page.tsx file. Payload CMS is already correctly served at /cms via (payload)/cms/[[...segments]]. The custom admin portal at (admin)/admin/ now routes cleanly to /admin. Build verified locally (exit code 0) and pushed to GitHub.

The 6-container stack (web, postgres, redis, ai-service, workers, docs) runs locally but has 3 active blockers. All must be fixed before pushing to GitHub and deploying to the VPS.


17A: Fix Redis DNS Resolution (EAI_AGAIN)

Root Cause: bizosaas-web is on two networks (bizosaas-network + dokploy-network). bizosaas-redis is only on bizosaas-network. When web starts and tries to resolve bizosaas-redis, DNS fails intermittently because the lookup goes through dokploy-network where redis has no entry.

  • 17A.1 — In the infrastructure/ directory, run: docker compose down
  • 17A.2 — Run: docker compose up -d
  • 17A.3 — Wait 30 seconds then test DNS ✅
  • 17A.4 — If ping fails, open infrastructure/docker-compose.yml
  • 17A.5 — Run: docker compose up -d --force-recreate redis web
  • 17A.6 — Confirm no EAI_AGAIN errors ✅

17B: Fix Health Check (Wrong Table Name)

Root Cause: The health check at apps/web/src/app/api/health/route.ts runs the SQL query select count(*) from "users" — but the database table is named "user" (singular, created by Drizzle in startup.mjs). This causes a relation "users" does not exist error every time health check is called.

  • Wait for the build to finish (usually 3–5 minutes with cache hits)

  • 17B.5 — Start updated container: docker compose up -d web

  • 17B.6 — Test: curl -s http://127.0.0.1:3000/api/health

    • Expected: JSON response with HTTP 200 status code

17C: Add Payload CMS Tables via Direct SQL

Root Cause: The push-payload-schema.mjs script uses drizzle-kit 0.31.7 internally to introspect the schema. Drizzle-kit 0.31.7 has a bug: its pg_constraint query uses $1::regnamespace but PostgreSQL returns error: there is no parameter $1. This makes the Payload schema push always crash — so Payload's own tables are never created.

Decision: Do NOT attempt to fix drizzle-kit or Payload's push. Instead, add the minimum Payload tables using raw SQL CREATE TABLE IF NOT EXISTS — exactly the same pattern used for the 25 Drizzle app tables already in startup.mjs.

  • 17C.1 — Open file: apps/web/scripts/startup.mjs
  • 17C.2 — Add Payload tables to SQL migration ✅
  • 17C.3 — Add payload_preferences table ✅
  • 17C.4 — Delete broken Payload sync block ✅
  • 17C.5 — Rebuild and restart ✅
  • 17C.6 — Verify tables exist ✅
    • Expected: payload_migrations and payload_preferences appear in the list

17D: Push to GitHub

  • 17D.1 — Check status ✅
  • 17D.2 — Stage files ✅
  • 17D.3 — Commit changes ✅
  • 17D.4 — Push to v2-rebuild ✅

17E: Deploy to VPS

  • 17E.1 — SSH into VPS ✅
  • 17E.2 — Pull latest ✅
  • 17E.3 — Rebuild and start ✅
  • 17E.4 — Verify containers ✅
  • 17E.5 — Test production health ✅
  • 17E.6 — Test public site ✅
    • Expected: HTTP/2 200

Phase 12: 📈 QuantTrade - Advanced Trading & Risk Management (🔴 HIGH PRIORITY)

Goal: Implement multi-stage strategy validation, AI-driven strategy identification, and advanced money management (Masaniello, Kelly Criterion).

12A: Multi-Stage Strategy Promotion

  • apps/ai-service/app/services/risk_manager.py — Implement check_promotion_eligibility logic.
    • Define promotion thresholds (Win Rate > 60%, Profit Factor > 1.5, Max Drawdown < 10%).
    • Automate progression: BACKTESTPAPER_TRADINGLIVE_BACKTESTLIVE_FORWARD_TESTLIVE_REAL_MONEY.
  • apps/ai-service/app/services/trading_service.py — Implement check_promotion_eligibility dispatcher.
    • Integrate with BullMQ to trigger strategy state transitions.

12B: AI Strategy Identification

  • apps/ai-service/app/services/trading_service.py — Implement identify_strategies method.
    • Integrate with MarketDataService to scan for patterns across multiple symbols.
    • Return candidate strategies for initial backtesting.

12C: Advanced Money Management

  • apps/ai-service/app/services/risk_manager.py — Implement calculate_lot_size with multiple modes.
    • Masaniello Money Management: Sequence-based bet sizing for target profit goals.
    • Kelly Criterion: Fractional sizing based on probability of win and payout ratio.
    • Fixed Amount: Standard static sizing.

12D: Order Life-cycle & HITL

  • apps/ai-service/app/models/trading.py — Add id and status to TradingOrder.
  • apps/ai-service/app/services/trading_service.py — Enhanced place_order and approve_order.
    • Implement PENDING_APPROVAL state for live trades.
    • Integrated PaperTradingEngine and BinanceConnector with consistent TradeExecution returns.

🤖 Saathi Recommendation: Personal CFO vs Senior AI Assistant

Recommendation: Proceed with Saathi Personal CFO (Alpha) immediately as a companion to QuantTrade.

  • Why Personal CFO?: As QuantTrade identifies and executes profitable strategies, the user needs a "Financial Truth" agent to manage the resulting wealth, optimize taxes, and handle personal expenses (Subscription optimization, etc.). This aligns perfectly with the "Business Operating System" goal.
  • Why defer Senior AI?: The "Senior AI Assistant" is a specialized B2C product involving heavy WhatsApp Voice/multilingual work (Phase 10C/10D). While valuable, it doesn't solve the immediate "management of trading capital" problem for the QuantTrade user.

Next Steps for Saathi Personal CFO:

  1. Implement Email-based transaction extraction (Phase 10).
  2. Implement Subscription Optimization agents.
  3. Integrate with QuantTrade Portfolio metrics for "Total Net Worth" tracking.

  1. Phase 12 QuantTrade Frontend: Build the UI for strategy promotion and risk metrics (Done).
  2. Phase 10 Saathi Personal CFO: Email-based transaction intelligence (Done).
  3. Phase 15 Coreldove Accelerator: High-impact D2C scenario inventory sync (Done).
  4. Phase 18: Stability & Production Hardening: Fix manifest, routing, and Saathi rendering crashes (Done).
  5. Final Production Smoke Test: Deployment verification.

Phase 18: 🛠️ Stability & Production Hardening (March 2026)

Goal: Fix common runtime errors, 404s, and rendering crashes in the production build.

  • PWA Manifest Fix: Add middleware bypass for .webmanifest, sw.js, and favicon to prevent syntax errors during subdomain routing.
  • Sidebar Routing Fix: Correct navigation links in sidebar.tsx for BizBot integration (/dashboard/bizbot).
  • Saathi Rendering Resilience: Added numeric amount parsing and safe defaults to prevent "Application error" if DB transaction records contain null/empty amount strings.
  • Branding Fail-Safe Logic: Wrapped host-based CSS variable generation in try/catch with default fallbacks for CMS connectivity issues.

Production Fix Plan — BizOSaaS Auth Stabilization (IN PROGRESS)

Phase 1 — Verify the Codebase Fixes Are on the Right Branch

  • Step 1.1: Confirm argon2 removal is on v2-rebuild (Merged from main)
  • Step 1.2: Verify argon2 is actually gone from auth.ts
  • Step 1.3: Verify startup.mjs won't undo migrations (Checking for destructive DROP ops)

Phase 2 — Fix the Database Migration for two_factor_enabled

  • Step 2.1: Confirm two_factor_enabled is in Drizzle schema (packages/db/src/schema/core.ts)
  • Step 2.2: Generate the migration file (pnpm run db:generate) and commit it
  • Step 2.3: Plan how the migration runs on deploy (Update apps/web/Dockerfile)

Phase 3 — Fix the DATABASE_URL in Dokploy ✅

  • Step 3.1: Find internal Postgres hostname ✅
  • Step 3.2: Update DATABASE_URL in Infisical natively to use internal service name ✅
  • Step 3.3: Verify the Dokploy app pulls from Infisical ✅

Phase 4 — Deploy and Verify ✅

  • Step 4.1: Trigger the deploy in Dokploy ✅
  • Step 4.2: Test auth endpoints locally via Curl / Browser ✅
  • Step 4.3: Confirm cross-subdomain cookies work ✅

Phase 5 — Login Issues Fixed (Summary)

Login is working. 200 with a valid session token.

Here's a summary of everything that was fixed today:

  1. DATABASE_URL was localhost → updated to VPS public IP 194.238.16.237
  2. Postgres SSL not enabled → generated self-signed certs and enabled SSL on postgres
  3. DATABASE_URL missing SSL params → updated to ?sslmode=no-verify
  4. Auth route missing export const runtime = "nodejs" → added to force Node.js runtime for native bindings
  5. @node-rs/argon2 not being used explicitly → added custom hash/verify functions in auth.ts
  6. turbo.json missing DEBUG_AUTH → added (with a comma fix)

Pending Issues (To be done):

  • Restrict admin.bizoholic.com to only allow specific admin accounts (disable open registration, restrict to owner/super-admin)
  • MFA 500 verify-totp error fixed (schema type mismatch resolved and setup logic corrected)
  • Fix Slow redirect from app.bizoholic.com to /login
  • Fix Service Worker (PWA) FetchEvent network error causing long loading times on /login

🛡️ Phase 18: Trust & Autonomy Framework (Governance)

Goal: Establish clear boundaries and trust mechanisms for AI-led operations.

  • L1-L4 Autonomy Model: Comprehensive range selector (Assistant to Autonomous) integrated into AutonomyManager.
  • Partner Guardian Thresholds: Safety gates for $500+ spend and sentiment-based auto-escalation.
  • Chain of Thought Transparency: Real-time reasoning traces persisted in DB and rendered in Dashboard Activity Feed.
  • Worker Gating: Global BullMQ job processor with autonomy validation.

🌍 Phase 19: 360° Market & Feature Enhancements ✅

Goal: Reach feature parity with top global SaaS tools.

  • Shopify SEO Guard (Deep Tech): Automated agent for canonicals, .atom blocking, and technical debt.
  • "Digital Twin" Brand DNA Engine: Specialized service for per-tenant identity and voice consistency.
  • Predictive Campaign Simulator: ROI forecasting engine using historical and market metrics.
  • Agentic RAG for Operations: Empowered BizBot to perform CRUD (Refunds, Order Status) via connectors.
  • Core Web Vitals Dashboard: Integrated real-time health score into Analytics Dashboard.
  • Sentiment Escalator: Advanced inbox analysis to flag high-risk customer interactions.

🚀 Phase 20: Future Resilience (Post-Launch)

Goal: Advanced technical resilience and external ecosystem connectivity.

  • Deadlock / Tie-Breaker Circuit Breaker
    • Implement a revision counter in BullMQ metadata for hierarchical agent tasks.
    • Define "Maximum Revisions" (e.g., 3 internal rejections) before triggering a circuit-breaker.
    • Implement fallback logic: Auto-escalate to human or accept the best version with a "Low Confidence" flag.
  • Webhooks Outbound (Partner APIs)
    • Build a native webhook outbound manager to push events to Zapier, Salesforce, or local ERPs.
    • Implement signature verification and retry logic for outbound payloads.
    • Create a UI for partners to register and manage their target webhook URLs.

📚 Troubleshooting Reference Index

To keep this document clean, all frequent issues, debug steps, and complex platform fixes are documented in the docs/troubleshooting/ directory.

  • MFA / TOTP 500 Verification Error: Explains how to resolve the relation does not exist or insert failed 500 error when verifying TOTP by ensuring the two_factor table and schema uses text instead of UUID, and the user table has the correct MFA columns.