Skip to Content

Documentation Index

This is the master index for the DM Agency AI Platform documentation.


Start Here

DocWhat it answers
IntroductionWhat Leadmetrics is, the problem it solves, key concepts, and where to go next
ArchitectureHow the system is structured — control plane, adapter pattern, phone-home callbacks
Architecture DiagramsNetwork diagrams — full system map, control plane internals, agent flow, data layer, deployment
Tech StackMonorepo structure, all packages and apps, technology choices
Workflow ModelThe operational flow: onboarding → strategy → goals → deliverables → activities

Developer Setup

DocWhat it covers
Local SetupPrerequisites, Docker, DB init, seed accounts, starting all 10 services, common issues
Environment VariablesEvery env var for every app and server — required vs optional, per-service grouping
CI/CD PipelineGitHub Actions jobs (lint, typecheck, unit tests), triggers, branch strategy, Coolify deployment

Core System

DocWhat it covers
Database — IndexDatabase folder overview, split pattern, quick decision guide
Database OverviewWhich data goes where and why — decision guide, key relationships
PostgreSQL SchemaFull PostgreSQL schema: all tables, indexes, useful queries
MongoDB CollectionsAll MongoDB collections with schemas, indexes, TTLs, and rationale
SQL Entity RelationsER diagrams for all 31 PostgreSQL tables and their relationships
NoSQL Entity RelationsMongoDB collections and their cross-references to PostgreSQL
Multi-TenancyTenant isolation, plans, subdomain routing, enterprise on-prem
InfrastructureDocker Compose, Coolify deployment, enterprise packaging
API GatewayGateway layer — request lifecycle, auth, audit logging, rate limiting, throttling, Option B future path
AdaptersAdapter pattern: Claude Code CLI, OpenAI, Ollama, Webhook — I/O mechanics per backend
Adapter — ClaudeClaude Code CLI subprocess: NDJSON stream, session resumption, --add-dir skills
Adapter — OpenAIOpenAI REST: SSE streaming, manual session history, Codex/o1 support
Adapter — OllamaLocal Ollama REST: NDJSON streaming, zero cost, data-local tasks
Adapter — WebhookAsync phone-home: enterprise custom runtimes, JWT callback auth
ScalabilityQueue design, partitioning, target: millions of activities/day
TestingThree-tier strategy: unit, integration (real DBs), E2E (Playwright)

Chat & Online Presence (docs/chat/)

DocWhat it covers
Overview & Framework DecisionWhy Socket.IO, scope by portal, feature summary
ArchitectureComponent diagram, auth flow, Redis layout, tenant isolation, multi-instance scaling
Data SchemaChatMessage Prisma model, Redis key conventions, retention
Event CatalogFull Socket.IO event reference — presence, chat, typing, read receipts
Implementation PlanFour-phase rollout: server setup, presence UI, chat panel, unread/notifications

Feature Docs (docs/features/)

DocWhat it covers
Agent HierarchyAll agents, roles, deliverable mapping, plan availability
Agent Execution EngineAdapter implementations, streaming, session, cost calculation
Task Queue & OrchestrationBullMQ, tenant-namespaced queues, activity pipeline progression
Skills SystemSkill injection, client context file, MongoDB storage
Session / Memory ManagementClaude session resumption, Ollama history management
Tool / Integration LayerExternal API integrations (SEMrush, GA4, WordPress, etc.)
Cost & Usage TrackingLLM cost tracking, budget caps, billing events
Governance & GuardrailsPermission whitelist, output validators, HITL enforcement
ObservabilityAudit logging, OpenTelemetry tracing, Grafana + Loki
RAG IntegrationHow RAG fits into Leadmetrics — two-layer context strategy, datasets, agent tool, onboarding flow
RAG ArchitectureTechnical design — Prisma schema, Qdrant collections, BullMQ ingestion pipeline, hybrid search

Insights (docs/insights/)

DocWhat it covers
OverviewFeature summary, supported channels, how it works, key design decisions
ArchitectureChannelInsight DB model, job data shapes, worker pattern, API routes, data flow
AgentsPer-channel agent specs — data fetched, system prompt focus, output sections
Implementation Plan6-phase build guide: DB → API → workers → cron → UI → prompt tuning
UI ScreensDashboard screens I1 (list), I2 (detail), I3 (channel tab), real-time update spec

Newsletters (docs/newsletters.md)

DocWhat it covers
NewslettersEmailNewsletter model, status machine (draft→dm_review→approved→sending→sent), API endpoints, Resend send flow, unsubscribe

Campaigns (docs/campaigns/)

DocWhat it covers
Overview & Campaign TypesFive campaign types, approval chain, existing foundations, open questions
Data ModelCampaign, CampaignEmail, CampaignMetrics, CampaignSequence models
AI AgentsWhich agents handle each campaign type
API RoutesAll campaign endpoints — tenant + DM portal
Dashboard UICampaigns hub, detail tabs, creation wizard
Workflow & PermissionsStatus machine, approval chain, notifications

CRM & Pipeline (docs/crm/)

DocWhat it covers
OverviewLead tracking, CRM vs Contacts distinction, contents
LeadsLead data model, capture sources, schema
PipelineLead lifecycle, statuses, qualification workflow
ActivitiesLead activity timeline, touchpoints
Lead ScoringScoring model, score bands, ranking logic
Nurture SequencesAutomated follow-up sequence model

Contacts (docs/contacts/)

DocWhat it covers
OverviewContacts vs CRM leads distinction
ContactsContact model, stages, sources, subscription management
Contact ListsStatic and dynamic lists, campaign audience targeting

Content Toolkit (docs/content/)

The full content creation, optimization, and distribution pipeline — from topic discovery to multi-channel publishing. See content/index.md for the feature map, gap analysis vs SEMrush, and build priority order.

DocStatusWhat it covers
OverviewFeature map, gap analysis, build priority, new credit rates
Content OptimizerTo Build · P1SEO, readability, brand voice, AI search scoring + in-editor guided fixes
Social PublishingTo Build · P1Scheduled + on-demand publishing to Facebook, Instagram, LinkedIn, TikTok, X
Repurposing Pipeline✅ ImplementedBlog → social posts, email newsletter, ads copy via content-repurposer agent
SEO Brief ExportTo Build · P2Shareable brief links, Google Docs export, brief compliance check
Mailchimp IntegrationTo Build · P2OAuth connect, draft campaign push, Mailchimp audience selector
Content AuditTo Build · P2Post freshness audit, health score, refresh workflow, cannibalisation detection
Multi-LanguageTo Build · P37-language support across all writer agents
Location TargetingTo Build · P3Geo-specific topics, keywords, and content for local service businesses
Performance FeedbackTo Build · P3GSC ingestion, ranking signals, performance-enriched refresh briefs
Blog Image GenerationTo Build · P3Hero + inline images via Azure GPT Image, brand-matched styles

Code Reviews (docs/code-reviews/)

DocWhat it covers
API Code Review v1Security & rate limiting audit — gaps between docs and implementation, fix priority order

New Features (docs/new-features/)

Comprehensive documentation for recently implemented features.

Content Repurposing Engine ✅ Implemented

Transform approved content into multiple platform-optimized derivatives with a single click. Includes template management portal and analytics dashboard.

DocWhat it covers
Complete Feature DocFull feature overview, architecture, implementation status, getting started
Implementation SummaryDetailed implementation notes, design decisions, component list
Migration GuideStep-by-step migration, database setup, worker configuration
Quick ReferenceHandy reference card, credit costs, user workflows, monitoring
Original Feature SpecOriginal specification and requirements

Key Features:

  • 🔄 Core Engine: 14 repurposing paths (blog→social/email/ads, etc.), 0.5 credits per derivative
  • 🎨 Template Portal: Customize prompts, manage templates, configure credit costs (/templates/repurposing)
  • 📊 Analytics Dashboard: Track ROI, usage patterns, credit savings (/analytics/repurposing)
  • Quality Control: 2-gate approval maintained for all derivatives
  • 💰 Cost Efficiency: 50-75% cheaper than creating content from scratch

Agent Docs (docs/agents/)

Design principle: one agent = one function. See agents/README.md for the master index with quick-reference tables (queue names, models, costs, plan availability). See agent-hierarchy.md for pipeline architecture, trigger types, and plan availability details.

Setup Chain — [To Build]

DocInput → Output
Client ResearcherDomain URL → client research notes
Competitor ResearcherCompetitor domains → competitor analysis
Context File WriterResearch notes → Client Context File (skill)

Strategy Chain — [To Build]

DocInput → Output
Strategy WriterContext File → marketing strategy document
Deliverable PlannerStrategy → goals + monthly deliverable volumes

Orchestration — [To Build]

DocInput → Output
Activity PlannerDeliverable plan → activity pipeline (dispatches to workers)

SEO Agents — [To Build]

DocInput → Output
Keyword ResearcherDomain/industry → keyword clusters
Content Brief WriterKeyword cluster → SEO content brief
Site AuditorDomain URL → technical SEO audit report
Backlink ResearcherNiche + existing links → prospect list
Backlink Outreach WriterSingle prospect → personalized outreach email

Content Agents — [To Build]

DocInput → Output
Blog WriterSEO brief → full blog post
GBP Post WriterBusiness info + topic → GBP post
Social Post WriterPlatform + calendar item → single social post
Email WriterCampaign brief → email newsletter copy
Landing Page WriterProduct brief → landing page copy
Google Ads WriterCampaign brief + keywords → RSA copy set
Meta Ads WriterCampaign brief + audience → Meta ad copy variants

Planning + Analysis + Reporting — [To Build]

DocInput → Output
Social Calendar PlannerStrategy + platforms → monthly content calendar
Ads AnalystAds performance data → analysis + recommendations
Report WriterAll channel data + goals → monthly performance report
Anomaly DetectorMetrics vs prior period → anomaly alerts

Research Agents (Ollama/local) — [To Build]

DocInput → Output
Topic ResearcherIndustry + recent topics → 10–15 topic ideas
Research Note WriterSingle topic → stats + citations + reference notes

Reactive Agents — [To Build]

DocInput → Output
Review Response WriterSingle review → draft response + classification

System Agents (live background automation)

AgentWhat it does
Blog AI Agent [Live]Auto-drafts blogs from Request Queue items; shows as assignee in M12/M13
Billing Agent [Live]Auto-creates invoices from billing events; shows in invoice audit trail

Superseded docs deleted. The old multi-function agent files have been removed. See agents/README.md for the replacement mapping.


Apps (docs/apps/)

Each app has its own folder with screens, navigation flows, and app-specific technical docs.

AppFolderWhat it covers
Apps — Indexdocs/apps/Master index of all apps, API surface map
Dashboarddocs/apps/dashboard/Tenant-facing web app (D1–D13 Live, P1–P16 To Build)
DM Portaldocs/apps/dm-portal/Internal reviewer interface (P1–P8)
Managedocs/apps/manage/Super admin platform control (M1–M15) + Knowledge Base management
Authdocs/apps/auth/JWT auth system (HS256), sessions, social providers [To Build], OAuth server [To Build]
Knowledge Baseapps/knowledgebaseInternal docs site (Nextra v4, port 3004, junction to docs/)
Mobiledocs/apps/mobile/React Native Dashboard — tech, screen availability, push notifications
CLI (lm)docs/apps/cli/Interactive REPL for the internal DM team — agents, approvals, queues, KB

Per-app docs quick reference

DocAppWhat it covers
Dashboard — ScreensDashboardAll screen specs (D1–D13 + P1–P16)
Dashboard — Screen FlowsDashboardNavigation flows
Dashboard — Workflow ScreensDashboardStrategy, Activity Detail, Inbox, Recurring Tasks
DM Portal — ScreensDM PortalAll screen specs (P1–P8)
DM Portal — Screen FlowsDM PortalNavigation flows
Manage — ScreensManageAll screen specs (M1–M15)
Manage — Screen FlowsManageNavigation flows
Auth — ScreensAuthLogin, Forgot PW, Reset PW, Register wizard
Auth — Screen FlowsAuthAuth & registration navigation flows
Auth — SessionsAuthJWT, refresh tokens, 2FA, biometrics
Auth — OAuth ServerAuthLeadmetrics as OAuth 2.0 / OIDC provider
Auth — Social ProvidersAuthGoogle, LinkedIn, Microsoft, Apple
Manage — Knowledge Base ScreensManageFull KB screen specs — dataset overview, file management, upload, sandbox, config (KB1–KB6)
Manage — Knowledge Base FlowsManageKB navigation flows
Dashboard — Knowledge BaseDashboardWhat tenants can do — upload/remove docs, sandbox, retrieved context
DM Portal — Knowledge BaseDM PortalWhat reviewers can do — upload/remove docs per tenant, retrieved context in activity detail
Mobile — Screen FlowsMobileReact Native navigation, push deep links, offline behaviour
CLI — CommandsCLIFull command reference — slash commands, flags, output formats
CLI — WorkflowsCLICommon team workflows — queue review, onboarding, investigations, scripting

Shared UI (docs/ui/)

Design decisions shared across all apps.

DocWhat it covers
UI LayerThree web apps + mobile, Next.js setup, auth, SSE, SendGrid integration
Design SystemColor palette, typography, spacing, component patterns, motion
Responsive DesignBreakpoints, shell layout, per-app nav items, responsive patterns for tables/charts/forms
ThemingDark/light mode — CSS variables, next-themes setup, color palette, no-flash strategy

HITL — Human-in-the-Loop (docs/hitl/)

DocWhat it covers
HITL IndexAll HITL touchpoints across 7 categories — onboarding, content, SEO, ads, reporting, mid-run decisions, safety gates
Approval FlowFull approval lifecycle — creation → notifications → review → decision → downstream effects → expiry → audit trail
UI PatternsHow approvals are displayed and actioned — DM Portal, Dashboard, Mobile, CLI — ASCII wireframes + notification preferences

Servers (docs/servers/)

Agents (docs/servers/agents/)

DocWhat it covers
OverviewService overview, worker list, scaling, required config

Notifications (docs/servers/notifications/)

DocWhat it covers
OverviewService overview, queue names, job schema, notification types reference
Design & ImplementationFile structure, startup flow, per-handler dispatch logic, templates, dev-mode filtering, config
ChannelsPer-channel handler details — Email, WhatsApp, Telegram, SMS (stub), Web (in-app)
Providers & ResolutionPer-tenant vs platform-default provider resolution, provider packages, config shapes
Provider Packagesprovider-sendgrid, provider-smtp, provider-ses, provider-whatsapp, provider-telegram — interfaces, tests, adding new providers

Billing (docs/servers/billing/)

DocWhat it covers
Overview3 BullMQ workers (invoice, overdue, credits-reset), 4 cron schedules, queue names, env vars, shutdown

Reporting (docs/servers/reporting/)

DocWhat it covers
OverviewService overview, three daily reports, scheduler, timezone handling, deduplication, trigger script

Credits (docs/credits/)

DocWhat it covers
Credits OverviewWhat credits are, plan allocations, credit rates per deliverable type, top-ups
Credit ConsumptionReservation vs consumption, retry handling, HITL rejection charges, overage policy
Credit TrackingDB schema (credit_balances, credit_ledger), API endpoints, monthly reset, reconciliation

External Providers (docs/providers/)

One doc per external service — purpose, config structure, integration pattern, test cases.

DocProviderCategory
Providers — IndexAll providersMaster index
ClaudeAnthropic Claude Code CLIAI / LLM
OpenAIOpenAI Chat CompletionsAI / LLM
OllamaLocal open-source LLMsAI / LLM
SEMrushKeyword research & competitor analysisSEO
DataForSEOSERP data, backlinks, keyword difficultySEO
AhrefsBacklinks & domain authoritySEO
Google Search ConsoleOrganic search performanceSEO / Analytics
Bing Webmaster ToolsBing/DuckDuckGo search performanceSEO
Google Analytics 4Website traffic & conversionsAnalytics
Google My BusinessGBP posts + review responsesLocal SEO
Google AdsCampaign performance + RSA pushPaid Ads
Meta AdsFacebook/Instagram campaignsPaid Ads
LinkedIn AdsB2B LinkedIn campaignsPaid Ads
FacebookOrganic Page posts + InsightsSocial Publishing
InstagramOrganic feed posts + carouselsSocial Publishing
LinkedInOrganic Company Page postsSocial Publishing
RedditCommunity posts + trend researchSocial Publishing
WordPressBlog post publishingPublishing
WebflowCMS item publishing with field mappingPublishing
MailchimpEmail campaignsEmail Marketing
KlaviyoE-commerce email flowsEmail Marketing
SendGridPlatform default email + tenant BYOPNotification
SMTPGeneric SMTP for tenant emailNotification
AWS SESTenant AWS SES emailNotification
MSG91Platform default SMS (India)Notification
TwilioInternational SMSNotification
WhatsApp Business APITemplate WhatsApp messagesNotification
Telegram BotOps/internal alertsNotification
RazorpaySubscription billing, credit top-upsPayments
AWS S3File storage (attachments, PDFs, media)Storage
QdrantVector store for RAGVector Search
RedisBullMQ backend, caching, dedupInfrastructure
PostgreSQLPrimary relational storeInfrastructure
MongoDBDocument store for agent outputs & blobsInfrastructure

Other

DocWhat it covers
IntroductionPlatform overview, key concepts, “where to go next” navigation guide
OnboardingSelf-registration, Razorpay, onboarding wizard, context file generation
Self-Signup4-step customer wizard — session management, tax logic, payment flow, abandonment emails
MCPModel Context Protocol — Playwright dev tooling, planned Leadmetrics MCP server
Open QuestionsDecisions pending, ambiguities, areas needing more design


Key Concepts (Quick Reference)

ConceptWhere Defined
Control plane + adapter patternArchitecture + Adapters
Onboarding → Context File → Strategy → Goals → Deliverables → ActivitiesWorkflow Model
Channels — OAuth-connected publishing platformsWorkflow Model + PostgreSQL Schema
Requests → Content Entities (BlogRequest → BlogPost, SocialMediaRequest → SocialPost)Workflow Model + PostgreSQL Schema
Paid Campaigns — Google Ads/Meta sync + classify + recommend + HITL pushWorkflow Model + PostgreSQL Schema
Recurring Task Templates (predefined periodic tasks)Workflow Model
Pipeline Activity Templates (per-deliverable pipelines)Workflow Model
HITL approval flowHITL Index + Approval Flow + UI Patterns
Client Context FileOnboarding Agent
Tenant isolationMulti-Tenancy
Base record fields (id, refId, tenantId, audit fields)PostgreSQL Schema
Backlink tracking + DataForSEO status checksPostgreSQL Schema + Tool Integration Layer
Audit logging + OpenTelemetry + Grafana LokiObservability
providers/ vs features/ directory conventionTech Stack
Contracts — tenant acceptance gate on first loginPostgreSQL Schema + MongoDB
Which data goes to PostgreSQL vs MongoDBDatabase Overview
All PostgreSQL table relationships (ER diagram)SQL Entity Relations
MongoDB collections and cross-referencesNoSQL Entity Relations

Deleted / Archived

The following files were removed or repurposed:

  • docs/agents.md → superseded by docs/agents/ directory
  • docs/database.md → moved to docs/database/overview.md (redirect stub left at old path)
  • docs/database-postgres.md → moved to docs/database/postgres.md (redirect stub left at old path)
  • docs/database-mongo.md → moved to docs/database/mongo.md (redirect stub left at old path)

© 2026 Leadmetrics — Internal use only