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.
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:
| Pillar | Principle |
|---|
| Security | Zero-trust by default; RLS on every table; secrets in vault only; JIT access model |
| Scalability | Horizontal worker scaling via BullMQ; multi-tenant schema isolation; PostgreSQL + Redis |
| Autonomy | Configurable autonomy levels (0–100) per domain; HITL gates at every high-impact action |
| Quality | Gold-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/
- 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
| Module | Description | Status |
|---|
| Multi-tenant Middleware | Subdomain detection → tenant context → RLS activation | ✅ Live |
| Role-Based Access Control | user.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 Governance | Partner policies, switch requests, platform boundaries | ✅ Live |
| Autonomy Engine | Per-domain autonomy levels, HITL routing, kill switches | ✅ Live |
| Audit Log | Immutable record of every agent and human action | ✅ Live |
4.2 CRM & Sales
| Feature | Description |
|---|
| Contacts & Accounts | Full contact management with lead scoring, lifecycle stages |
| Deals & Pipelines | Visual kanban pipeline with AI deal-stage automation rules |
| Activities | Call, email, meeting, note logging per contact/deal |
| Teams & Lists | Team ownership, segmented CRM lists, member management |
| AI Follow-Up Engine | AI drafts 3 personalised follow-up variants for stalled deals |
| Churn Prediction | Weekly ML scoring (0–100) flags at-risk accounts for proactive outreach |
| Revenue Forecasting | Probability-weighted pipeline forecast exported as PDF |
4.3 Omni-Channel Marketing
| Feature | Description |
|---|
| Campaign Builder | Email, SMS, push, WhatsApp campaigns with visual editor |
| Dynamic Segmentation | Real-time audience lists built from behavioural signals |
| Subject Line Optimizer | 5 AI subjects → 3-way split test → auto-selects statistical winner |
| Compliance Guard | DMARC/SPF/DKIM validation; CAN-SPAM/GDPR flag detection; suppression list management |
| SMS Flow Builder | Visual SMS sequence builder with delay nodes, branch conditions, opt-out gates |
| A/B Testing | Multi-variant send-time optimizer per segment |
4.4 E-Commerce Operations
| Feature | Description |
|---|
| Multi-channel Sync | Shopify, WooCommerce, Amazon inventory and order sync via BullMQ workers |
| Abandoned Cart Recovery | WhatsApp (1h) → Email (6h) → SMS (24h) cascade, stops on purchase |
| Dynamic Pricing Agent | Competitor price scrape every 6h; suggests adjustment with margin impact; HITL gate |
| Inventory Alert Agent | Auto-drafts re-order PO when SKU hits threshold; HITL approval |
| Refund Classification | Auto-approves low-risk returns; escalates disputes to HITL queue |
| Product Launch Coordinator | Single trigger → simultaneous social, email, ad, Shopify activation |
| Post-Purchase Sequence | Review request → upsell → loyalty points over 30 days via BullMQ delays |
4.5 AI Workforce & Agents
| Feature | Description |
|---|
| Agent Registry | List, enable/disable, and monitor all AI agents per tenant |
| Agent Observatory | Real-time BullMQ job metrics (completed, failed, active, waiting) |
| Visual Workflow Builder | React Flow drag-and-drop DAG compiler → BullMQ job chains |
| NL Workflow Composer | Natural language → structured workflow proposal; HITL before deployment |
| HITL Dashboard | Pending agent tasks requiring human approval with impact scores |
| Kill Switch | Instant workforce pause/resume per tenant (admin-only) |
| Telemetry & Fine-tuning | Structured JSONL logs of all LLM interactions for dataset generation |
| Multi-Modal Pipeline | Text → Image → Video generation via OpenRouter + ElevenLabs |
| Voice Agents | WebRTC/ElevenLabs real-time voice agents for conversational sales |
4.6 Saathi AI — Personal CFO & Senior Business Assistant
| Feature | Description |
|---|
| Senior Assistant Agent | Context-aware business assistant across 4 personas (CFO, CMO, CTO, COO) |
| Email Intelligence | Gmail/Outlook OAuth sync; LLM + regex extraction of transactions from receipts |
| Bank Sync | Plaid integration for real-time transaction sync via BullMQ webhooks |
| Subscription Tracker | Auto-detects recurring SaaS subscriptions; flags waste and optimises cost |
| Transaction Dashboard | Categorised spend view, income tracking, budget analysis |
| WhatsApp Delivery | Conversational AI replies via WhatsApp Business API (controlled by ENABLE_WHATSAPP_DELIVERY flag) |
4.7 GEO / AEO — Generative Engine Optimisation
| Feature | Description |
|---|
| AI Share of Voice Audit | Queries GPT-4o, Claude, DeepSeek, Gemini with brand-intent search phrases; measures citation rate |
| Competitor Analysis | Tracks competitor brands cited by LLMs; aggregated in aeo_competitor_analysis table |
| GEO Remediation Editor | RAG-powered gap analysis; generates HTML copy rewrites for uncited queries |
| Content Freshness Monitor | Crawls priority pages; scores freshness (0–100); alerts on stale content |
| Topic Cluster Mapper | Groups sitemap into pillar-spoke architecture; identifies orphan pages |
| AI Citation Referral Tracker | UTM-tagged LLM referral clicks stored in aeo_referral_events table |
| JSON-LD Schema Injector | Auto-generates structured data schemas (Organization, FAQPage, HowTo) |
4.8 Customer Support Intelligence
| Feature | Description |
|---|
| Unified Inbox | Cross-platform conversation view (WhatsApp, Email, Social) with AI reply drafts |
| Ticket Priority Classifier | ML model scores urgency + business impact; SLA auto-starts |
| RAG Reply Quality Scorer | Scores HITL draft 0–100 against quality rubric; auto-regenerates low scores |
| Multi-Language Routing | Language detection → locale-specific reply templates (Hindi, Tamil, Arabic, Spanish, French, Telugu) |
| Customer Health Timeline | Full journey (purchases, emails, churn risk, support) in ticket sidebar |
| CSAT Auto-Survey | 24h after close → 1-question SMS survey → logs to csat_responses |
| Feature | Description |
|---|
| Unified Analytics Model | analytics_events captures every action with channel, cost, revenue attribution |
| Media Mix Modeling | Monthly attribution analysis across paid, organic, social, AI referral channels |
| Cross-Channel ROAS Dashboard | Side-by-side ROAS, CAC, LTV per channel with 30/90/365-day windows |
| AI Agent Scorecard | Per-agent: tasks, success rate, latency, cost, estimated revenue generated |
| Custom Report Builder | Drag-and-drop metrics, export PDF/CSV, schedule email delivery |
| Anomaly Detector | Flags statistical outliers (>20% conversion drop, cost-per-lead spike) |
| QBR Deck Generator | AI compiles 90-day data into Google Slides / PDF for account reviews |
4.10 Customer Retention & Advocacy (Phase 32)
| Feature | Description |
|---|
| Account Health Score | Composite score (workflow frequency, feature adoption, support volume, payment history) per tenant; live in /admin/tenants/[id] |
| At-Risk Intervention | Health < 40 → personalised email + in-app banner + Slack CSM alert |
| Feature Adoption Nudge | Identifies unused high-value features; sends contextual in-app tips |
| Expansion Trigger | 80% quota hit → AI generates personalised upgrade proposal; HITL before send |
| NPS Survey Engine | Auto-send at days 30/90/180; routes promoters (9–10) to G2 review flow |
| G2 Review Automation | Personalised email with direct G2 link + optional gift card incentive |
| Referral Programme | Track referral link sharing → conversion → trigger reward via BillingService |
| Feature | Description |
|---|
| Confidence-Based HITL Matrix | Configurable thresholds per action type (email blast, price change, CRM update) |
| Audit Log API | Every agent and human action logged: actor, action, resource, before/after state, IP |
| GDPR / DMARC Compliance Agent | Weekly automated scan; flags missing consent, unsubscribe violations, DMARC failures |
| Workflow Rollback Engine | Any AI-executed change can be rolled back with one click from the audit log |
4.12 Payload CMS (Phase 9E)
| Feature | Description |
|---|
| Headless CMS | Payload 3.0 powers Bizoholic.com and Thrillring.com content |
| Collections | Blog posts, pages, team members, testimonials, products per brand |
| Multi-tenant support | Each internal brand has isolated collection namespaces |
| ISR & SSG | Content changes trigger ISR revalidation on the public-facing Next.js sites |
4.13 Ecosystem & Marketplace (Phase 35)
| Feature | Description |
|---|
| Agent Marketplace | Publish, version, and monetise custom AI agents; certification workflow |
| Workflow Template Library | Pre-built one-click templates (e.g., "Shopify + WhatsApp Cart Recovery") |
| White-Label Client Portals | Partners brand BizOSaaS as their own platform (domain + logo + colours) |
| API Developer Hub | Public REST API docs, SDK (Python, JS), webhooks, sandbox |
| Revenue Share Programme | Partners 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
| Agent | Purpose | Trigger |
|---|
senior_assistant_agent | Context-aware business advice across 4 C-suite personas | Chat prompt |
aeo_agent | GEO/AEO brand visibility audit across LLMs | Scheduled / manual |
crm_agent | Deal automation, follow-ups, churn prediction | BullMQ cron |
email_agent | Campaign drafting, personalisation, send-time optimisation | Campaign trigger |
seo_audit_crew | Technical SEO + schema validation + freshness crawl | Scheduled |
multi_modal_agent | Text → Image → Video pipeline | Workflow trigger |
voice_agent | Real-time voice conversations via ElevenLabs + WebRTC | Inbound call |
saathi_cfo | Email/bank transaction extraction and CFO advisory | OAuth sync / webhook |
5.3 Autonomy Levels
| Level | Behaviour |
|---|
| 0–20 | Supervised — Agent drafts only; human must approve every action |
| 21–50 | Assisted — Auto-executes low-risk actions; HITL on medium/high impact |
| 51–80 | Automated — Auto-executes medium-risk; HITL on high impact only |
| 81–100 | Fully 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)
| Table | Purpose |
|---|
tenants | Tenant registry with tier, plan, domain, feature flags |
user | Platform users with role, tenantId, OAuth tokens |
workflow_proposals | AI-generated workflow suggestions awaiting HITL approval |
agent_task_log | BullMQ job lifecycle tracking per tenant |
agent_milestone_log | Step-level milestone tracking for visual reasoning graph |
autonomy_config | Per-tenant, per-domain autonomy level settings |
change_impact_log | Immutable record of every AI-applied change |
user_transactions | Saathi CFO extracted financial transactions |
user_subscriptions | Detected recurring subscriptions per user |
bank_connections | Encrypted Plaid access tokens per user |
aeo_audit_runs | GEO/AEO brand visibility audit results (managed by Python service) |
aeo_competitor_analysis | Competitor citation tracking (managed by Python service) |
seo_page_freshness | Content freshness scores per URL |
aeo_referral_events | LLM-sourced UTM referral click events |
6.3 Queue Architecture (BullMQ)
| Queue | Purpose |
|---|
bizosaas-agent-task | All AI agent job execution |
bizosaas-email-sync | Gmail/Outlook OAuth transaction sync |
bizosaas-plaid-sync | Bank transaction sync via Plaid webhooks |
bizosaas-workflow | Compiled workflow DAG job chains |
bizosaas-cron | Scheduled reports, NPS surveys, AEO digests |
7. Self-Improvement & Learning Architecture
The platform is designed to continuously improve through:
7.1 Telemetry → Fine-tuning Loop
- Every LLM call is logged as structured JSONL (prompt, response, model, tenant, outcome)
- JSONL datasets accumulate in the observability store
- Periodic fine-tuning jobs train localised open-source models (Mistral, Llama) on platform-specific patterns
- 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
| Component | Technology | Notes |
|---|
| Frontend | Next.js 15 on Docker | Multi-port: 3000 (app), 3001 (admin), 3002 (partner) |
| AI Service | FastAPI on Docker | Port 8000; DISABLE_AUTH=false in prod |
| AI Agents Worker | Python async on Docker | Shares same FastAPI codebase; separate container |
| Database | PostgreSQL 16 | Shared instance; RLS provides tenant isolation |
| Queue | Redis 7 | BullMQ connection; also used for session caching |
| CMS | Payload CMS 3.0 | Separate Next.js app on port 3003 |
| Reverse Proxy | Caddy / Nginx | Subdomain routing: app.*, admin.*, partner.* |
10. Roadmap — Next Phases
| Phase | Focus | Timeline |
|---|
| Phase 15 | WhatsApp full integration (remove ENABLE_WHATSAPP_DELIVERY flag) | Q3 2026 |
| Phase 16 | JIT Security, field-level encryption, WebAuthn | Q4 2026 |
| Phase 10C | Saathi monetization model (usage-based pricing for CFO service) | Q2 2027 |
| Phase 36 | Multi-language platform UI (Hindi, Tamil, Arabic, Spanish) | Q1 2027 |
| Phase 37 | Mobile apps (React Native) for client and partner portals | Q2 2027 |
| Phase 38 | On-premise / private cloud deployment option | Q3 2027 |
11. Documentation Conventions for AI Agents
When generating user-facing documentation from this reference, follow these rules:
- Role scoping: Every doc page must specify which role it applies to (Client / Partner / Admin / Super Admin)
- No secrets: Never include tokens, keys, passwords, or internal service URLs
- Feature flags: Note when a feature is behind a flag (e.g., WhatsApp requires
ENABLE_WHATSAPP_DELIVERY=true)
- Beta labels: Saathi AI and QuantTrade are BETA — label them clearly
- HITL transparency: Always explain that AI-generated actions require human approval unless autonomy level is set to 80+
- Tone: Professional, confident, jargon-free. Assume the reader is a business owner, not an engineer
- 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.