Skip to main content

BizOSaaS — Platform Master Reference

Purpose: Single source of truth for all modules, roles, architecture, and operational principles.
Audience: AI documentation agents, onboarding flows, internal teams.
Security note: This document is safe for internal distribution. Secrets, credentials, encryption keys, and production infrastructure topology are never stored here — they live in Infisical / environment variables only.


1. Platform Philosophy

BizOSaaS is designed as a self-sustaining, self-learning, self-improving, and self-optimising multi-tenant B2B SaaS platform. Its core principle:

The platform and its AI agents work alongside humans — not instead of them. Every autonomous action is reversible, auditable, and subject to configurable human oversight.

Four pillars govern every architectural and product decision:

PillarPrinciple
SecurityZero-trust by default; RLS on every table; secrets in vault only; JIT access model
ScalabilityHorizontal worker scaling via BullMQ; multi-tenant schema isolation; PostgreSQL + Redis
AutonomyConfigurable autonomy levels (0–100) per domain; HITL gates at every high-impact action
QualityGold-standard coding conventions; CI lint/type-check gates; E2E Playwright coverage

2. User Roles & Capabilities

2.1 Super Admin

  • Full platform visibility across all tenants
  • Manage platform boundaries (markup limits, notice periods, tier pricing)
  • Pause/resume any tenant's AI workforce
  • Access governance audit logs, LLM telemetry, billing ledger
  • Configure global autonomy defaults and security policies
  • Portal: admin.bizoholic.com/admin/

2.2 Admin (Platform Operator)

  • Manage their own tenant's settings, users, billing, and integrations
  • View agent task logs, observatory metrics, and AI agent registries
  • Approve/reject HITL workflow proposals within their tenant
  • Generate API keys for third-party integrations
  • Portal: admin.bizoholic.com/admin/ (scoped to own tenant)

2.3 Partner

  • Onboard and manage client tenants under their reseller agreement
  • Delegate tasks to client AI workforces; monitor via leaderboard
  • Deploy partner policy (markup, notice period, SLA guarantee)
  • View compliance snapshots and switch requests
  • Portal: partner.bizoholic.com/partner/

2.4 Client (Tenant User)

  • Access all enabled modules for their subscription tier
  • Interact with Saathi AI (Personal CFO / Senior Business Assistant)
  • View, approve, or reject AI-generated workflow proposals
  • Manage CRM, e-commerce, campaigns, support tickets, and analytics
  • Portal: app.bizoholic.com/dashboard/

3. Architecture Overview

┌─────────────────────────────────────────────────────────┐
│ Unified Next.js Frontend │
│ (app / admin / partner portals — single monorepo) │
│ Subdomain routing via middleware → role-based layout │
└───────────────┬────────────────────────────────┬────────┘
│ REST/Server Actions │ Proxy routes
▼ ▼
┌──────────────────────┐ ┌─────────────────────────┐
│ PostgreSQL (Drizzle) │ │ Python AI Service │
│ Multi-tenant RLS │ │ (FastAPI + SQLAlchemy) │
│ Shared schema │◄────────►│ AI agents, BullMQ jobs │
└──────────────────────┘ └─────────────────────────┘

┌──────────────────────┤
▼ ▼
┌──────────────┐ ┌──────────────────┐
│ Redis Queue │ │ pgvector (RAG) │
│ (BullMQ) │ │ Embeddings store │
└──────────────┘ └──────────────────┘

Technology choices:

  • Frontend: Next.js 15 App Router, TypeScript, Tailwind CSS, shadcn/ui
  • Database: PostgreSQL with Drizzle ORM (TypeScript) + SQLAlchemy (Python); Row-Level Security enforced
  • Queue: BullMQ on Redis for all background jobs and agent tasks
  • AI inference: OpenRouter (multi-model routing: GPT-4o, Claude 3.5, DeepSeek, Gemini)
  • Auth: better-auth (session cookies); internal M2M via signed token headers
  • CMS: Payload CMS 3.0 (headless) powering Bizoholic.com and Thrillring.com
  • Observability: OpenTelemetry traces, JSONL telemetry logging for fine-tuning datasets

4. Module Catalogue

4.1 Core Platform Infrastructure

ModuleDescriptionStatus
Multi-tenant MiddlewareSubdomain detection → tenant context → RLS activation✅ Live
Role-Based Access Controluser.role field gates UI layouts and API routes✅ Live
Auth (better-auth)Session cookies, OAuth (Google/GitHub), 2FA✅ Live
Billing (Stripe)Subscription plans, invoices, credit ledger, usage events✅ Live
Partner GovernancePartner policies, switch requests, platform boundaries✅ Live
Autonomy EnginePer-domain autonomy levels, HITL routing, kill switches✅ Live
Audit LogImmutable record of every agent and human action✅ Live

4.2 CRM & Sales

FeatureDescription
Contacts & AccountsFull contact management with lead scoring, lifecycle stages
Deals & PipelinesVisual kanban pipeline with AI deal-stage automation rules
ActivitiesCall, email, meeting, note logging per contact/deal
Teams & ListsTeam ownership, segmented CRM lists, member management
AI Follow-Up EngineAI drafts 3 personalised follow-up variants for stalled deals
Churn PredictionWeekly ML scoring (0–100) flags at-risk accounts for proactive outreach
Revenue ForecastingProbability-weighted pipeline forecast exported as PDF

4.3 Omni-Channel Marketing

FeatureDescription
Campaign BuilderEmail, SMS, push, WhatsApp campaigns with visual editor
Dynamic SegmentationReal-time audience lists built from behavioural signals
Subject Line Optimizer5 AI subjects → 3-way split test → auto-selects statistical winner
Compliance GuardDMARC/SPF/DKIM validation; CAN-SPAM/GDPR flag detection; suppression list management
SMS Flow BuilderVisual SMS sequence builder with delay nodes, branch conditions, opt-out gates
A/B TestingMulti-variant send-time optimizer per segment

4.4 E-Commerce Operations

FeatureDescription
Multi-channel SyncShopify, WooCommerce, Amazon inventory and order sync via BullMQ workers
Abandoned Cart RecoveryWhatsApp (1h) → Email (6h) → SMS (24h) cascade, stops on purchase
Dynamic Pricing AgentCompetitor price scrape every 6h; suggests adjustment with margin impact; HITL gate
Inventory Alert AgentAuto-drafts re-order PO when SKU hits threshold; HITL approval
Refund ClassificationAuto-approves low-risk returns; escalates disputes to HITL queue
Product Launch CoordinatorSingle trigger → simultaneous social, email, ad, Shopify activation
Post-Purchase SequenceReview request → upsell → loyalty points over 30 days via BullMQ delays

4.5 AI Workforce & Agents

FeatureDescription
Agent RegistryList, enable/disable, and monitor all AI agents per tenant
Agent ObservatoryReal-time BullMQ job metrics (completed, failed, active, waiting)
Visual Workflow BuilderReact Flow drag-and-drop DAG compiler → BullMQ job chains
NL Workflow ComposerNatural language → structured workflow proposal; HITL before deployment
HITL DashboardPending agent tasks requiring human approval with impact scores
Kill SwitchInstant workforce pause/resume per tenant (admin-only)
Telemetry & Fine-tuningStructured JSONL logs of all LLM interactions for dataset generation
Multi-Modal PipelineText → Image → Video generation via OpenRouter + ElevenLabs
Voice AgentsWebRTC/ElevenLabs real-time voice agents for conversational sales

4.6 Saathi AI — Personal CFO & Senior Business Assistant

FeatureDescription
Senior Assistant AgentContext-aware business assistant across 4 personas (CFO, CMO, CTO, COO)
Email IntelligenceGmail/Outlook OAuth sync; LLM + regex extraction of transactions from receipts
Bank SyncPlaid integration for real-time transaction sync via BullMQ webhooks
Subscription TrackerAuto-detects recurring SaaS subscriptions; flags waste and optimises cost
Transaction DashboardCategorised spend view, income tracking, budget analysis
WhatsApp DeliveryConversational AI replies via WhatsApp Business API (controlled by ENABLE_WHATSAPP_DELIVERY flag)

4.7 GEO / AEO — Generative Engine Optimisation

FeatureDescription
AI Share of Voice AuditQueries GPT-4o, Claude, DeepSeek, Gemini with brand-intent search phrases; measures citation rate
Competitor AnalysisTracks competitor brands cited by LLMs; aggregated in aeo_competitor_analysis table
GEO Remediation EditorRAG-powered gap analysis; generates HTML copy rewrites for uncited queries
Content Freshness MonitorCrawls priority pages; scores freshness (0–100); alerts on stale content
Topic Cluster MapperGroups sitemap into pillar-spoke architecture; identifies orphan pages
AI Citation Referral TrackerUTM-tagged LLM referral clicks stored in aeo_referral_events table
JSON-LD Schema InjectorAuto-generates structured data schemas (Organization, FAQPage, HowTo)

4.8 Customer Support Intelligence

FeatureDescription
Unified InboxCross-platform conversation view (WhatsApp, Email, Social) with AI reply drafts
Ticket Priority ClassifierML model scores urgency + business impact; SLA auto-starts
RAG Reply Quality ScorerScores HITL draft 0–100 against quality rubric; auto-regenerates low scores
Multi-Language RoutingLanguage detection → locale-specific reply templates (Hindi, Tamil, Arabic, Spanish, French, Telugu)
Customer Health TimelineFull journey (purchases, emails, churn risk, support) in ticket sidebar
CSAT Auto-Survey24h after close → 1-question SMS survey → logs to csat_responses

4.9 Analytics & Platform Intelligence

FeatureDescription
Unified Analytics Modelanalytics_events captures every action with channel, cost, revenue attribution
Media Mix ModelingMonthly attribution analysis across paid, organic, social, AI referral channels
Cross-Channel ROAS DashboardSide-by-side ROAS, CAC, LTV per channel with 30/90/365-day windows
AI Agent ScorecardPer-agent: tasks, success rate, latency, cost, estimated revenue generated
Custom Report BuilderDrag-and-drop metrics, export PDF/CSV, schedule email delivery
Anomaly DetectorFlags statistical outliers (>20% conversion drop, cost-per-lead spike)
QBR Deck GeneratorAI compiles 90-day data into Google Slides / PDF for account reviews

4.10 Customer Retention & Advocacy (Phase 32)

FeatureDescription
Account Health ScoreComposite score (workflow frequency, feature adoption, support volume, payment history) per tenant; live in /admin/tenants/[id]
At-Risk InterventionHealth < 40 → personalised email + in-app banner + Slack CSM alert
Feature Adoption NudgeIdentifies unused high-value features; sends contextual in-app tips
Expansion Trigger80% quota hit → AI generates personalised upgrade proposal; HITL before send
NPS Survey EngineAuto-send at days 30/90/180; routes promoters (9–10) to G2 review flow
G2 Review AutomationPersonalised email with direct G2 link + optional gift card incentive
Referral ProgrammeTrack referral link sharing → conversion → trigger reward via BillingService

4.11 Platform Governance & Compliance (Phase 34)

FeatureDescription
Confidence-Based HITL MatrixConfigurable thresholds per action type (email blast, price change, CRM update)
Audit Log APIEvery agent and human action logged: actor, action, resource, before/after state, IP
GDPR / DMARC Compliance AgentWeekly automated scan; flags missing consent, unsubscribe violations, DMARC failures
Workflow Rollback EngineAny AI-executed change can be rolled back with one click from the audit log

4.12 Payload CMS (Phase 9E)

FeatureDescription
Headless CMSPayload 3.0 powers Bizoholic.com and Thrillring.com content
CollectionsBlog posts, pages, team members, testimonials, products per brand
Multi-tenant supportEach internal brand has isolated collection namespaces
ISR & SSGContent changes trigger ISR revalidation on the public-facing Next.js sites

4.13 Ecosystem & Marketplace (Phase 35)

FeatureDescription
Agent MarketplacePublish, version, and monetise custom AI agents; certification workflow
Workflow Template LibraryPre-built one-click templates (e.g., "Shopify + WhatsApp Cart Recovery")
White-Label Client PortalsPartners brand BizOSaaS as their own platform (domain + logo + colours)
API Developer HubPublic REST API docs, SDK (Python, JS), webhooks, sandbox
Revenue Share ProgrammePartners earn 20% of client revenue; tracked via partner_commissions table

5. AI Agent Framework

5.1 Agent Base Contract

Every agent extends BaseAgent and must implement:

  • _execute_agent_logic(task: AgentTaskRequest) → dict
  • Emit milestones to agent_milestone_log table
  • Write JSONL telemetry for fine-tuning datasets
  • Respect tenant autonomy level and HITL thresholds

5.2 Registered Agents

AgentPurposeTrigger
senior_assistant_agentContext-aware business advice across 4 C-suite personasChat prompt
aeo_agentGEO/AEO brand visibility audit across LLMsScheduled / manual
crm_agentDeal automation, follow-ups, churn predictionBullMQ cron
email_agentCampaign drafting, personalisation, send-time optimisationCampaign trigger
seo_audit_crewTechnical SEO + schema validation + freshness crawlScheduled
multi_modal_agentText → Image → Video pipelineWorkflow trigger
voice_agentReal-time voice conversations via ElevenLabs + WebRTCInbound call
saathi_cfoEmail/bank transaction extraction and CFO advisoryOAuth sync / webhook

5.3 Autonomy Levels

LevelBehaviour
0–20Supervised — Agent drafts only; human must approve every action
21–50Assisted — Auto-executes low-risk actions; HITL on medium/high impact
51–80Automated — Auto-executes medium-risk; HITL on high impact only
81–100Fully Autonomous — Auto-executes all actions except irreversible changes

6. Data Architecture

6.1 Multi-Tenancy Pattern

  • Every table has a tenant_id column with a Row-Level Security policy
  • RLS policies use current_setting('app.current_tenant') to isolate data
  • Bypass: set_config('app.bypass_rls', 'on', true) — used only for system/admin operations
  • Internal M2M calls pass x-tenant-id header; Python service sets RLS context accordingly

6.2 Key Tables (TypeScript/Drizzle)

TablePurpose
tenantsTenant registry with tier, plan, domain, feature flags
userPlatform users with role, tenantId, OAuth tokens
workflow_proposalsAI-generated workflow suggestions awaiting HITL approval
agent_task_logBullMQ job lifecycle tracking per tenant
agent_milestone_logStep-level milestone tracking for visual reasoning graph
autonomy_configPer-tenant, per-domain autonomy level settings
change_impact_logImmutable record of every AI-applied change
user_transactionsSaathi CFO extracted financial transactions
user_subscriptionsDetected recurring subscriptions per user
bank_connectionsEncrypted Plaid access tokens per user
aeo_audit_runsGEO/AEO brand visibility audit results (managed by Python service)
aeo_competitor_analysisCompetitor citation tracking (managed by Python service)
seo_page_freshnessContent freshness scores per URL
aeo_referral_eventsLLM-sourced UTM referral click events

6.3 Queue Architecture (BullMQ)

QueuePurpose
bizosaas-agent-taskAll AI agent job execution
bizosaas-email-syncGmail/Outlook OAuth transaction sync
bizosaas-plaid-syncBank transaction sync via Plaid webhooks
bizosaas-workflowCompiled workflow DAG job chains
bizosaas-cronScheduled reports, NPS surveys, AEO digests

7. Self-Improvement & Learning Architecture

The platform is designed to continuously improve through:

7.1 Telemetry → Fine-tuning Loop

  1. Every LLM call is logged as structured JSONL (prompt, response, model, tenant, outcome)
  2. JSONL datasets accumulate in the observability store
  3. Periodic fine-tuning jobs train localised open-source models (Mistral, Llama) on platform-specific patterns
  4. Fine-tuned models are swapped in via OpenRouter custom model routing

7.2 RAG Knowledge Base

  • Client website content is vectorised via pgvector into the embeddings store
  • Agents retrieve relevant context before every LLM call, reducing hallucinations
  • Freshness monitor ensures embeddings stay current as content changes

7.3 Feedback Loops

  • CSAT surveys → training signal for support agent quality
  • HITL approval/rejection patterns → autonomy level calibration
  • AEO audit deltas → content remediation effectiveness measurement
  • NPS promoter/detractor split → product roadmap prioritisation signal

8. Security Architecture

8.1 Principles (without exposing implementation details)

  • Zero-trust: Every request is authenticated; no implicit trust between services
  • Least privilege: Users and agents only access resources scoped to their tenant/role
  • Audit everything: Every state change is immutably logged with actor identity
  • Secrets never in code: All secrets (API keys, tokens, encryption keys) are in Infisical/environment variables only
  • GDPR by design: Consent flags, suppression lists, right-to-erasure workflows built in

8.2 What AI Documentation Agents MUST NOT include in public-facing docs

  • Internal API token values or formats
  • Database connection strings or schema details beyond public API contracts
  • Encryption key derivation methods
  • Production infrastructure hostnames or IP ranges
  • Specific vulnerability mitigations or security bypass patterns

9. Deployment & Infrastructure

ComponentTechnologyNotes
FrontendNext.js 15 on DockerMulti-port: 3000 (app), 3001 (admin), 3002 (partner)
AI ServiceFastAPI on DockerPort 8000; DISABLE_AUTH=false in prod
AI Agents WorkerPython async on DockerShares same FastAPI codebase; separate container
DatabasePostgreSQL 16Shared instance; RLS provides tenant isolation
QueueRedis 7BullMQ connection; also used for session caching
CMSPayload CMS 3.0Separate Next.js app on port 3003
Reverse ProxyCaddy / NginxSubdomain routing: app.*, admin.*, partner.*

10. Roadmap — Next Phases

PhaseFocusTimeline
Phase 15WhatsApp full integration (remove ENABLE_WHATSAPP_DELIVERY flag)Q3 2026
Phase 16JIT Security, field-level encryption, WebAuthnQ4 2026
Phase 10CSaathi monetization model (usage-based pricing for CFO service)Q2 2027
Phase 36Multi-language platform UI (Hindi, Tamil, Arabic, Spanish)Q1 2027
Phase 37Mobile apps (React Native) for client and partner portalsQ2 2027
Phase 38On-premise / private cloud deployment optionQ3 2027

11. Documentation Conventions for AI Agents

When generating user-facing documentation from this reference, follow these rules:

  1. Role scoping: Every doc page must specify which role it applies to (Client / Partner / Admin / Super Admin)
  2. No secrets: Never include tokens, keys, passwords, or internal service URLs
  3. Feature flags: Note when a feature is behind a flag (e.g., WhatsApp requires ENABLE_WHATSAPP_DELIVERY=true)
  4. Beta labels: Saathi AI and QuantTrade are BETA — label them clearly
  5. HITL transparency: Always explain that AI-generated actions require human approval unless autonomy level is set to 80+
  6. Tone: Professional, confident, jargon-free. Assume the reader is a business owner, not an engineer
  7. Version: Include Last updated date on all generated docs; pull from git log on the relevant files

Last updated: 2026-07-15 | Platform version: Production (commit 6e0e374db) | All phases 1–35 complete. Phase 10C, 15, 16 intentionally deferred per roadmap.