25 KiB
Chat-First Communications Manager — Phase 1 Engineering Design
Date: 2026-06-15
Author: Claude Code
Sprint plan: → 2026-06-15-phase1-mvp-sprint-plan.md
Spec: 2026-06-15-comprehensive-product-spec.md (Sections IV–VI)
Status: DRAFT — ready for Week 1 implementation
This is the implementable companion to the sprint plan. Read it alongside the week-by-week tasks. It resolves spec ambiguities, provides complete DDL with FKs/indexes/CHECK constraints, locks API contracts, and lists what to confirm before Day 1.
Contents
- Deviations from Spec
- Database Schema — Full DDL
- API Contracts
- Generation Pipeline
- NMLS Compliance Injection
- Approval / Publish Sequence
- Open Items — Confirm Before Week 1
1. Deviations from Spec
Two fields added that the spec referenced but omitted from the DDL. Two spec errors corrected.
1.1 drafts.generation_id — added
The spec puts one drafts row per platform per generation but provides no way to group them. The approval UI needs "all drafts from this generation" to render platform tabs side-by-side. The /regenerate endpoint needs it to fetch original context without re-querying the chat session.
Fix: Add generation_id CHAR(36) NOT NULL to drafts. Every call to POST /api/communications/chat generates one UUID and writes it into every platform row produced by that call. Rows from a /regenerate call keep the same generation_id.
1.2 business_profiles.email_recipients — added
Spec Section 5.5: "Send to user's configured recipient list (new field: email_recipients)." The field is named in prose but absent from the Section V.1 DDL.
Fix: Add email_recipients JSON NULL to business_profiles. Shape: ["alex@lodge.com", "lisa@lodge.com"]. Populated during onboarding via PUT /api/communications/profile. Validation: if enabled_platforms includes "email" and email_recipients is null or empty, return a 400 on profile save.
1.3 posts.draft_id — spec correction
Spec V.1 names this column platform_id UUID. That name is wrong — it references drafts.id, not a platform. Renamed to draft_id throughout this doc.
1.4 drafts.draft_metadata — added
The spec stores the entire draft as draft_text TEXT. This doesn't work for two platforms:
- Instagram: Claude returns a caption (TEXT) + hashtags (array) — two fields
- Email: Claude returns a subject (VARCHAR) + body (TEXT) — two fields
Fix: Add draft_metadata JSON NULL alongside draft_text. Convention:
- Instagram:
draft_text= caption;draft_metadata = {"hashtags": ["#mortgage", "#rateupdate"]} - Email:
draft_text= body;draft_metadata = {"subject": "Rate alert: what the Fed cut means for you"} - LinkedIn / Facebook:
draft_metadata = null;draft_text= full post
1.5 Claude model — spec correction
Spec says claude-3-5-sonnet-20241022. Current production model is claude-sonnet-4-6. Use claude-sonnet-4-6 in all implementation. (See open item #7.)
2. Database Schema — Full DDL
Migration order
Create in this order; rollback scripts drop in reverse:
business_profileschat_sessionschat_messagesdraftspostsuser_content_examplesALTER TABLE users(last — additive only)
Requirements
- MySQL 8.0.16+ for CHECK constraint enforcement (silently ignored on earlier versions — confirm before running; see open item #1)
- MySQL 8.0.13+ for
DEFAULT (UUID())expression defaults (see open item #3) - All FKs assume
users.idisCHAR(36)(see open item #2)
business_profiles
CREATE TABLE business_profiles (
id CHAR(36) NOT NULL DEFAULT (UUID()),
user_id CHAR(36) NOT NULL,
business_type VARCHAR(50) NOT NULL,
nmls_number VARCHAR(20) NULL,
states_licensed JSON NULL, -- ["CA","TX","NY"]
nmls_disclaimer_text TEXT NULL,
tone_preference VARCHAR(50) NOT NULL DEFAULT 'professional',
enabled_platforms JSON NOT NULL, -- ["linkedin","facebook","instagram","email"]
brand_voice_examples TEXT NULL,
email_recipients JSON NULL, -- ["user@domain.com"] — NEW (§1.2)
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uq_bp_user_id (user_id),
CONSTRAINT fk_bp_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
CONSTRAINT chk_bp_type CHECK (business_type IN ('mortgage_broker','publisher','real_estate','coach','consultant','other')),
CONSTRAINT chk_bp_tone CHECK (tone_preference IN ('professional','conversational','energetic','educational'))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
chat_sessions
CREATE TABLE chat_sessions (
id CHAR(36) NOT NULL DEFAULT (UUID()),
user_id CHAR(36) NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
last_message_at DATETIME NULL,
metadata JSON NULL,
PRIMARY KEY (id),
KEY idx_cs_user_last (user_id, last_message_at DESC),
CONSTRAINT fk_cs_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
chat_messages
CREATE TABLE chat_messages (
id CHAR(36) NOT NULL DEFAULT (UUID()),
session_id CHAR(36) NOT NULL,
role VARCHAR(20) NOT NULL,
content TEXT NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY idx_cm_session_time (session_id, created_at),
CONSTRAINT fk_cm_session FOREIGN KEY (session_id) REFERENCES chat_sessions(id) ON DELETE CASCADE,
CONSTRAINT chk_cm_role CHECK (role IN ('user','assistant'))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
drafts
CREATE TABLE drafts (
id CHAR(36) NOT NULL DEFAULT (UUID()),
generation_id CHAR(36) NOT NULL, -- groups all platform rows from one chat turn — NEW (§1.1)
user_id CHAR(36) NOT NULL,
session_id CHAR(36) NOT NULL,
platform VARCHAR(50) NOT NULL,
original_prompt TEXT NOT NULL,
draft_text TEXT NULL, -- NULL if this platform's generation failed
draft_metadata JSON NULL, -- {hashtags:[...]} or {subject:"..."} — NEW (§1.4)
status VARCHAR(20) NOT NULL DEFAULT 'pending',
generated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
approved_at DATETIME NULL,
error_message TEXT NULL,
regeneration_count INT NOT NULL DEFAULT 0,
PRIMARY KEY (id),
KEY idx_drafts_generation (generation_id),
KEY idx_drafts_user_status (user_id, status, generated_at DESC),
KEY idx_drafts_session (session_id),
CONSTRAINT fk_drafts_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
CONSTRAINT fk_drafts_session FOREIGN KEY (session_id) REFERENCES chat_sessions(id) ON DELETE CASCADE,
CONSTRAINT chk_drafts_platform CHECK (platform IN ('linkedin','facebook','instagram','email')),
CONSTRAINT chk_drafts_status CHECK (status IN ('pending','approved','rejected','published','failed'))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
posts
CREATE TABLE posts (
id CHAR(36) NOT NULL DEFAULT (UUID()),
user_id CHAR(36) NOT NULL,
draft_id CHAR(36) NULL, -- was platform_id in spec — renamed (§1.3)
platform VARCHAR(50) NOT NULL,
content_text TEXT NOT NULL,
platform_post_id VARCHAR(500) NULL, -- native ID returned by platform API
published_at DATETIME NULL,
scheduled_at DATETIME NULL,
autonomous TINYINT(1) NOT NULL DEFAULT 0,
error_message TEXT NULL,
PRIMARY KEY (id),
KEY idx_posts_user (user_id, published_at DESC),
KEY idx_posts_draft (draft_id),
CONSTRAINT fk_posts_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
CONSTRAINT fk_posts_draft FOREIGN KEY (draft_id) REFERENCES drafts(id) ON DELETE SET NULL,
CONSTRAINT chk_posts_platform CHECK (platform IN ('linkedin','facebook','instagram','email'))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
user_content_examples
CREATE TABLE user_content_examples (
id CHAR(36) NOT NULL DEFAULT (UUID()),
user_id CHAR(36) NOT NULL,
platform VARCHAR(50) NOT NULL,
original_prompt TEXT NULL,
approved_text TEXT NOT NULL,
metadata JSON NULL, -- {hashtags:[...], tone:"professional", length:842}
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
feedback_score INT NOT NULL DEFAULT 0,
PRIMARY KEY (id),
KEY idx_uce_user_platform (user_id, platform, created_at DESC),
CONSTRAINT fk_uce_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
CONSTRAINT chk_uce_platform CHECK (platform IN ('linkedin','facebook','instagram','email'))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
users table additions
ALTER TABLE users
ADD COLUMN autonomous_mode_enabled TINYINT(1) NOT NULL DEFAULT 0,
ADD COLUMN approved_posts_count INT NOT NULL DEFAULT 0;
3. API Contracts
3.1 Business Profile
GET /api/communications/profile
200:
{
"id": "uuid",
"user_id": "uuid",
"business_type": "mortgage_broker",
"nmls_number": "123456",
"states_licensed": ["CA", "TX"],
"nmls_disclaimer_text": "NMLS #123456, licensed in CA/TX. Not an offer to lend...",
"tone_preference": "professional",
"enabled_platforms": ["linkedin", "facebook", "instagram", "email"],
"brand_voice_examples": "...",
"email_recipients": ["alex@lodge.com"],
"created_at": "2026-06-15T00:00:00Z",
"updated_at": "2026-06-15T00:00:00Z"
}
404: { "error": "No business profile found" } — first-time user before onboarding
PUT /api/communications/profile
All fields optional on update. Required on first create: business_type, enabled_platforms.
Request:
{
"business_type": "mortgage_broker",
"nmls_number": "123456",
"states_licensed": ["CA", "TX"],
"nmls_disclaimer_text": "NMLS #123456...",
"tone_preference": "professional",
"enabled_platforms": ["linkedin", "facebook", "instagram", "email"],
"brand_voice_examples": "Here's a post I liked: ...",
"email_recipients": ["alex@lodge.com", "team@lodge.com"]
}
200: Full profile object (same shape as GET)
400 validation errors:
business_typenot in allowed enumenabled_platformscontains a value not in['linkedin','facebook','instagram','email']enabled_platformsincludes"email"butemail_recipientsis null or empty
GET /api/communications/examples
200:
{
"examples": [
{
"id": "uuid",
"platform": "linkedin",
"original_prompt": "Rate update",
"approved_text": "Big news for buyers...",
"metadata": null,
"created_at": "2026-06-14T10:00:00Z",
"feedback_score": 0
}
]
}
No filtering in Week 1 — return all examples for the authenticated user, newest first.
POST /api/communications/profile/generate-onboarding
Request: empty body (fetches profile from auth context)
200:
{
"chips": [
"Rate update",
"New listing",
"Market commentary",
"Client testimonial request",
"Refinance education"
],
"vertical": "mortgage_broker"
}
Hardcode chip lists per vertical in Week 1. No Claude call needed here — chips are static per business_type.
3.2 Chat
POST /api/communications/chat
Request:
{
"session_id": "uuid-or-null",
"user_prompt": "Write me a rate update post about the Fed dropping rates",
"enabled_platforms": ["linkedin", "facebook", "instagram", "email"]
}
session_id: null→ create new session, return newsession_idin responseenabled_platformsdefaults tobusiness_profiles.enabled_platformsif omitted
200:
{
"session_id": "uuid",
"generation_id": "uuid",
"drafts": [
{
"draft_id": "uuid",
"platform": "linkedin",
"draft_text": "Big news for homebuyers...",
"draft_metadata": null,
"status": "pending",
"error": null
},
{
"draft_id": "uuid",
"platform": "instagram",
"draft_text": "Rates just dropped!",
"draft_metadata": { "hashtags": ["#mortgagerates", "#homebuying", "#NMLS123456"] },
"status": "pending",
"error": null
},
{
"draft_id": "uuid",
"platform": "email",
"draft_text": "The Fed just cut rates. Here's what that means for you...",
"draft_metadata": { "subject": "Rate alert: what this week's Fed decision means for you" },
"status": "pending",
"error": null
},
{
"draft_id": null,
"platform": "facebook",
"draft_text": null,
"draft_metadata": null,
"status": "failed",
"error": "Claude API timeout"
}
]
}
A failed platform returns draft_id: null, no row in drafts. The client renders an error state for that tab; user clicks "Regenerate this platform" to retry via /regenerate.
3.3 Draft Management
GET /api/communications/drafts/:draft_id
200:
{
"draft_id": "uuid",
"generation_id": "uuid",
"platform": "linkedin",
"original_prompt": "Write me a rate update...",
"draft_text": "Big news for homebuyers...",
"draft_metadata": null,
"status": "pending",
"generated_at": "2026-06-15T19:00:00Z",
"approved_at": null,
"error_message": null,
"regeneration_count": 0
}
POST /api/communications/drafts/:draft_id/regenerate
Request (optional):
{ "feedback": "Make it shorter and punchier" }
200: Same shape as GET /drafts/:draft_id with updated draft_text, incremented regeneration_count, status: "pending".
Updates the existing drafts row in place — does not create a new row. generation_id is preserved.
POST /api/communications/drafts/:draft_id/reject
Request: empty body
200: { "draft_id": "uuid", "status": "rejected" }
Side effect: UPDATE drafts SET status = 'rejected'.
3.4 Approval & Publish
POST /api/communications/drafts/:draft_id/approve
Request: empty body
200 — success:
{
"draft_id": "uuid",
"platform": "linkedin",
"post_id": "uuid",
"platform_post_id": "urn:li:share:7309876543210",
"published_at": "2026-06-15T19:05:00Z",
"status": "published",
"error": null
}
200 — platform API failure (not 4xx — the HTTP request succeeded; the platform call failed):
{
"draft_id": "uuid",
"platform": "instagram",
"post_id": null,
"platform_post_id": null,
"published_at": null,
"status": "failed",
"error": "Instagram: token expired — reconnect credentials"
}
Return 200 even on platform failure. The client handles per-platform error copy without treating the whole request as an HTTP error.
4. Generation Pipeline
Architecture decision: per-platform parallel Claude calls
The spec (§4.5) implies a single Claude call returning a multi-platform JSON blob. The sprint plan (2.1) requires partial-failure isolation per platform. These conflict: if you send one multi-platform JSON call and the instagram key is malformed, you can recover the other keys via partial parsing — but you can't independently retry just Instagram without regenerating everything, and regeneration_count becomes ambiguous (did you regenerate the full batch or just one platform?).
Decision: one Claude call per platform, all launched via Promise.allSettled().
Cost tradeoff: ~1.7× more tokens than a single multi-platform call because the system prompt is repeated per call. Acceptable for a pilot with <10 users; revisit at scale. Benefit: true per-platform isolation, clean regeneration_count per drafts row, natural fit for the schema.
POST /api/communications/chat
│
├─ Resolve session (create new if session_id is null)
├─ Fetch business_profile for req.user.id
├─ Fetch last 3 user_content_examples per enabled platform
│ SELECT approved_text FROM user_content_examples
│ WHERE user_id = ? AND platform = ?
│ ORDER BY created_at DESC LIMIT 3
│
├─ generation_id = uuid()
│
├─ Promise.allSettled([
│ generateForPlatform('linkedin', prompt, profile, examples),
│ generateForPlatform('facebook', prompt, profile, examples),
│ generateForPlatform('instagram', prompt, profile, examples),
│ generateForPlatform('email', prompt, profile, examples),
│ ]) → settledResults[]
│
├─ For each settled result:
│ fulfilled → INSERT INTO drafts (generation_id, platform, draft_text, ...)
│ rejected → no row inserted; add error entry to response
│
├─ INSERT INTO chat_messages (role='user', content=user_prompt)
├─ INSERT INTO chat_messages (role='assistant', content='Generated N platform drafts')
├─ UPDATE chat_sessions SET last_message_at = NOW()
│
└─ Return { session_id, generation_id, drafts: [...] }
generateForPlatform
async function generateForPlatform(
platform: 'linkedin' | 'facebook' | 'instagram' | 'email',
userPrompt: string,
profile: BusinessProfile,
examples: string[] // last 3 approved_text values for this platform
): Promise<{ draft_text: string; draft_metadata: object | null }> {
const system = buildSystemPrompt(platform, profile, examples);
const response = await anthropic.messages.create({
model: 'claude-sonnet-4-6',
max_tokens: 512, // per-platform; 512 is plenty for any single platform
system,
messages: [{ role: 'user', content: userPrompt }]
});
const raw = response.content[0].type === 'text' ? response.content[0].text : '';
const { draft_text, draft_metadata } = parsePlatformResponse(platform, raw);
return {
draft_text: injectNmlsCompliance(draft_text, profile), // see §5
draft_metadata
};
}
System prompt structure
You are an AI communications operator for [business_type] professionals.
Platform: [PLATFORM]
Character limit: [LIMIT]
[VERTICAL_CONSTRAINTS]
Previously approved posts by this user on [PLATFORM]:
---
[examples[0]]
---
[examples[1]]
---
[examples[2]]
---
Generate ONLY the [PLATFORM] content. [PLATFORM-SPECIFIC OUTPUT INSTRUCTION]
Platform-specific output instructions:
| Platform | max_tokens | Output instruction |
|---|---|---|
linkedin |
512 | "Output the post text only. 800–1300 characters." |
facebook |
256 | "Output the post text only. 150–400 characters." |
instagram |
256 | "Line 1: caption (138–150 chars). Line 2: space-separated #hashtags (5–10 tags)." |
email |
512 | "Line 1: Subject: [subject line]. Blank line. Then email body (200–400 words)." |
parsePlatformResponse
function parsePlatformResponse(
platform: string,
raw: string
): { draft_text: string; draft_metadata: object | null } {
switch (platform) {
case 'instagram': {
const [caption = '', hashtagLine = ''] = raw.trim().split('\n');
const hashtags = hashtagLine.match(/#\w+/g) ?? [];
return { draft_text: caption, draft_metadata: { hashtags } };
}
case 'email': {
const match = raw.match(/^Subject:\s*(.+)\n\n?([\s\S]+)/);
return match
? { draft_text: match[2].trim(), draft_metadata: { subject: match[1].trim() } }
: { draft_text: raw.trim(), draft_metadata: { subject: '' } };
}
default:
return { draft_text: raw.trim(), draft_metadata: null };
}
}
5. NMLS Compliance Injection
Post-process every mortgage_broker draft after parsePlatformResponse, before inserting into drafts. This is a hard server-side append, not a prompt instruction — prompts can miss it; keyword detection cannot.
const NMLS_TRIGGER = /\b(rates?|loans?|APR|refinanc|financial advice|borrow|lend)\b/i;
function injectNmlsCompliance(draftText: string, profile: BusinessProfile): string {
if (profile.business_type !== 'mortgage_broker') return draftText;
if (!NMLS_TRIGGER.test(draftText)) return draftText;
const disclaimer =
profile.nmls_disclaimer_text ??
`NMLS #${profile.nmls_number}. Not an offer to enter into an agreement. ` +
`Not all customers will qualify. Information subject to TILA.`;
return `${draftText}\n\n${disclaimer}`;
}
Sprint plan 2.2 acceptance criterion: "100% of generated mortgage-broker drafts mentioning rates/loans/APR include the disclaimer." This gate is enforceable only with server-side injection — verify via log inspection before marking 2.2 done.
Open question (see §7 item #6): Should user_content_examples.approved_text store the post WITH or WITHOUT the disclaimer? Recommendation: strip the disclaimer before inserting into user_content_examples so that style learning operates on the human-readable voice, not the legal boilerplate.
6. Approval / Publish Sequence
POST /api/communications/drafts/:draft_id/approve
│
├─ Fetch draft WHERE id = :draft_id AND user_id = req.user.id
│ → 404 if not found or wrong user
│ → 409 if status != 'pending' (already approved / rejected / published)
│
├─ Fetch OAuth token from Redis
│ key pattern: oauth:credentials:{user_id}:{platform}
│ (same helper as existing src/tools.ts credential lookup — do not duplicate)
│
├─ Call platform API
│ ├─ linkedin → POST /v2/ugcPosts (reuse src/tools.ts)
│ ├─ facebook → POST /{page_id}/feed (reuse src/tools.ts)
│ ├─ instagram → POST media → POST caption (reuse src/tools.ts)
│ └─ email → smtp.ts sendMail()
│ to: business_profiles.email_recipients ← the §1.2 new field
│
├─ On platform API SUCCESS:
│ ├─ INSERT INTO posts (user_id, draft_id, platform, content_text, platform_post_id, published_at)
│ ├─ UPDATE drafts SET status='published', approved_at=NOW()
│ ├─ INSERT INTO user_content_examples
│ │ (user_id, platform, original_prompt, approved_text=<draft_text without disclaimer>, metadata)
│ └─ UPDATE users SET approved_posts_count = approved_posts_count + 1
│ (autonomous mode toggle appears in UI once this hits 10)
│
├─ On platform API FAILURE:
│ ├─ UPDATE drafts SET status='failed', error_message=<platform error>
│ └─ Return 200 with status:'failed' + error string
│ (do not throw HTTP 5xx — request succeeded; platform call failed)
│
└─ Return result object (see §3.4)
Platform API notes
| Platform | Endpoint | Token key in Redis | Notes |
|---|---|---|---|
POST /v2/ugcPosts |
oauth:credentials:{uid}:linkedin |
Existing connector in src/tools.ts |
|
POST /{page_id}/feed |
oauth:credentials:{uid}:facebook |
Existing connector; page_id from profile or token |
|
POST /{ig_user_id}/media + /caption |
oauth:credentials:{uid}:instagram |
Requires image URL from user; set draft_metadata.image_required=true if none provided |
|
smtp.ts.sendMail() |
SMTP creds in Redis (existing key format — confirm in §7 #5) | to: = business_profiles.email_recipients |
7. Open Items — Confirm Before Week 1
| # | Item | Impact if wrong | Action |
|---|---|---|---|
| 1 | MySQL version | CHECK constraints silently not enforced on <8.0.16 | SELECT VERSION() on staging |
| 2 | users.id column type |
FK CHAR(36) declarations break if users.id is INT |
SHOW COLUMNS FROM users LIKE 'id' |
| 3 | DEFAULT (UUID()) support |
Fails on MySQL <8.0.13; need app-level UUID gen | Follows from version check |
| 4 | Redis key format for OAuth tokens | Approval flow fetches wrong/empty token | Read src/tools.ts credential lookup — confirm key pattern |
| 5 | smtp.ts send signature |
Week 2.4 email approval breaks if to: param shape differs |
Read smtp.ts; note exact param name for recipient list |
| 6 | NMLS style examples | Store post WITH or WITHOUT disclaimer in user_content_examples? |
Decide before Week 2; recommend WITHOUT — see §5 |
| 7 | Claude model string | claude-sonnet-4-6 vs. spec's claude-3-5-sonnet-20241022 |
Confirm API key has access to claude-sonnet-4-6 |
| 8 | Instagram image URL | status='pending' rows with no image block the Approve button |
Add {image_required: true} to draft_metadata when no URL provided; UI renders "Add image URL" callout before enabling Approve |
Changelog
| Date | Author | Change |
|---|---|---|
| 2026-06-15 | Claude Code | Initial draft — DDL with FKs/indexes/CHECK constraints, API contracts, generation pipeline, compliance injection, approval sequence |