# Self-Hosted SaaS AI Sales Widget
## Production Development Plan for Antigravity

> This document is the single source of truth for building the application.
> Build it like a real production SaaS product, not like a demo, template, or
> "AI-generated dashboard".
>
> IMPORTANT: Do not blindly generate the entire application in one pass.
> Inspect the existing repository first, preserve working functionality, then
> implement the system in controlled phases.

---

# 1. Product Definition

Build a production-grade, self-hostable SaaS platform that allows businesses
to create AI sales agents and embed them into any website using a lightweight
JavaScript widget.

Working product concept:

**AI Sales Agent for Any Website**

Core flow:

1. User creates an account.
2. User creates a workspace/business.
3. User creates an AI sales agent.
4. User provides business information and knowledge sources.
5. System processes the knowledge.
6. User configures the widget.
7. System generates an installation snippet.
8. User installs the snippet on any website.
9. Website visitors interact with the AI agent.
10. AI answers questions using the configured knowledge.
11. AI attempts to convert visitors into leads.
12. Conversations and leads appear in the dashboard.
13. User can inspect analytics and manage the agent.

The product must feel like a serious commercial SaaS application.

It must NOT feel like:

- A generic admin template
- A generated CRUD application
- A university project
- A prototype
- A collection of unrelated pages
- An AI-generated UI with excessive cards, gradients, animations, or fake data

---

# 2. Primary Product Goals

The application must prioritize:

1. Reliability
2. Security
3. Maintainability
4. Clear information architecture
5. Fast user workflows
6. Excellent responsive UI
7. Multi-tenant data isolation
8. Production-ready validation and error handling
9. Real analytics based on real database data
10. Easy self-hosted deployment

Every feature must have:

- Proper database design
- Backend validation
- Authorization
- Error handling
- Loading states
- Empty states
- Success states
- Failure states
- Responsive behavior
- Security considerations
- Appropriate tests where practical

---

# 3. Technology Direction

Use the existing project stack if already established.

If the project is currently a fresh Laravel application, use:

Backend:
- Laravel 12
- PHP 8.2+
- MySQL 8+ or compatible MariaDB
- Laravel queues
- Laravel scheduler
- Laravel cache
- Laravel filesystem

Frontend:
- Use the existing frontend architecture if present.
- If no frontend architecture exists, use Laravel Blade + Livewire where
  appropriate, or the project's established modern frontend stack.
- Tailwind CSS for styling.
- Alpine.js only for lightweight client-side interactions if required.

Widget:
- Standalone JavaScript bundle.
- Do not require React, Vue, or another framework on the customer's website.
- The widget must work on plain HTML, WordPress, Laravel, React, Next.js,
  Shopify-like environments, and other normal websites.

AI:
- Create an abstraction layer around the AI provider.
- Never hard-code the entire application to one provider.
- Provider configuration must be environment driven.
- Keep AI provider logic separate from business logic.

Architecture principle:

Controllers -> Actions/Services -> Repositories/Models where appropriate

Do not put complex business logic directly inside controllers.

---

# 4. Repository Inspection Before Coding

Before changing anything, inspect:

- Existing Laravel version
- PHP version
- composer.json
- package.json
- .env.example
- routes
- app structure
- existing models
- migrations
- middleware
- authentication
- frontend architecture
- Tailwind configuration
- Vite configuration
- existing components
- existing tests
- storage configuration

Create a short internal implementation map before coding.

Do NOT delete existing functionality unless it is demonstrably broken and
replacement is required.

Do NOT recreate files that already contain useful implementation.

Do NOT introduce a second frontend framework without a clear reason.

---

# 5. High-Level Architecture

Core domains:

- Authentication
- Workspaces
- Members
- Roles & Permissions
- AI Agents
- Agent Instructions
- Knowledge Bases
- Knowledge Sources
- Website Crawling
- Documents
- Document Processing
- Embeddings / Retrieval
- Conversations
- Messages
- Leads
- Lead Statuses
- Widget Configuration
- Widget Sessions
- Analytics
- API Keys
- Integrations
- Notifications
- Billing
- System Administration
- Audit Logs
- Settings

Recommended relationship:

User
  |
  +-- Workspace
        |
        +-- Members
        +-- Agents
        |     |
        |     +-- Knowledge Base
        |     +-- Widget
        |     +-- Conversations
        |     +-- Leads
        |     +-- Analytics
        |
        +-- API Keys
        +-- Integrations
        +-- Billing
        +-- Settings

---

# 6. Multi-Tenancy

This is a critical requirement.

Every customer-owned record must be scoped to a workspace/tenant.

Never trust workspace IDs submitted directly by the browser.

Always resolve the active workspace from authenticated membership/context and
authorize every resource access.

Prevent:

- Cross-workspace conversation access
- Cross-workspace lead access
- Cross-workspace agent access
- Cross-workspace knowledge access
- Cross-workspace API key access
- Cross-workspace analytics access

Use policies and server-side authorization consistently.

Add tests specifically for tenant isolation.

---

# 7. Authentication

Implement a proper authentication system.

Required:

- Registration
- Login
- Logout
- Password reset
- Email verification if supported by the project
- Remember session
- Session security
- Account settings
- Password change

Do not build fake authentication.

Authentication state must be handled server-side.

---

# 8. Workspace System

A user should operate inside a workspace.

Workspace fields should include appropriate values such as:

- id
- name
- slug
- logo
- timezone
- locale
- status
- created_at
- updated_at

Workspace membership:

- owner
- admin
- member
- custom permissions only if genuinely required

Workspace switcher must be available from the authenticated application.

Do not allow users to access workspaces where they are not members.

---

# 9. Roles and Permissions

Implement authorization at the backend level.

Minimum roles:

Owner
Admin
Member

Permissions should cover:

- Manage workspace
- Manage members
- Manage agents
- Manage knowledge
- View conversations
- Manage leads
- Manage integrations
- Manage billing
- View analytics
- Manage API keys

Do not rely only on hidden frontend buttons for security.

---

# 10. User Application Panel

The main user panel should be the core product experience.

Navigation:

- Dashboard
- Inbox
- Conversations
- Leads
- Agents
- Knowledge
- Analytics
- Integrations
- Settings

Potential secondary navigation:

- Workspace
- Team
- API Keys
- Billing

Use clear grouping instead of a huge navigation menu.

---

# 11. User Dashboard

The dashboard must use real database data.

Do NOT ship hard-coded fake analytics.

Top-level metrics:

- Conversations
- Messages
- Leads
- Conversion Rate
- Active Agents
- Knowledge Sources

Time range:

- 7 days
- 30 days
- 90 days
- Custom where practical

Charts should communicate useful information.

Example:

Conversation trend
Lead trend
Conversion trend

Additional sections:

- Recent conversations
- Recent leads
- Agent performance
- Lead pipeline
- Knowledge health
- System status

If there is no data, show useful empty states instead of fake numbers.

---

# 12. Inbox / Conversations

Build a serious customer-support/sales inbox.

Layout:

Left:
Conversation list

Center:
Conversation thread

Right:
Visitor/lead details

Conversation list should support:

- Search
- Agent filter
- Status filter
- Lead filter
- Date filter
- Sort
- Unread state

Conversation states:

- Open
- Pending
- Resolved
- Archived

Conversation details:

- Visitor
- Agent
- Source URL
- Started at
- Last activity
- Lead information
- Tags
- Metadata

Message types:

- Visitor
- AI agent
- System
- Human agent if handoff exists

Never fake message history.

---

# 13. Lead Management

Build a lightweight CRM-style lead system.

Lead fields:

- Name
- Email
- Phone
- Company
- Source
- Agent
- Conversation
- Status
- Score
- Notes
- Metadata
- Created at
- Updated at

Pipeline:

- New
- Qualified
- Contacted
- Won
- Lost

Allow:

- Search
- Filter
- Sort
- Status update
- Lead detail view
- Conversation link
- Notes

Keep it simple and useful.

Do not turn the MVP into a full CRM.

---

# 14. AI Agent Builder

This is one of the most important screens.

Agent creation flow:

Step 1:
Basic information

- Agent name
- Business name
- Description

Step 2:
Behavior

- Primary goal
- Tone
- Language
- Response style
- Sales objective
- Rules

Step 3:
Knowledge

- Website
- Documents
- Manual text

Step 4:
Lead capture

- Name
- Email
- Phone
- Company
- Custom fields if implemented

Step 5:
Widget

- Brand
- Position
- Welcome message
- Avatar
- Display settings

Step 6:
Test

Provide a real test chat interface.

Step 7:
Publish

Publishing should produce an active agent and installation snippet.

---

# 15. Agent Configuration

Agent should support:

- Name
- Status
- System instructions
- Business context
- Sales objective
- Allowed topics
- Disallowed topics
- Tone
- Language
- Lead capture rules
- Human handoff rules
- Knowledge settings
- Widget settings

Agent status:

- Draft
- Active
- Paused
- Archived

Never expose secrets in the browser.

---

# 16. AI Provider Abstraction

Create a clean provider interface.

Conceptually:

AIProviderInterface

Methods may include:

- generateResponse()
- streamResponse()
- createEmbedding()
- estimateUsage()

Implement provider-specific classes separately.

The rest of the application should not need to know which provider is being
used.

Environment variables should hold credentials.

Never store provider API keys in frontend JavaScript.

---

# 17. AI Response Pipeline

A normal message should follow a predictable pipeline:

1. Validate request
2. Identify widget/agent
3. Validate agent status
4. Create/find visitor session
5. Create conversation
6. Store visitor message
7. Retrieve relevant knowledge
8. Build AI context
9. Apply agent instructions
10. Call AI provider
11. Validate response
12. Store AI message
13. Update conversation metadata
14. Detect lead information
15. Update analytics
16. Return/stream response

Keep each responsibility separated.

Do not implement the entire pipeline inside one controller method.

---

# 18. Knowledge Base

Knowledge should belong to an agent or workspace in a controlled manner.

Source types:

- Website URL
- Sitemap
- PDF
- TXT
- DOC/DOCX where supported
- Manual text

Knowledge source states:

- Pending
- Processing
- Indexed
- Failed
- Disabled

Show processing progress.

Show errors clearly.

---

# 19. Website Crawler

Implement website ingestion carefully.

Requirements:

- Validate URL
- Restrict supported schemes
- Respect reasonable crawl limits
- Prevent server-side request abuse
- Prevent internal/private network access
- Avoid localhost/private IP targets
- Apply timeouts
- Apply response size limits
- Normalize URLs
- Avoid duplicate URLs
- Store crawl status
- Queue long-running work

Never perform unrestricted server-side URL fetching.

Protect against SSRF.

---

# 20. Document Processing

Document processing must be asynchronous for non-trivial files.

Pipeline:

Upload
  ->
Validate
  ->
Store
  ->
Queue processing
  ->
Extract text
  ->
Clean text
  ->
Chunk
  ->
Create embeddings
  ->
Store vectors/metadata
  ->
Mark indexed

Never make the browser wait for a large document indexing job.

---

# 21. Retrieval / RAG

Implement a clean retrieval layer.

Conceptual pipeline:

User Question
  ->
Query preparation
  ->
Embedding
  ->
Similarity search
  ->
Relevant chunks
  ->
Context assembly
  ->
AI model
  ->
Response

Store metadata with chunks:

- source
- title
- URL
- chunk index
- agent/workspace
- document ID

Retrieved content must always be tenant-scoped.

---

# 22. Website Widget

The widget is the product's external-facing surface.

Requirements:

- Small initial payload
- Async loading
- No framework dependency on host website
- Responsive
- Mobile friendly
- Accessible
- Keyboard usable
- Configurable
- Cross-browser compatible

Embed example:

```html
<script
    src="https://YOUR-DOMAIN.com/widget.js"
    data-agent="AGENT_PUBLIC_ID">
</script>
```

Do not expose:

- Database credentials
- Internal API keys
- AI provider secrets
- Private workspace information

Use public agent identifiers/tokens designed specifically for widget access.

---

# 23. Widget UX

Default widget should include:

- Floating launcher
- Chat window
- Header
- Agent identity
- Welcome message
- Message list
- Input
- Send button
- Loading state
- Error state
- Lead capture UI when triggered
- Mobile full-screen behavior where appropriate

Support:

- Enter to send
- Shift+Enter for newline if appropriate
- Auto-scroll
- Streaming response if implemented
- Retry failed response
- Clear conversation where appropriate

Avoid unnecessary animations.

---

# 24. Widget Security

Public widget endpoints must be hardened.

Requirements:

- Rate limiting
- Origin validation where appropriate
- Abuse prevention
- Message size limits
- Request validation
- Session validation
- Agent status validation
- CORS policy
- Bot/abuse protection strategy
- No secret exposure

Never trust:

- agent ID alone for private operations
- client-provided workspace ID
- client-provided conversation owner
- client-provided lead ownership

---

# 25. Widget Customization

Settings:

- Primary color
- Position
- Avatar
- Agent name
- Welcome text
- Placeholder
- Language
- Border radius
- Button style
- Show/hide branding where licensing permits
- Opening behavior

Provide live preview.

Do not make the settings page visually overloaded.

---

# 26. Installation Page

Each agent should have a clear installation page.

Show:

1. Installation instructions
2. Copyable script
3. Platform guidance
4. Test widget
5. Domain configuration
6. Widget status

Example:

```html
<script
    src="https://YOUR-DOMAIN.com/widget.js"
    data-agent="PUBLIC_AGENT_ID">
</script>
```

Include examples for:

- HTML
- WordPress
- Laravel
- React/Next.js

Only provide instructions that actually match the implemented system.

---

# 27. Analytics

Analytics must come from real events.

Track useful events such as:

- Widget opened
- Conversation started
- Message sent
- Lead captured
- Conversation resolved
- Conversion

Metrics:

- Total conversations
- Unique visitors
- Messages
- Leads
- Conversion rate
- Average messages per conversation
- Agent performance

Avoid vanity metrics that do not help users sell.

---

# 28. Integrations

Prepare an integrations architecture.

Initial architecture should support:

- API
- Webhooks

Future integrations can include:

- WhatsApp
- Email
- CRM
- Calendar
- Slack
- Zapier/Make-like automation

Do not implement every integration in the MVP.

Build extension points correctly.

---

# 29. API

Create versioned APIs.

Example:

```text
/api/v1/...
```

Separate:

- Public widget endpoints
- Authenticated application endpoints
- Admin endpoints
- Webhook endpoints

Use:

- Form Requests
- API Resources
- Policies
- Rate limits
- Consistent JSON responses

Do not expose raw database models unnecessarily.

---

# 30. API Keys

Workspace API keys must:

- Be hashed at rest where appropriate
- Only show the full secret once
- Support revocation
- Have clear names
- Have created/last-used timestamps
- Be scoped where necessary

Never log full API secrets.

---

# 31. Notifications

Create a notification layer.

Potential notifications:

- Knowledge indexing completed
- Knowledge indexing failed
- New lead
- Agent errors
- Integration errors

Use queued notifications where appropriate.

---

# 32. Billing Architecture

Billing should be modular.

Do not hard-code billing logic throughout the application.

Plans may eventually contain:

- Agents
- Conversations
- Knowledge sources
- Team members
- API usage
- Features

The application should have a clear entitlement/checking layer.

Do not fake payment status.

If billing is not implemented initially, create clean boundaries so it can be
added later.

---

# 33. Admin Panel

Create a separate protected admin area.

Admin navigation:

- Overview
- Users
- Workspaces
- Agents
- Conversations
- Leads
- Knowledge
- System Health
- AI Usage
- API Usage
- Jobs
- Logs
- Settings
- Audit Logs

Admin must NOT simply be the user dashboard with extra buttons.

It should be designed around platform operations.

---

# 34. Admin Dashboard

Real system metrics:

- Total users
- Active workspaces
- Active agents
- Conversations
- Leads
- AI requests
- Failed jobs
- Knowledge indexing failures
- API errors

Operational sections:

- Recent signups
- Recent workspaces
- System errors
- Queue health
- AI provider status

Never use fake statistics in production.

---

# 35. Admin Security

Admin routes must have dedicated authorization.

Requirements:

- Admin middleware/policy
- Audit logging
- Sensitive action confirmation
- No accidental tenant data modification
- Secure impersonation only if implemented
- Never expose provider secrets
- Rate limiting on sensitive actions

---

# 36. Audit Logs

Record sensitive actions:

- Login events where appropriate
- Agent changes
- Workspace changes
- Member changes
- API key creation/revocation
- Integration changes
- Admin actions
- Billing changes
- Security-sensitive operations

Audit entries should include useful metadata without storing secrets.

---

# 37. Database Design

Use proper migrations.

Important tables may include:

- users
- workspaces
- workspace_members
- agents
- agent_settings
- knowledge_bases
- knowledge_sources
- documents
- document_chunks
- conversations
- conversation_messages
- visitors
- leads
- lead_notes
- widget_settings
- widget_sessions
- analytics_events
- api_keys
- integrations
- notifications
- audit_logs
- jobs-related tables where required

Add:

- foreign keys where appropriate
- indexes
- unique constraints
- nullable fields intentionally
- timestamps
- soft deletes only where justified

Do not add columns without a real purpose.

---

# 38. Database Performance

Index high-volume query paths.

Especially consider indexes for:

- workspace_id
- agent_id
- conversation_id
- visitor_id
- lead status
- created_at
- message timestamps
- analytics event timestamps

Avoid N+1 queries.

Use pagination.

Do not load entire conversation histories unnecessarily.

---

# 39. Background Jobs

Use queues for:

- Website crawling
- Document extraction
- Chunking
- Embedding
- Knowledge indexing
- Email notifications
- Heavy analytics processing
- Webhook delivery
- Other long-running tasks

Jobs should be:

- Retryable
- Idempotent where practical
- Observable
- Failure-aware

Do not make long-running AI/processing operations block normal HTTP requests.

---

# 40. Scheduled Tasks

Use Laravel scheduler for:

- Cleanup
- Expired sessions
- Old temporary files
- Analytics aggregation if needed
- Failed job maintenance
- Usage reset
- Other periodic maintenance

Do not rely on browser activity for scheduled operations.

---

# 41. Error Handling

Create proper error handling.

User-facing errors must be understandable.

Developer-facing logs must contain useful technical context.

Never display:

- SQL queries
- stack traces
- API keys
- environment variables
- server paths unnecessarily

Differentiate:

- validation error
- authorization error
- not found
- rate limit
- AI provider failure
- knowledge processing failure
- internal server error

---

# 42. Security Requirements

Treat security as a first-class feature.

Must address:

- CSRF
- XSS
- SQL injection
- mass assignment
- authorization
- authentication
- session security
- rate limiting
- SSRF
- file upload validation
- MIME validation
- file size limits
- path traversal
- secret handling
- CORS
- webhook verification
- tenant isolation
- API abuse

Never trust browser-provided ownership fields.

---

# 43. File Upload Security

For documents:

- Validate extension
- Validate MIME type
- Limit file size
- Generate safe stored names
- Never use original filename as storage path
- Store outside public directory when appropriate
- Scan/validate content where practical
- Process asynchronously

Never execute uploaded files.

---

# 44. UI / UX Direction

This is extremely important.

The UI must look like it was designed by an experienced product team.

Target characteristics:

- Premium
- Minimal
- Dense but readable
- Professional
- Consistent
- Calm
- High information quality
- Strong hierarchy
- Excellent spacing
- Excellent typography
- Subtle borders
- Subtle shadows
- Intentional color usage

Avoid:

- Excessive gradients
- Neon AI effects
- Giant glowing blobs
- Robot illustrations
- Random glassmorphism
- Excessive rounded cards
- Every section inside a card
- Huge unnecessary headings
- Excessive animations
- Generic "AI SaaS" visual clichés
- Fake charts
- Random purple gradients
- Over-designed empty states

---

# 45. UI System

Create a reusable design system.

Define:

- Typography
- Font sizes
- Font weights
- Spacing
- Border radius
- Shadows
- Inputs
- Buttons
- Badges
- Tabs
- Dropdowns
- Tables
- Modals
- Toasts
- Alerts
- Empty states
- Skeleton loaders
- Pagination
- Charts

Do not create slightly different buttons on every page.

Reuse components.

---

# 46. Responsive Design

Every user-facing screen must work on:

- Desktop
- Laptop
- Tablet
- Mobile

Do not simply shrink desktop UI.

Mobile navigation must be deliberately designed.

Conversation inbox must have an appropriate mobile interaction model.

Tables should become useful mobile layouts instead of overflowing blindly.

---

# 47. Loading / Empty / Error States

Every asynchronous feature needs:

Loading:
- skeleton or meaningful loading state

Empty:
- explain what is empty
- explain what to do next
- useful action

Error:
- explain failure
- retry action where appropriate

Success:
- clear confirmation

Never leave blank white/black areas when data is unavailable.

---

# 48. Forms

Forms must have:

- labels
- validation
- inline errors
- disabled/loading submit state
- success feedback
- unsaved-change protection where appropriate

Use backend validation as the source of truth.

Do not rely only on frontend validation.

---

# 49. Tables

Production tables should support:

- Search
- Filtering where useful
- Sorting where useful
- Pagination
- Bulk actions only when genuinely useful
- Row actions
- Responsive behavior

Do not add every possible table feature.

---

# 50. Real Data Only

After development is complete:

Search the project for obvious placeholder/fake production values.

Remove:

- Fake analytics
- Fake user names
- Fake conversation messages
- Fake leads
- Hard-coded dashboard metrics
- "Lorem ipsum"
- Demo company names
- Fake API responses used in production code

Seeders may contain demo data only if explicitly intended and clearly isolated.

---

# 51. Developer Experience

The project must be easy for another developer to understand.

Use:

- meaningful class names
- meaningful method names
- small focused services
- clear route naming
- clear model relationships
- clear config
- environment variables for secrets
- comments only where they explain non-obvious reasoning

Do not create giant files.

Do not create a 1,000-line controller.

Do not duplicate business logic.

---

# 52. Testing Strategy

At minimum, test critical paths.

Authentication:
- registration
- login
- authorization

Multi-tenancy:
- workspace isolation
- unauthorized resource access

Agents:
- create
- update
- publish
- pause

Knowledge:
- upload
- indexing state
- tenant isolation

Widget:
- valid public agent
- invalid agent
- rate limiting
- conversation creation

Conversations:
- message persistence
- authorization

Leads:
- creation
- status update

Admin:
- protected routes
- role authorization

Do not chase meaningless 100% coverage.

Prioritize business-critical behavior.

---

# 53. Deployment

The application must be deployable to a normal Linux VPS.

Prepare for:

- Nginx
- PHP-FPM
- MySQL/MariaDB
- Redis where required
- Supervisor for workers
- SSL
- Queue workers
- Scheduler
- Storage linking
- Environment configuration

Provide a deployment document covering:

1. Server requirements
2. PHP extensions
3. Composer
4. Node build
5. Environment variables
6. Database
7. Storage
8. Queue worker
9. Scheduler
10. Nginx
11. SSL
12. Permissions
13. Backup
14. Update procedure

---

# 54. Self-Hosted Requirement

The application must not depend on hidden infrastructure controlled by the
original developer.

A self-hosted installation should be able to run using configured:

- Database
- Cache/queue
- AI provider
- Storage
- Mail provider
- Application URL

Avoid unnecessary external dependencies.

If an external service is required, make it explicit in configuration.

---

# 55. Environment Configuration

Create/update `.env.example` with documented variables.

Never commit secrets.

Examples of configuration categories:

- APP
- DATABASE
- CACHE
- QUEUE
- MAIL
- FILE STORAGE
- AI PROVIDER
- WIDGET
- CORS
- BILLING
- WEBHOOKS

Use Laravel config files instead of reading `env()` throughout application
code.

---

# 56. Logging and Observability

Use structured, useful logging.

Log:

- critical application errors
- AI provider failures
- failed jobs
- webhook failures
- security-relevant events
- indexing failures

Never log:

- passwords
- API keys
- access tokens
- full sensitive user data

Add enough context to diagnose problems.

---

# 57. Production Readiness Checklist

Before considering the project complete:

## Backend

- [ ] Authentication works
- [ ] Authorization works
- [ ] Multi-tenancy works
- [ ] Policies implemented
- [ ] Validation implemented
- [ ] API responses are consistent
- [ ] Errors handled
- [ ] Rate limiting configured
- [ ] Queues configured
- [ ] Scheduled tasks configured
- [ ] Database indexes reviewed
- [ ] Sensitive data protected

## AI

- [ ] Provider abstraction
- [ ] Agent instructions
- [ ] Knowledge retrieval
- [ ] AI errors handled
- [ ] Usage tracking
- [ ] Rate limiting
- [ ] Secrets protected

## Widget

- [ ] Standalone script
- [ ] Responsive
- [ ] Accessible
- [ ] Public endpoints secured
- [ ] No secrets exposed
- [ ] Error handling
- [ ] Loading states
- [ ] Lead capture
- [ ] Conversation persistence

## User Panel

- [ ] Dashboard
- [ ] Inbox
- [ ] Conversations
- [ ] Leads
- [ ] Agents
- [ ] Knowledge
- [ ] Analytics
- [ ] Integrations
- [ ] Settings

## Admin

- [ ] Separate admin area
- [ ] Authorization
- [ ] Users
- [ ] Workspaces
- [ ] Agents
- [ ] System health
- [ ] Usage
- [ ] Jobs
- [ ] Audit logs

## UI

- [ ] Consistent design system
- [ ] Responsive
- [ ] Loading states
- [ ] Empty states
- [ ] Error states
- [ ] Accessible forms
- [ ] No fake production data
- [ ] No placeholder UI
- [ ] No broken links
- [ ] No console errors

## Deployment

- [ ] Production environment documented
- [ ] Queue worker documented
- [ ] Scheduler documented
- [ ] Storage documented
- [ ] SSL documented
- [ ] Backup strategy documented
- [ ] Update procedure documented

---

# 58. Implementation Order

Build in this order.

## Phase 0 — Repository Audit

Inspect the existing repository.

Do not change application behavior yet.

Document:

- current architecture
- dependencies
- existing features
- missing infrastructure
- recommended implementation order

## Phase 1 — Foundation

Implement:

- authentication
- workspace
- membership
- roles
- base layout
- design system
- settings
- database foundations

## Phase 2 — Agent System

Implement:

- agent CRUD
- agent configuration
- agent status
- agent testing interface
- publishing

## Phase 3 — Knowledge

Implement:

- knowledge sources
- website ingestion
- documents
- processing jobs
- chunks
- embeddings
- retrieval

## Phase 4 — AI Conversation Engine

Implement:

- visitor sessions
- conversations
- messages
- AI provider abstraction
- RAG pipeline
- streaming if appropriate
- error handling

## Phase 5 — Widget

Implement:

- widget bundle
- launcher
- chat
- streaming
- lead capture
- configuration
- installation snippet
- security

## Phase 6 — Leads and Inbox

Implement:

- inbox
- conversation management
- lead capture
- pipeline
- lead details

## Phase 7 — Analytics

Implement:

- event collection
- metrics
- charts
- agent analytics
- conversion analytics

## Phase 8 — Admin

Implement:

- admin dashboard
- user management
- workspace management
- system health
- usage
- jobs
- audit logs

## Phase 9 — Integrations / Billing Foundations

Implement only what is actually required.

Create clean extension points for future integrations.

## Phase 10 — Production Hardening

Review:

- security
- performance
- queues
- caching
- database indexes
- authorization
- tenant isolation
- error handling
- logging
- deployment

## Phase 11 — QA

Test the full system from:

1. New user registration
2. Workspace creation
3. Agent creation
4. Knowledge ingestion
5. Agent publishing
6. Widget installation
7. Visitor conversation
8. Lead capture
9. Dashboard analytics
10. Admin monitoring

Fix real issues.

---

# 59. Antigravity Operating Rules

These rules are mandatory while implementing this plan.

1. First inspect the repository.
2. Do not assume files are empty.
3. Do not overwrite working code unnecessarily.
4. Do not change unrelated functionality.
5. Implement one coherent phase at a time.
6. After each phase, run relevant tests/build checks.
7. Fix errors before continuing.
8. Never hide errors with hacks.
9. Never hard-code production secrets.
10. Never use fake data where real data is expected.
11. Never bypass authorization for convenience.
12. Never trust client-supplied tenant ownership.
13. Never create giant controllers.
14. Never put all logic into one service.
15. Do not create duplicate components.
16. Reuse the existing design system.
17. Do not introduce unnecessary dependencies.
18. Keep the UI consistent across the entire application.
19. Make responsive behavior intentional.
20. Make all important operations observable.
21. Prefer maintainable code over clever code.
22. Do not mark features complete until they actually work.
23. Do not use TODO comments as substitutes for implementation.
24. Do not leave broken placeholder screens.
25. Do not remove existing functionality unless explicitly required.
26. Do not fabricate APIs or integrations.
27. Verify routes, migrations, jobs, policies, and frontend calls together.
28. After major changes, check for N+1 queries and authorization gaps.
29. Before finalizing, perform a production-readiness review.
30. The finished application must look and behave like a product built by an
    experienced software engineering team.

---

# 60. Definition of Done

A feature is DONE only when:

- Database support exists
- Backend logic works
- Validation exists
- Authorization exists
- UI exists
- Loading state exists
- Empty state exists
- Error state exists
- Success state exists
- Responsive behavior works
- Relevant tests exist
- No obvious console errors remain
- No obvious server errors remain
- No fake production data remains
- Existing functionality still works

Do not call a visual screen "complete" if the underlying functionality is not
implemented.

---

# 61. Final Product Standard

The final product should communicate:

**"This is a real SaaS product."**

It should have:

- Professional user onboarding
- Excellent dashboard
- Real AI agent management
- Real knowledge processing
- Real conversations
- Real leads
- Real analytics
- Real admin operations
- Secure multi-tenancy
- Production-grade API
- Embeddable widget
- Self-hosted deployment capability
- Consistent visual language
- Strong error handling
- Maintainable architecture

The goal is not to generate the maximum amount of code.

The goal is to produce a coherent, secure, maintainable, production-ready
application where every part belongs to the same product.

---

# 62. Final Instruction to Antigravity

Treat this file as the master product and engineering specification.

Before implementation:

1. Read this entire file.
2. Inspect the repository.
3. Compare the current project against this specification.
4. Identify what already exists.
5. Identify what is missing.
6. Create an implementation plan based on the actual repository.
7. Implement in phases.
8. Verify each phase.
9. Fix issues before moving forward.
10. Keep the final application production-grade.

Do not interpret "AI-assisted development" as permission to cut engineering
corners.

Write the code as if another senior developer will review every file.

The finished product must not feel like a generated prototype.
It must feel like a deliberately engineered commercial SaaS application.
