Files
wp-agentic-writer/docs/architecture/CORE_CHAT_WORKFLOW_SPEC.md

96 KiB

WP Agentic Writer - Core Editor Chat Workflow Specification

Version: 1.0 Date: 2026-05-17 Status: 🔴 FOUNDATIONAL - REQUIRES COMPLETE REBUILD


Executive Summary

This document defines the complete Core Editor Chat Workflow - the primary user interaction system for WP Agentic Writer. It covers everything from initial load to final article completion, ensuring seamless UX with zero friction.

Design Philosophy:

"The AI should feel like a skilled writing assistant who remembers everything, anticipates needs, and never loses context - regardless of document state or mode."


Architecture Overview

┌─────────────────────────────────────────────────────────────────────┐
│                    CORE EDITOR CHAT WORKFLOW                         │
├─────────────────────────────────────────────────────────────────────┤
│                                                                      │
│  ┌──────────────┐     ┌──────────────┐     ┌──────────────┐         │
│  │ INITIAL      │────▶│ CONTEXT     │────▶│ MODE        │         │
│  │ LOAD        │     │ RESTORE     │     │ DETECTION   │         │
│  └──────────────┘     └──────────────┘     └──────────────┘         │
│         │                                        │                   │
│         ▼                                        ▼                   │
│  ┌──────────────┐     ┌──────────────┐     ┌──────────────┐         │
│  │ NEW DOC      │     │ EDIT DOC    │     │ CHAT        │         │
│  │ FLOW         │     │ FLOW        │     │ CONVERSATION│         │
│  └──────────────┘     └──────────────┘     └──────────────┘         │
│                                                   │                   │
│         ┌─────────────────────────────────────────┘                   │
│         │                                                           │
│         ▼                                                           │
│  ┌──────────────────────────────────────────────────────────────┐   │
│  │                     WRITING PIPELINE                          │   │
│  │  ┌────────┐  ┌────────┐  ┌────────┐  ┌────────┐  ┌────────┐  │   │
│  │  │OUTLINE │─▶│REFINE  │─▶│APPROVE │─▶│WRITE   │─▶│REFINE  │  │   │
│  │  │CREATE  │  │OUTLINE │  │OUTLINE │  │SECTIONS│  │ARTICLE │  │   │
│  │  └────────┘  └────────┘  └────────┘  └────────┘  └────────┘  │   │
│  └──────────────────────────────────────────────────────────────┘   │
│                           │                                          │
│                           ▼                                          │
│  ┌──────────────────────────────────────────────────────────────┐   │
│  │                     SEO & GEO HANDLERS                       │   │
│  │  ┌────────┐  ┌────────┐  ┌────────┐  ┌────────┐  ┌────────┐  │   │
│  │  │META    │  │FOCUS   │  │FAQ     │  │SCHEMA  │  │CONTENT │  │   │
│  │  │TITLE   │  │KEYWORD │  │GENERATE│  │MARKUP  │  │SCORE   │  │   │
│  │  └────────┘  └────────┘  └────────┘  └────────┘  └────────┘  │   │
│  └──────────────────────────────────────────────────────────────┘   │
│                                                                      │
└─────────────────────────────────────────────────────────────────────┘

Document States & Initial Load

Document State Machine

                    ┌─────────────────┐
                    │    NEW DOC      │
                    │   (Empty post)  │
                    └────────┬────────┘
                             │
                             ▼
                    ┌─────────────────┐
                    │   ONBOARDING    │  ← Clarification Quiz
                    │   FLOW          │
                    └────────┬────────┘
                             │
              ┌──────────────┼──────────────┐
              ▼              ▼              ▼
     ┌──────────────┐ ┌──────────────┐ ┌──────────────┐
     │   EXISTING   │ │    HAS      │  │    NO       │
     │   CONTENT    │ │    PLAN     │  │    PLAN     │
     │   ONLY       │ │   (Draft)   │  │   (Fresh)   │
     └──────────────┘ └──────────────┘ └──────────────┘
              │              │              │
              └──────────────┴──────────────┘
                             │
                             ▼
                    ┌─────────────────┐
                    │   CHAT MODE     │
                    │   (Default)     │
                    └─────────────────┘

Load Decision Matrix

Scenario Detection Action
New post (no content, no plan) !postId || !content && !plan Show onboarding + chat
New post (from quick draft) !content && plan Load plan, ask to write
Edit existing (has content) content && !plan Show content, enable refinement
Edit existing (has plan) content && plan Full restore with context
Re-open during writing in_progress flag Resume from last section
Re-open after completion status: complete Show finished article

Initial Load Flow

New Document (Fresh Start)

┌──────────────────────────────────────────────────────────────────┐
│ STEP 1: Detect State                                              │
│ ──────────────────────────────────────────────────────────────── │
│ post_id = get_current_post_id()                                   │
│ existing_content = get_post_content(post_id)                      │
│ existing_plan = get_post_meta('_wpaw_plan')                      │
│                                                                   │
│ IF post_id == null OR (empty content AND empty plan):            │
│     → NEW_DOC_FLOW                                                │
│ ELSE IF has_plan:                                                 │
│     → RESUME_FROM_PLAN                                            │
│ ELSE:                                                             │
│     → EXISTING_CONTENT_FLOW                                       │
└──────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌──────────────────────────────────────────────────────────────────┐
│ STEP 2: New Document Onboarding                                    │
│ ──────────────────────────────────────────────────────────────── │
│                                                                   │
│ MODE: chat                                                        │
│ STATE: onboarding                                                 │
│                                                                   │
│ Show: "What would you like to write about today?"                 │
│                                                                   │
│ OPTIONS:                                                          │
│   1. Start chatting (free-form)                                   │
│   2. Enter focus keyword (SEO mode)                               │
│   3. Use Clarification Quiz (guided)                              │
│                                                                   │
│ USER CHOICE 1 → Start Chat Mode                                    │
│ USER CHOICE 2 → Show Keyword Input → SEO Chat Mode                 │
│ USER CHOICE 3 → Run Clarification Quiz → Generate Topic + Plan    │
│                                                                   │
└──────────────────────────────────────────────────────────────────┘

Existing Document (Edit Mode)

┌──────────────────────────────────────────────────────────────────┐
│ STEP 1: Load Context                                              │
│ ──────────────────────────────────────────────────────────────── │
│                                                                   │
│ post_id = get_current_post_id()                                   │
│ content = get_post_content(post_id)                               │
│ plan = get_post_meta('_wpaw_plan', post_id)                       │
│ messages = get_post_meta('_wpaw_messages', post_id)                │
│ focus_keyword = get_post_meta('_wpaw_focus_keyword', post_id)      │
│ status = get_post_meta('_wpaw_status', post_id)                   │
│                                                                   │
└──────────────────────────────────────────────────────────────────┘
                              │
              ┌───────────────┼───────────────┐
              ▼               ▼               ▼
      ┌───────────────┐ ┌───────────────┐ ┌───────────────┐
      │   HAS PLAN    │ │ HAS CONTENT   │ │   INCOMPLETE  │
      │   & CONTENT   │ │   ONLY        │ │    STATUS     │
      └───────────────┘ └───────────────┘ └───────────────┘
              │               │               │
              ▼               ▼               ▼
      ┌───────────────┐ ┌───────────────┐ ┌───────────────┐
      │ FULL RESTORE  │ │  REFINE MODE  │ │    RESUME     │
      │ Show plan     │ │ Show content  │ │  Show prompt  │
      │ + content     │ │ Enable @ref   │ │  Continue     │
      │ + chat history │ │ Enable blocks │ │  writing      │
      └───────────────┘ └───────────────┘ └───────────────┘

Mode System

Mode Definitions

Mode Purpose Available Actions Transitions To
chat Free-form conversation Chat, Create Outline, Switch Mode planning, writing
planning Outline creation & refinement Create Outline, Refine Outline, Approve, Generate from Outline chat, writing
writing Article generation Write Section, Pause, Resume, Abort refinement, chat
refinement Content improvement Refine Block, Refine All, SEO, Abort chat, writing
seo SEO optimization Meta Title, Meta Desc, FAQ, Schema refinement, chat

Mode Transition Rules

┌─────────────────────────────────────────────────────────────────┐
│                     MODE TRANSITION MAP                         │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│    ┌─────────┐                                                   │
│    │  CHAT   │◀──────────┐                                     │
│    └────┬────┘            │                                     │
│         │                 │                                     │
│    ┌────┴────┐       ┌────┴────┐                                │
│    │         │       │         │                                │
│    ▼         │       ▼         │                                │
│ ┌─────────┐  │   ┌─────────┐  │                                │
│ │PLANNING │──┴──▶│WRITING │──┴────────┐                        │
│ └────┬────┘      └────┬────┘           │                        │
│      │                │                │                        │
│      │          ┌─────┴────┐            │                        │
│      │          │          │            │                        │
│      ▼          ▼          │            ▼                        │
│  ┌─────────┐ ┌─────────┐   │      ┌─────────┐                   │
│  │OUTLINE  │ │SECTION  │   │      │REFINE  │                   │
│  │REFINE   │ │WRITE    │   │      │ARTICLE │                   │
│  └─────────┘ └─────────┘   │      └────┬────┘                   │
│                             │           │                        │
│                             └───────────┤                        │
│                                         │                        │
│                                         ▼                        │
│                                   ┌─────────┐                    │
│                                   │   SEO   │                    │
│                                   └─────────┘                    │
│                                                                  │
│ TRANSITION TRIGGERS:                                            │
│ ──────────────────────────────────────────────────────────────── │
│ chat → planning: User says "create outline" / "write article"   │
│ planning → writing: User approves outline                        │
│ writing → refinement: Article completed or user pauses          │
│ refinement → seo: User triggers SEO mode                        │
│ any → chat: User wants to chat freely                            │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

Mode State Persistence

// State stored in post_meta for persistence across page loads
const state = {
  mode: 'chat',                    // Current mode
  modeHistory: ['chat'],          // Mode history stack
  timestamp: Date.now(),           // Last state change
  context: {
    messages: [],                  // Chat messages
    plan: null,                    // Current outline
    content: '',                   // Generated content
    focusKeyword: null,            // Focus keyword
    seoData: {}                    // SEO metadata
  },
  flags: {
    isOnboarding: false,           // First-time flow
    hasPlanApproved: false,        // Outline approved
    isWritingInProgress: false,    // Currently writing
    lastSectionCompleted: null,    // Resume point
  }
};

Chat Conversation System

Message Types

const messageTypes = {
  user: {
    type: 'user',
    role: 'user',
    display: 'You',
    icon: '👤',
    class: 'message-user'
  },
  assistant: {
    type: 'assistant',
    role: 'assistant',
    display: 'AI',
    icon: '🤖',
    class: 'message-assistant'
  },
  system: {
    type: 'system',
    role: 'system',
    display: 'System',
    icon: '⚙️',
    class: 'message-system'
  },
  timeline: {
    type: 'timeline',
    role: 'system',
    display: 'Progress',
    icon: '📊',
    class: 'message-timeline'
  },
  plan: {
    type: 'plan',
    role: 'system',
    display: 'Outline',
    icon: '📋',
    class: 'message-plan'
  },
  content: {
    type: 'content',
    role: 'system',
    display: 'Article',
    icon: '📄',
    class: 'message-content'
  },
  seo: {
    type: 'seo',
    role: 'system',
    display: 'SEO',
    icon: '🎯',
    class: 'message-seo'
  }
};

Context Management

Context Building Pipeline

┌─────────────────────────────────────────────────────────────────┐
│                    CONTEXT BUILDING PIPELINE                     │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  INPUTS                           PROCESS           OUTPUT      │
│  ───────────────────────────────────────────────────────────────── │
│                                                                  │
│  ┌─────────────┐    ┌─────────────────┐    ┌─────────────┐     │
│  │ Chat History │───▶│ Intent Detection │───▶│ Optimize    │     │
│  │ (messages)   │    │ (per message)    │    │ Context     │     │
│  └─────────────┘    └─────────────────┘    └─────────────┘     │
│         │                    │                  │              │
│         │                    ▼                  │              │
│         │           ┌─────────────────┐         │              │
│         │           │ Suggest Actions │         │              │
│         │           │ Based on Intent  │         │              │
│         │           └─────────────────┘         │              │
│         │                                        │              │
│         ▼                                        ▼              │
│  ┌─────────────┐                    ┌─────────────────────┐   │
│  │ Plan Data    │───────────────────▶│ Combined Prompt     │   │
│  │ (if exists)  │                    │ for AI Backend      │   │
│  └─────────────┘                    └─────────────────────┘   │
│         │                                        │              │
│         ▼                                        ▼              │
│  ┌─────────────┐                    ┌─────────────────────┐   │
│  │ Focus       │───────────────────▶│ System Prompt       │   │
│  │ Keyword     │                    │ with Context       │   │
│  └─────────────┘                    └─────────────────────┘   │
│         │                                        │              │
│         ▼                                        ▼              │
│  ┌─────────────┐                    ┌─────────────────────┐   │
│  │ Post Config │───────────────────▶│ API Request Payload │   │
│  │ (SEO, etc)  │                    └─────────────────────┘   │
│  └─────────────┘                                                 │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

Context Optimization Strategy

Chat Length Strategy Trigger Tokens Saved
1-6 messages Full history Default 0%
7-15 messages Summary + last 4 Auto ~50%
16-30 messages Summary + last 2 Auto ~70%
30+ messages Aggressive summary Auto ~85%

Context Optimizer Logic:

async function buildOptimizedContext(messages, postConfig) {
  // If short conversation, use as-is
  if (messages.length <= 6) {
    return messages;
  }

  // Check if summarization needed
  const estimatedTokens = estimateTokens(messages);
  const tokenLimit = 4000; // Safety limit

  if (estimatedTokens > tokenLimit) {
    // Summarize old messages
    const { summary, remaining } = await summarizeContext(messages);

    return [
      { role: 'system', content: `CONTEXT SUMMARY:\n${summary}` },
      ...remaining.slice(-4) // Keep last 4 for recency
    ];
  }

  return messages;
}

Intent Detection System

Intent Types

Intent Trigger Phrases Action
create_outline "create outline", "outline", "plan", "structure" Show outline preview
write_article "write", "start writing", "generate", "create article" Begin writing pipeline
refine_content "improve", "rewrite", "enhance", "polish" Show refinement options
add_section "add section", "more", "continue" Add to plan
clarify "what", "how", "explain", "?" Provide clarification
continue_chat anything else Continue conversation

Intent Detection Flow

┌──────────────────────────────────────────────────────────────────┐
│                  INTENT DETECTION PIPELINE                       │
├──────────────────────────────────────────────────────────────────┤
│                                                                   │
│   User Message                                                    │
│        │                                                          │
│        ▼                                                          │
│   ┌─────────────────────────┐                                     │
│   │ 1. Keyword Matching      │ ← Fast path, language-agnostic    │
│   │    (configurable)        │   Fallback if AI fails             │
│   └────────────┬────────────┘                                     │
│                │                                                   │
│                │ No match                                          │
│                ▼                                                  │
│   ┌─────────────────────────┐                                     │
│   │ 2. AI Intent Detection   │ ← $0.00002 per detection          │
│   │    /detect-intent        │   Cached for 5 minutes             │
│   └────────────┬────────────┘                                     │
│                │                                                   │
│         ┌──────┴──────┐                                           │
│         │             │                                           │
│    Success        Failure                                         │
│         │             │                                           │
│         ▼             ▼                                           │
│   ┌──────────┐   ┌──────────┐                                     │
│   │ Return   │   │ Default  │                                     │
│   │ Intent   │   │ to       │                                     │
│   │          │   │ continue  │                                     │
│   └──────────┘   │ _chat     │                                     │
│                  └──────────┘                                     │
│                                                                   │
│   POST-DETECTION:                                                 │
│   ┌───────────────────────────────────────────────────────────┐  │
│   │ Show contextual action button based on intent             │  │
│   │                                                             │  │
│   │ create_outline → [📝 Create Outline]                       │  │
│   │ write_article  → [✍️ Start Writing] (if plan exists)      │  │
│   │                  → [📝 Create Outline First] (if no plan)  │  │
│   │ refine_content → [🎯 Refine Article]                       │  │
│   └───────────────────────────────────────────────────────────┘  │
│                                                                   │
└──────────────────────────────────────────────────────────────────┘

Outline System

Outline Data Structure

const outlineStructure = {
  metadata: {
    id: 'outline_20260517_001',
    title: 'Article Title',
    focus_keyword: 'focus keyword',
    created_at: '2026-05-17T10:00:00Z',
    updated_at: '2026-05-17T10:30:00Z',
    version: 3,  // Track revisions
    status: 'draft' | 'approved' | 'in_progress' | 'completed'
  },
  sections: [
    {
      id: 'sec_1',
      index: 0,
      heading: 'Section Heading',
      type: 'h2',  // h2, h3, etc.
      description: 'Brief description of section content',
      key_points: [
        'Point 1',
        'Point 2',
        'Point 3'
      ],
      target_word_count: 300,
      actual_word_count: 0,
      status: 'pending' | 'in_progress' | 'completed' | 'refined',
      content: '',  // Filled after writing
      refinement_notes: ''  // User's refinement requests
    }
  ],
  seo_notes: {
    primary_keyword: 'keyword',
    secondary_keywords: ['kw2', 'kw3'],
    target_length: 2000,
    internal_links: [],
    external_links: []
  }
};

Outline Creation Flow

┌──────────────────────────────────────────────────────────────────┐
│                    OUTLINE CREATION PIPELINE                      │
├──────────────────────────────────────────────────────────────────┤
│                                                                   │
│   USER INPUT: Topic + Optional Keywords                          │
│        │                                                         │
│        ▼                                                         │
│   ┌────────────────────────────────────────────────────────────┐ │
│   │ STEP 1: Context Collection                                 │ │
│   │ ──────────────────────────────────────────────────────────  │ │
│   │ • Fetch related posts (@mentions)                          │ │
│   │ • Include focus keyword context                            │ │
│   │ • Build SEO requirements                                   │ │
│   │ • Pull user preferences from settings                      │ │
│   └────────────────────────────────────────────────────────────┘ │
│        │                                                         │
│        ▼                                                         │
│   ┌────────────────────────────────────────────────────────────┐ │
│   │ STEP 2: AI Outline Generation                             │ │
│   │ ──────────────────────────────────────────────────────────  │ │
│   │ Model: planning_model                                      │ │
│   │ Prompt: Generate structured outline with:                  │ │
│   │   - Main sections (H2) with descriptions                    │ │
│   │   - Key points for each section                            │ │
│   │   - Estimated word counts                                  │ │
│   │   - SEO recommendations                                     │ │
│   └────────────────────────────────────────────────────────────┘ │
│        │                                                         │
│        ▼                                                         │
│   ┌────────────────────────────────────────────────────────────┐ │
│   │ STEP 3: Parse & Format                                     │ │
│   │ ──────────────────────────────────────────────────────────  │ │
│   │ • Parse JSON from response                                 │ │
│   │ • Validate structure                                       │ │
│   │ • Apply formatting standards                               │ │
│   │ • Add section IDs and metadata                             │ │
│   └────────────────────────────────────────────────────────────┘ │
│        │                                                         │
│        ▼                                                         │
│   ┌────────────────────────────────────────────────────────────┐ │
│   │ STEP 4: Display & Wait for Approval                       │ │
│   │ ──────────────────────────────────────────────────────────  │ │
│   │ • Render outline as interactive cards                      │ │
│   │ • Enable drag-to-reorder                                   │ │
│   │ • Enable inline editing                                    │ │
│   │ • Show "Start Writing" button (disabled until approved)   │ │
│   └────────────────────────────────────────────────────────────┘ │
│        │                                                         │
│        ▼                                                         │
│   USER APPROVES → Save to post_meta → Enable Writing             │
│                                                                   │
└──────────────────────────────────────────────────────────────────┘

Outline Refinement Flow

┌──────────────────────────────────────────────────────────────────┐
│                   OUTLINE REFINEMENT PIPELINE                    │
├──────────────────────────────────────────────────────────────────┤
│                                                                   │
│   APPROVED OUTLINE ─────────────────────────────────────────────│
│        │                                                          │
│        ▼                                                          │
│   ┌──────────────────────────────────────────────────────────┐  │
│   │ USER REQUESTS CHANGES:                                    │  │
│   │ • "Make section 2 longer"                                 │  │
│   │ • "Add a section about X"                                  │  │
│   │ • "Reorder to put Y first"                                 │  │
│   │ • "Combine sections 1 and 2"                              │  │
│   └──────────────────────────────────────────────────────────┘  │
│        │                                                          │
│        ▼                                                          │
│   ┌──────────────────────────────────────────────────────────┐  │
│   │ AI PROCESSES REQUEST                                     │  │
│   │ ──────────────────────────────────────────────────────────  │  │
│   │ • Understand change intent                                 │  │
│   │ • Apply to outline structure                               │  │
│   │ • Maintain internal consistency                           │  │
│   │ • Return updated outline                                   │  │
│   └──────────────────────────────────────────────────────────┘  │
│        │                                                          │
│        ▼                                                          │
│   ┌──────────────────────────────────────────────────────────┐  │
│   │ DISPLAY REFINED OUTLINE                                   │  │
│   │ ──────────────────────────────────────────────────────────  │  │
│   │ • Highlight changes (new/modified/deleted)               │  │
│   │ • Show "Accept Changes" / "Undo"                           │  │
│   │ • Update version number                                    │  │
│   └──────────────────────────────────────────────────────────┘  │
│        │                                                          │
│        ▼                                                          │
│   USER APPROVES → Continue                                        │
│                                                                   │
└──────────────────────────────────────────────────────────────────┘

Writing Pipeline

Section Writing Flow

┌──────────────────────────────────────────────────────────────────┐
│                    SECTION WRITING PIPELINE                        │
├──────────────────────────────────────────────────────────────────┤
│                                                                   │
│   APPROVED OUTLINE + USER CLICKS "Start Writing"                 │
│        │                                                          │
│        ▼                                                          │
│   ┌────────────────────────────────────────────────────────────┐ │
│   │ STEP 1: Initialize Writing State                            │ │
│   │ ──────────────────────────────────────────────────────────  │ │
│   │ • Set status: 'writing'                                    │ │
│   │ • Set current_section: 0                                   │ │
│   │ • Initialize section_results: []                           │ │
│   │ • Calculate total estimated tokens                         │ │
│   └────────────────────────────────────────────────────────────┘ │
│        │                                                          │
│        ▼                                                          │
│   ┌────────────────────────────────────────────────────────────┐ │
│   │ LOOP: For each section in outline                          │ │
│   │ ──────────────────────────────────────────────────────────  │ │
│   │                                                            │ │
│   │   SECTION i: "{heading}"                                   │ │
│   │   ┌─────────────────────────────────────────────────────┐  │ │
│   │   │ (a) Write Section Content                          │  │ │
│   │   │ ──────────────────────────────────────────────────── │  │ │
│   │   │ Model: writing_model                                │  │ │
│   │   │ Context: full_plan + previous_sections + this_heading │ │
│   │   │ Output: Markdown content for this section           │  │ │
│   │   └─────────────────────────────────────────────────────┘  │ │
│   │        │                                                  │ │
│   │        ▼                                                  │ │
│   │   ┌─────────────────────────────────────────────────────┐  │ │
│   │   │ (b) Insert into WordPress                          │  │ │
│   │   │ ──────────────────────────────────────────────────── │  │ │
│   │   │ • Parse Markdown to blocks                          │  │ │
│   │   │ • Insert after existing content                     │  │ │
│   │   │ • Mark section as 'completed' in plan               │  │ │
│   │   │ • Update post_meta                                  │  │ │
│   │   └─────────────────────────────────────────────────────┘  │ │
│   │        │                                                  │ │
│   │        ▼                                                  │ │
│   │   IF user clicks "Pause":                                  │ │
│   │   ┌─────────────────────────────────────────────────────┐  │ │
│   │   │ • Save current state to post_meta                   │  │ │
│   │   │ • Set status: 'paused'                              │  │ │
│   │   │ • Show "Resume Writing" button                      │  │ │
│   │   └─────────────────────────────────────────────────────┘  │ │
│   │                                                            │ │
│   │   IF user clicks "Abort":                                  │ │
│   │   ┌─────────────────────────────────────────────────────┐  │ │
│   │   │ • Prompt: "Keep written sections or discard?"       │  │ │
│   │   │ • Save choice to post_meta                           │  │ │
│   │   └─────────────────────────────────────────────────────┘  │ │
│   │                                                            │ │
│   └────────────────────────────────────────────────────────────┘ │
│        │                                                          │
│        ▼ (after loop)                                            │
│   ┌────────────────────────────────────────────────────────────┐ │
│   │ STEP 2: Finalize                                           │ │
│   │ ──────────────────────────────────────────────────────────  │ │
│   │ • Set status: 'completed'                                  │ │
│   │ • Run auto-refinement if enabled                           │ │
│   │ • Show SEO optimization prompt                              │ │
│   └────────────────────────────────────────────────────────────┘ │
│                                                                   │
└──────────────────────────────────────────────────────────────────┘

Writing State Machine

┌─────────────────────────────────────────────────────────────────────┐
│                      WRITING STATE MACHINE                          │
├─────────────────────────────────────────────────────────────────────┤
│                                                                      │
│                     ┌─────────────┐                                  │
│                     │  IDLE      │                                  │
│                     │ (No active │                                  │
│                     │  writing)   │                                  │
│                     └──────┬──────┘                                  │
│                            │                                        │
│          User clicks "Start Writing"                                │
│                            │                                        │
│                            ▼                                        │
│                     ┌─────────────┐                                  │
│                     │ INITIALIZED │                                  │
│                     │ Preparing   │                                  │
│                     │ context     │                                  │
│                     └──────┬──────┘                                  │
│                            │                                        │
│                            ▼                                        │
│                     ┌─────────────┐                                  │
│              ┌──────│  WRITING    │──────┐                          │
│              │      │ Section N   │      │                          │
│              │      │ of M        │      │                          │
│              │      └──────┬──────┘      │                          │
│              │             │             │                          │
│              │    ┌────────┴────────┐     │                          │
│              │    │                 │     │                          │
│              │ Pause           Continue │                          │
│              │    │                 │     │                          │
│              │    ▼                 ▼     │                          │
│              │ ┌──────────┐    ┌──────────────┐                      │
│              │ │  PAUSED  │    │SECTION_DONE │                      │
│              │ │          │    │  Next sec?  │                      │
│              │ │ Resume?  │    └──────┬───────┘                      │
│              │ │  Abort?  │           │                             │
│              │ └────┬─────┘           │ All done                    │
│              │      │                 ▼                             │
│              │      │           ┌──────────────┐                    │
│              │      └──────────▶│  COMPLETED   │                    │
│              │                  │  Run SEO    │                    │
│              │                  └──────────────┘                    │
│              │                                                         │
│              └─────────── User aborts ──────────────▶ ABORTED         │
│                                                                      │
│ STATE PERSISTENCE:                                                    │
│ ─────────────────────────────────────────────────────────────────── │
│ Writing state is saved to post_meta on every state change:           │
│ • current_section_index                                              │
│ • sections_written[]                                                  │
│ • content_inserted                                                   │
│ • token_usage_so_far                                                  │
│ • estimated_time_remaining                                            │
│                                                                      │
│ This enables seamless resume after page refresh.                      │
│                                                                      │
└─────────────────────────────────────────────────────────────────────┘

Block-Level Writing (Alternative Mode)

For sites using Gutenberg, individual blocks can be written:

┌──────────────────────────────────────────────────────────────────┐
│                    BLOCK WRITING MODE                             │
├──────────────────────────────────────────────────────────────────┤
│                                                                   │
│   USER SELECTS: A specific block in the editor                    │
│        │                                                          │
│        ▼                                                          │
│   ┌────────────────────────────────────────────────────────────┐ │
│   │ DETECT BLOCK TYPE                                           │ │
│   │ ──────────────────────────────────────────────────────────  │ │
│   │ • Paragraph → Write prose                                   │ │
│   │ • Heading → Write heading + subheading                      │ │
│   │ • List → Write list items                                    │ │
│   │ • Quote → Write quote with attribution                       │ │
│   │ • Image → Trigger image generation                           │ │
│   └────────────────────────────────────────────────────────────┘ │
│        │                                                          │
│        ▼                                                          │
│   ┌────────────────────────────────────────────────────────────┐ │
│   │ GENERATE CONTENT                                            │ │
│   │ ──────────────────────────────────────────────────────────  │ │
│   │ • Context: surrounding blocks + plan + focus keyword       │ │
│   │ • Model: writing_model                                       │ │
│   │ • Output: Block-specific content                             │ │
│   └────────────────────────────────────────────────────────────┘ │
│        │                                                          │
│        ▼                                                          │
│   ┌────────────────────────────────────────────────────────────┐ │
│   │ REPLACE/INSERT BLOCK                                         │ │
│   │ ──────────────────────────────────────────────────────────  │ │
│   │ • User confirms → Replace block                             │ │
│   │ • User edits → Apply with edits                              │ │
│   │ • User cancels → Discard                                     │ │
│   └────────────────────────────────────────────────────────────┘ │
│                                                                   │
└──────────────────────────────────────────────────────────────────┘

Refinement System

Refinement Types

Type Scope Use Case
Block Refinement Single block Fix specific section
Section Refinement Single section Improve entire section
Article Refinement Full article Global improvements
SEO Refinement Meta + Content Optimize for search
Style Refinement Tone/Voice Match brand voice

Article Refinement Pipeline

┌──────────────────────────────────────────────────────────────────┐
│                  ARTICLE REFINEMENT PIPELINE                      │
├──────────────────────────────────────────────────────────────────┤
│                                                                   │
│   USER TRIGGERS REFINEMENT                                        │
│   "Improve this article" / "Make it more engaging" / etc.        │
│        │                                                          │
│        ▼                                                          │
│   ┌────────────────────────────────────────────────────────────┐ │
│   │ PASS 1: Clarity & Readability                              │ │
│   │ ──────────────────────────────────────────────────────────  │ │
│   │ • Simplify complex sentences                               │ │
│   │ • Improve sentence flow                                    │ │
│   │ • Reduce jargon                                            │ │
│   │ • Increase scannability                                    │ │
│   └────────────────────────────────────────────────────────────┘ │
│        │                                                          │
│        ▼                                                          │
│   ┌────────────────────────────────────────────────────────────┐ │
│   │ PASS 2: SEO Optimization                                   │ │
│   │ ──────────────────────────────────────────────────────────  │ │
│   │ • Integrate focus keyword naturally                        │ │
│   │ • Add related keywords                                      │ │
│   │ • Improve headings structure                                │ │
│   │ • Add internal link suggestions                            │ │
│   └────────────────────────────────────────────────────────────┘ │
│        │                                                          │
│        ▼                                                          │
│   ┌────────────────────────────────────────────────────────────┐ │
│   │ PASS 3: Quality Enhancement                                │ │
│   │ ──────────────────────────────────────────────────────────  │ │
│   │ • Strengthen conclusions                                   │ │
│   │ • Add examples where missing                               │ │
│   │ • Improve transitions                                      │ │
│   │ • Ensure consistent tone                                   │ │
│   └────────────────────────────────────────────────────────────┘ │
│        │                                                          │
│        ▼                                                          │
│   ┌────────────────────────────────────────────────────────────┐ │
│   │ DISPLAY DIFF                                                 │ │
│   │ ──────────────────────────────────────────────────────────  │ │
│   │ • Show side-by-side comparison                              │ │
│   │ • Highlight specific changes                                │ │
│   │ • Enable selective acceptance                               │ │
│   └────────────────────────────────────────────────────────────┘ │
│        │                                                          │
│        ▼                                                          │
│   USER APPROVES → Apply changes                                   │
│                                                                   │
└──────────────────────────────────────────────────────────────────┘

SEO & GEO Handler System

SEO Handler Components

┌─────────────────────────────────────────────────────────────────────┐
│                       SEO HANDLER SYSTEM                             │
├─────────────────────────────────────────────────────────────────────┤
│                                                                      │
│  ┌───────────────────────────────────────────────────────────────┐  │
│  │                    META OPTIMIZATION                          │  │
│  │  ───────────────────────────────────────────────────────────  │  │
│  │                                                               │  │
│  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐         │  │
│  │  │  Title      │  │  Meta Desc  │  │  Slug       │         │  │
│  │  │  Generator  │  │  Generator  │  │  Optimizer  │         │  │
│  │  └──────┬──────┘  └──────┬──────┘  └──────┬──────┘         │  │
│  │         │                │                │                  │  │
│  │         └────────────────┴────────────────┘                  │  │
│  │                           │                                   │  │
│  │                           ▼                                   │  │
│  │                  ┌─────────────────┐                          │  │
│  │                  │  SEO Preview   │                         │  │
│  │                  │  (Google/SERP)  │                         │  │
│  │                  └─────────────────┘                          │  │
│  └───────────────────────────────────────────────────────────────┘  │
│                              │                                       │
│                              ▼                                       │
│  ┌───────────────────────────────────────────────────────────────┐  │
│  │                    CONTENT OPTIMIZATION                      │  │
│  │  ───────────────────────────────────────────────────────────  │  │
│  │                                                               │  │
│  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐         │  │
│  │  │  Keyword    │  │  Content    │  │  Heading    │         │  │
│  │  │  Density    │  │  Length     │  │  Structure  │         │  │
│  │  │  Analyzer   │  │  Checker    │  │  Checker    │         │  │
│  │  └─────────────┘  └─────────────┘  └─────────────┘         │  │
│  │                                                               │  │
│  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐         │  │
│  │  │  Internal   │  │  External   │  │  Readability│         │  │
│  │  │  Links      │  │  Links      │  │  Score      │         │  │
│  │  └─────────────┘  └─────────────┘  └─────────────┘         │  │
│  └───────────────────────────────────────────────────────────────┘  │
│                              │                                       │
│                              ▼                                       │
│  ┌───────────────────────────────────────────────────────────────┐  │
│  │                    FAQ GENERATION                            │  │
│  │  ───────────────────────────────────────────────────────────  │  │
│  │                                                               │  │
│  │  ┌───────────────────────────────────────────────────────┐  │  │
│  │  │  AI analyzes article content and generates            │  │  │
│  │  │  relevant FAQ questions people ask about topic        │  │  │
│  │  │                                                       │  │  │
│  │  │  Output: FAQ schema + FAQ block for article           │  │  │
│  │  └───────────────────────────────────────────────────────┘  │  │
│  └───────────────────────────────────────────────────────────────┘  │
│                              │                                       │
│                              ▼                                       │
│  ┌───────────────────────────────────────────────────────────────┐  │
│  │                    SCHEMA MARKUP                             │  │
│  │  ───────────────────────────────────────────────────────────  │  │
│  │                                                               │  │
│  │  ┌─────────┐  ┌─────────┐  ┌─────────┐  ┌─────────┐         │  │
│  │  │ Article │  │  FAQ    │  │  HowTo  │  │  FAQ    │         │  │
│  │  │  Schema │  │  Schema │  │  Schema │  │  Page   │         │  │
│  │  └─────────┘  └─────────┘  └─────────┘  └─────────┘         │  │
│  │                                                               │  │
│  │  Auto-generated JSON-LD injected into <head>                │  │
│  └───────────────────────────────────────────────────────────────┘  │
│                                                                      │
└─────────────────────────────────────────────────────────────────────┘

GEO (Generative Engine Optimization)

Note: GEO refers to optimizing content for AI-generated search results (Google SGE, Bing Chat, etc.)

┌─────────────────────────────────────────────────────────────────────┐
│                    GEO OPTIMIZATION SYSTEM                           │
├─────────────────────────────────────────────────────────────────────┤
│                                                                      │
│   AI OVERVIEW OPTIMIZATION:                                          │
│   ───────────────────────────────────────────────────────────────── │
│                                                                      │
│   Content needs to be:                                               │
│   • Clear and direct (answer questions immediately)                 │
│   • Well-structured with headers                                     │
│   • Contains definitive statements, not hedged language              │
│   • Has factual claims with supporting evidence                     │
│   • Properly formatted lists and tables                              │
│                                                                      │
│   ┌──────────────────────────────────────────────────────────────┐  │
│   │                    GEO SCORE CHECK                           │  │
│   │  ──────────────────────────────────────────────────────────  │  │
│   │                                                               │  │
│   │  Score based on:                                              │  │
│   │  • Directness: Does content answer questions upfront?        │  │
│   │  • Structure: Is content well-organized with headers?         │  │
│   │  • Authority: Does it cite sources and show expertise?         │  │
│   │  • Clarity: Is language clear, avoiding ambiguity?           │  │
│   │  • Completeness: Does it cover all aspects of the topic?      │  │
│   │                                                               │  │
│   │  Score Range: 0-100                                           │  │
│   │  Target: 80+ for AI Overview eligibility                     │  │
│   │                                                               │  │
│   └──────────────────────────────────────────────────────────────┘  │
│                                                                      │
│   ┌──────────────────────────────────────────────────────────────┐  │
│   │                 GEO IMPROVEMENT SUGGESTIONS                  │  │
│   │  ──────────────────────────────────────────────────────────  │  │
│   │                                                               │  │
│   │  If score < 80, suggest:                                       │  │
│   │  • "Add a summary at the start"                               │  │
│   │  • "Use more bullet points"                                    │  │
│   │  • "Include statistics or facts"                               │  │
│   │  • "Add expert quotes"                                         │  │
│   │  • "Structure with clear H2/H3 headers"                       │  │
│   │                                                               │  │
│   └──────────────────────────────────────────────────────────────┘  │
│                                                                      │
└─────────────────────────────────────────────────────────────────────┘

SEO Flow Implementation

┌──────────────────────────────────────────────────────────────────┐
│                      SEO HANDLER FLOW                             │
├──────────────────────────────────────────────────────────────────┤
│                                                                   │
│   USER CLICKS: "SEO Optimize"                                     │
│        │                                                          │
│        ▼                                                          │
│   ┌────────────────────────────────────────────────────────────┐ │
│   │ STEP 1: Analyze Content                                      │ │
│   │ ──────────────────────────────────────────────────────────  │ │
│   │ • Extract focus keyword from meta                           │ │
│   │ • Analyze current keyword density                           │ │
│   │ • Calculate content length vs competitors                   │ │
│   │ • Identify missing SEO elements                             │ │
│   └────────────────────────────────────────────────────────────┘ │
│        │                                                          │
│        ▼                                                          │
│   ┌────────────────────────────────────────────────────────────┐ │
│   │ STEP 2: Generate Meta                                       │ │
│   │ ──────────────────────────────────────────────────────────  │ │
│   │ • Title: 50-60 chars, keyword at start                      │ │
│   │ • Description: 150-160 chars, compelling                    │ │
│   │ • Slug: Clean, keyword-based                                │ │
│   └────────────────────────────────────────────────────────────┘ │
│        │                                                          │
│        ▼                                                          │
│   ┌────────────────────────────────────────────────────────────┐ │
│   │ STEP 3: Generate FAQ                                        │ │
│   │ ──────────────────────────────────────────────────────────  │ │
│   │ • AI analyzes article                                        │ │
│   │ • Generate 5-8 relevant questions                           │ │
│   │ • Generate answers for each                                  │ │
│   │ • Format for FAQ schema                                      │ │
│   └────────────────────────────────────────────────────────────┘ │
│        │                                                          │
│        ▼                                                          │
│   ┌────────────────────────────────────────────────────────────┐ │
│   │ STEP 4: Generate Schema                                      │ │
│   │ ──────────────────────────────────────────────────────────  │ │
│   │ • Article schema with author, date, modified                │ │
│   │ • FAQ schema (if FAQ generated)                             │ │
│   │ • Breadcrumb schema                                         │ │
│   └────────────────────────────────────────────────────────────┘ │
│        │                                                          │
│        ▼                                                          │
│   ┌────────────────────────────────────────────────────────────┐ │
│   │ STEP 5: Display & Apply                                      │ │
│   │ ──────────────────────────────────────────────────────────  │ │
│   │ • Show SEO preview (Google snippet)                        │ │
│   │ • Show FAQ preview                                           │ │
│   │ • Show Schema preview (collapsible)                         │ │
│   │ • Apply All / Apply Individual buttons                       │ │
│   └────────────────────────────────────────────────────────────┘ │
│                                                                   │
└──────────────────────────────────────────────────────────────────┘

Markdown Rendering System

Markdown to Blocks Converter

const markdownToBlocks = {
  // Headers
  '^#{1}\\s+(.*)$': 'core/heading',
  '^#{2}\\s+(.*)$': 'core/heading',
  '^#{3}\\s+(.*)$': 'core/heading',
  '^#{4}\\s+(.*)$': 'core/heading',

  // Paragraphs
  '^(?!#{1,6}|\\*|\\d+\\.|- ).*$': 'core/paragraph',

  // Lists
  '^\\*\\s+(.*)$': 'core/list',
  '^\\d+\\.\\s+(.*)$': 'core/list',

  // Blockquotes
  '^>\\s+(.*)$': 'core/quote',

  // Code blocks
  '^```(\\w*)\\n([\\s\\S]*?)```$': 'core/code',

  // Images
  '^!\\[([^\\]]*)\\]\\(([^)]*)\\)$': 'core/image',

  // Horizontal rules
  '^---$': 'core/separator'
};

Markdown Rendering in Sidebar

┌──────────────────────────────────────────────────────────────────┐
│                  MARKDOWN RENDERING IN SIDEBAR                     │
├──────────────────────────────────────────────────────────────────┤
│                                                                   │
│   SOURCE: AI generates Markdown                                    │
│        │                                                          │
│        ▼                                                          │
│   ┌────────────────────────────────────────────────────────────┐ │
│   │ RENDERER OPTIONS                                            │ │
│   │ ──────────────────────────────────────────────────────────  │ │
│   │                                                               │ │
│   │ [ ] WYSIWYG Preview (Interactive)                            │ │
│   │ [x] Markdown Source (Code-like)                              │ │
│   │ [ ] Split View (Side-by-side)                                │ │
│   │                                                               │ │
│   │ Toggle: "Preview" / "Markdown" / "Split"                     │ │
│   └────────────────────────────────────────────────────────────┘ │
│        │                                                          │
│        ▼                                                          │
│   ┌────────────────────────────────────────────────────────────┐ │
│   │ FEATURE HIGHLIGHTS                                           │ │
│   │ ──────────────────────────────────────────────────────────  │ │
│   │                                                               │  │
│   │ • Syntax highlighting for code blocks                       │  │
│   │ • Collapsible headings for long content                     │  │
│   │ • Quick copy button for each section                         │  │
│   │ • Insert into editor button                                  │  │
│   │ • @mention highlighting in preview                           │  │
│   │                                                               │  │
│   └────────────────────────────────────────────────────────────┘ │
│                                                                   │
└──────────────────────────────────────────────────────────────────┘

Future-Proof Architecture

Extensibility Points

┌─────────────────────────────────────────────────────────────────────┐
│                    EXTENSIBILITY ARCHITECTURE                        │
├─────────────────────────────────────────────────────────────────────┤
│                                                                      │
│  PLUGINS/ADDONS HOOK INTO:                                           │
│  ───────────────────────────────────────────────────────────────── │
│                                                                      │
│  ┌─────────────────────────────────────────────────────────────┐   │
│  │ HOOKS (Actions & Filters)                                    │   │
│  │  • wpaw_before_generate                                      │   │
│  │  • wpaw_after_generate                                       │   │
│  │  • wpaw_context_optimized                                    │   │
│  │  • wpaw_outline_created                                      │   │
│  │  • wpaw_section_written                                      │   │
│  │  • wpaw_article_completed                                    │   │
│  │  • wpaw_seo_analyzed                                         │   │
│  │  • wpaw_filter_context                                       │   │
│  │  • wpaw_filter_prompt                                        │   │
│  └─────────────────────────────────────────────────────────────┘   │
│                                                                      │
│  ┌─────────────────────────────────────────────────────────────┐   │
│  │ PROVIDER SYSTEM                                              │   │
│  │  • OpenRouter (default)                                      │   │
│  │  • Local Backend (LM Studio, Ollama)                         │   │
│  │  • Custom providers via filter                               │   │
│  │                                                              │   │
│  │  add_filter('wpaw_provider_for_task', function($provider,    │   │
│  │              $task, $context) { ... }, 10, 3);              │   │
│  └─────────────────────────────────────────────────────────────┘   │
│                                                                      │
│  ┌─────────────────────────────────────────────────────────────┐   │
│  │ MODE EXTENSIONS                                              │   │
│  │  • Future modes can be added via filter                      │   │
│  │  • Mode-specific hooks for customization                     │   │
│  │                                                              │   │
│  │  add_filter('wpaw_available_modes', function($modes) {      │   │
│  │      $modes['translation'] = 'Translation Mode';             │   │
│  │      return $modes;                                          │   │
│  │  });                                                         │   │
│  └─────────────────────────────────────────────────────────────┘   │
│                                                                      │
│  ┌─────────────────────────────────────────────────────────────┐   │
│  │ SEO INTEGRATION                                              │   │
│  │  • Yoast SEO hooks                                           │   │
│  │  • Rank Math integration                                     │   │
│  │  • Schema.org validators                                     │   │
│  │                                                              │   │
│  │  add_filter('wpaw_seo_score', function($score, $content) {   │   │
│  │      // Custom SEO scoring logic                             │   │
│  │  });                                                         │   │
│  └─────────────────────────────────────────────────────────────┘   │
│                                                                      │
└─────────────────────────────────────────────────────────────────────┘

Data Migration Strategy

// Version-aware data structure for future migrations
const stateVersion = {
  version: '1.0',
  schema: '2026-05-17',
  migrations: [
    {
      from: '0.x',
      to: '1.0',
      script: migrate_0x_to_1_0
    }
  ]
};

// On load, check version and migrate if needed
function ensureCurrentVersion(postId) {
  const currentVersion = getPostMeta(postId, '_wpaw_state_version');
  if (currentVersion !== stateVersion.version) {
    runMigrations(currentVersion, stateVersion.version);
    setPostMeta(postId, '_wpaw_state_version', stateVersion.version);
  }
}

API Versioning

/wp-json/wp-agentic-writer/v1/     ← Current stable
/wp-json/wp-agentic-writer/v2/     ← Future versions
/wp-json/wp-agentic-writer/v1/legacy  ← Old endpoints, deprecated

Implementation Priority

Phase 1: Core Foundation (Critical)

  1. Document state detection (new vs edit)
  2. Mode system implementation
  3. Context management
  4. Basic chat functionality

Phase 2: Writing Pipeline

  1. Outline creation flow
  2. Outline refinement
  3. Section writing
  4. Writing state persistence

Phase 3: Refinement

  1. Block refinement
  2. Article refinement
  3. Multi-pass refinement

Phase 4: SEO & GEO

  1. Meta title/description generation
  2. FAQ generation
  3. Schema markup
  4. GEO optimization

Phase 5: Polish

  1. Markdown rendering
  2. Performance optimization
  3. Error handling
  4. Testing

File Structure

wp-agentic-writer/
├── includes/
│   ├── class-gutenberg-sidebar.php    # Main chat interface
│   ├── class-context-manager.php       # Context building
│   ├── class-mode-controller.php       # Mode state machine
│   ├── class-outline-manager.php        # Outline handling
│   ├── class-writing-pipeline.php      # Writing flow
│   ├── class-refinement-engine.php     # Refinement system
│   ├── class-seo-handler.php           # SEO operations
│   └── providers/
│       └── class-openrouter-provider.php
├── assets/
│   ├── js/
│   │   ├── sidebar.js                   # React sidebar
│   │   ├── context-manager.js          # Context utilities
│   │   └── markdown-renderer.js         # MD rendering
│   └── css/
│       ├── agentic-workflow.css        # Workflow UI
│       └── sidebar-chat.css           # Chat styling
└── views/
    └── settings/

Document Status: 🔴 DRAFT - PENDING IMPLEMENTATION Estimated Implementation: 40-60 hours Next Step: Start with Phase 1 (Core Foundation)


Last Updated: 2026-05-17 Author: Claude (AI Assistant)