refactor: Cleanup git state - commit all staged changes

Major refactoring cleanup:
- Add new controller architecture (class-controller-*.php)
- Add new settings-v2 UI (views/settings-v2/)
- Add new CSS architecture (agentic-sidebar.css, tokens)
- Add esbuild build pipeline (scripts/build.js, package.json)
- Add composer dependencies (vendor/)
- Add frontend src directory (assets/js/src/index.jsx)
- Add documentation files
- Remove old/obsolete files (class-settings.php, old CSS)

This commits all pending changes from previous refactoring efforts.
This commit is contained in:
Dwindi Ramadhana
2026-06-17 05:27:58 +07:00
parent d3f142222c
commit 690991c526
7963 changed files with 941566 additions and 67372 deletions

View File

@@ -1,506 +0,0 @@
# WP Agentic Writer - Distribution Strategy
**Version:** 1.0
**Date:** 2026-05-17
**Strategy:** Freemium with Addon Model
---
## Executive Summary
This document outlines a comprehensive strategy for distributing WP Agentic Writer as two distinct versions:
- **Free Version** - Published on WordPress.org repository for maximum visibility and user acquisition
- **Pro Version** - Premium addon sold via your own license server with advanced features
**Core Philosophy:** The free version must be a complete, valuable product on its own. Pro features are genuine enhancements that power users will happily pay for.
---
## Architecture Overview
```
┌─────────────────────────────────────────────────────────────┐
│ WP AGENTIC WRITER │
├─────────────────────────────────────────────────────────────┤
│ FREE CORE PLUGIN (WordPress.org) │
│ ├── AI Writing Assistant (sidebar) │
│ ├── Context Management │
│ ├── Planning & Writing Pipeline │
│ ├── Model Selection (OpenRouter) │
│ ├── Basic Refinement │
│ ├── Cost Tracking │
│ └── Hook System (for extensibility) │
├─────────────────────────────────────────────────────────────┤
│ PRO ADDON (License Server) │
│ ├── License Verification System │
│ ├── Advanced Refinement (multi-pass) │
│ ├── Local Backend Integration (extended) │
│ ├── Brave Search Integration │
│ ├── Image Generation (DALL-E, Stable Diffusion) │
│ ├── Custom Model Presets │
│ ├── Team Collaboration │
│ ├── Priority Support │
│ └── Advanced Analytics │
└─────────────────────────────────────────────────────────────┘
```
---
## Feature Distribution
### Free Version Features
#### Core Writing Pipeline
| Feature | Description | Strategic Value |
|---------|-------------|-----------------|
| Planning Mode | AI-powered article outline creation | Core value prop |
| Writing Mode | Generate full articles with context | Core value prop |
| Chat Mode | Quick AI assistance | Engagement driver |
| Refinement Mode | Basic content polishing | Entry to refinement |
| @mention Detection | Link to related posts | Unique capability |
| Clarification Quiz | Guided topic extraction | User onboarding |
| Focus Keyword | SEO-first writing | Differentiation |
#### Model Integration
| Feature | Description | Strategic Value |
|---------|-------------|-----------------|
| OpenRouter Integration | Access to 100+ models | Flexibility |
| Model Selection UI | Easy model switching | Usability |
| Preset Configurations | Budget/Balanced/Premium | Quick start |
| Cost Estimation | Real-time cost display | Budget control |
#### Analytics & Tracking
| Feature | Description | Strategic Value |
|---------|-------------|-----------------|
| Cost Log | Basic usage tracking | Transparency |
| Token Usage | Input/output tracking | Optimization |
| Daily/Monthly Stats | Usage overview | Awareness |
#### Technical Foundation
| Feature | Description | Strategic Value |
|---------|-------------|-----------------|
| Gutenberg Integration | Block editor sidebar | Core integration |
| Classic Editor Support | Alternative UI | Coverage |
| Shortcode Support | Flexible embedding | Versatility |
| REST API Endpoints | Developer hooks | Ecosystem |
| WebSocket Status | Real-time updates | Polish |
---
### Pro Addon Features
#### Advanced Refinement (Multi-Pass)
| Feature | Description | Value |
|---------|-------------|-------|
| Multi-Pass Refinement | 3-stage polishing (clarity, SEO, quality) | High |
| Keyword Density Optimization | Automatic SEO improvement | High |
| Readability Scoring | Flesch-Kincaid integration | Medium |
| Plagiarism Check | Integration with Copyscape API | Premium |
| Brand Voice Training | Learn from existing content | Premium |
#### External Integrations
| Feature | Description | Value |
|---------|-------------|-------|
| Brave Search Integration | Real-time web research | High |
| Image Generation (DALL-E 3) | AI-generated featured images | High |
| Image Generation (SDXL) | Stable Diffusion XL | Premium |
| Unsplash Integration | Stock photo search | Medium |
| WordPress Media Library | Direct image management | Medium |
#### Local Backend (Extended)
| Feature | Description | Value |
|---------|-------------|-------|
| LM Studio Support (Full) | Complete integration | Medium |
| Ollama Support (Full) | Complete integration | Medium |
| Self-Hosted Models | Custom model hosting | Premium |
| Multi-Instance Support | Multiple backend servers | Premium |
| Load Balancing | Automatic failover | Premium |
#### Collaboration & Team
| Feature | Description | Value |
|---------|-------------|-------|
| Team Workspaces | Shared configurations | Premium |
| User Roles & Permissions | Role-based access | Premium |
| Activity Logs | Audit trails | Medium |
| Template Sharing | Team templates | Medium |
| Content Approvals | Workflow integration | Premium |
#### Advanced Analytics
| Feature | Description | Value |
|---------|-------------|-------|
| ROI Calculator | Content performance vs cost | Medium |
| Content Performance | SEO ranking tracking | Premium |
| A/B Testing | Headline variations | Premium |
| Seasonal Trends | Content calendar | Premium |
#### Priority Support
| Feature | Description | Value |
|---------|-------------|-------|
| Email Support | Direct assistance | Medium |
| Priority Response | 24hr vs 7 days | Medium |
| Feature Requests | Influence roadmap | Low |
| Custom Integrations | Bespoke solutions | Premium |
---
## Hook System Architecture
### Purpose
The free version provides comprehensive hooks that both Pro addon and third-party developers can use to extend functionality.
### Hook Types
#### 1. Action Hooks (Events)
```php
// Writing lifecycle
do_action('wpaw_before_generate', $post_id, $mode);
do_action('wpaw_after_generate', $post_id, $mode, $content);
do_action('wpaw_planning_started', $post_id);
do_action('wpaw_planning_complete', $post_id, $plan);
do_action('wpaw_writing_started', $post_id, $section_index);
do_action('wpaw_writing_section_complete', $post_id, $section_index, $content);
do_action('wpaw_refinement_started', $post_id);
do_action('wpaw_refinement_complete', $post_id, $refined_content);
// Model interactions
do_action('wpaw_model_selected', $model_id, $task_type);
do_action('wpaw_api_request_sent', $model_id, $tokens, $cost);
do_action('wpaw_api_response_received', $model_id, $response_time);
// Context management
do_action('wpaw_context_loaded', $post_id, $context_data);
do_action('wpaw_context_updated', $post_id, $changes);
// Cost tracking
do_action('wpaw_cost_recorded', $record);
do_action('wpaw_daily_limit_reached', $total_cost);
```
#### 2. Filter Hooks (Data Modification)
```php
// Context modification
add_filter('wpaw_context_data', 'modify_context', 10, 2);
add_filter('wpaw_post_content', 'process_content', 10, 2);
add_filter('wpaw_planning_prompt', 'customize_planning', 10, 2);
// Model selection
add_filter('wpaw_model_for_task', 'override_model', 10, 3);
add_filter('wpaw_model_parameters', 'customize_params', 10, 2);
// Output modification
add_filter('wpaw_generated_content', 'post_process', 10, 3);
add_filter('wpaw_refinement_criteria', 'custom_criteria', 10, 2);
// Cost calculations
add_filter('wpaw_cost_calculation', 'adjust_cost', 10, 2);
add_filter('wpaw_token_count', 'modify_tokens', 10, 2);
```
#### 3. REST API Endpoints
```
POST /wpaw/v1/generate
- Generate content via API
- Authentication: API key or OAuth
POST /wpaw/v1/refine
- Refine existing content
- Parameters: content, criteria, iterations
GET /wpaw/v1/cost-log
- Retrieve cost tracking data
- Filters: date range, post_id, model
GET /wpaw/v1/models
- List available models
- Include pricing and capabilities
POST /wpaw/v1/context
- Update context for specific post
```
#### 4. JavaScript Events (Frontend)
```javascript
// jQuery / DOM Events
document.dispatchEvent(new CustomEvent('wpaw:generation-start', {
detail: { postId, mode }
}));
document.dispatchEvent(new CustomEvent('wpaw:generation-complete', {
detail: { postId, content, cost }
}));
document.dispatchEvent(new CustomEvent('wpaw:section-written', {
detail: { postId, sectionIndex, content }
}));
// React component hooks (for sidebar)
window.wpawHooks = {
onBeforeGenerate: (postId, mode) => {},
onAfterGenerate: (postId, mode, content) => {},
onModelSelected: (modelId, taskType) => {},
};
```
---
## Licensing System
### Pro Addon Structure
#### License Types
| Type | Price Point | Activations | Features |
|------|-------------|-------------|----------|
| Personal | $49/year | 1 site | All Pro features |
| Professional | $99/year | 5 sites | All Pro + priority support |
| Agency | $199/year | 25 sites | All Pro + team features |
| Enterprise | Custom | Unlimited | White-label + SLA |
#### License Verification Flow
```
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ User │ │ Pro Addon │ │ License │
│ Activates │────▶│ Checks │────▶│ Server │
└──────────────┘ └──────────────┘ └──────────────┘
│ │
│ Valid? │
▼ ▼
┌──────────────┐ ┌──────────────┐
│ Enable Pro │ │ Response: │
│ Features │◀────│ key, expiry, │
└──────────────┘ │ features │
└──────────────┘
```
### License Server Requirements
#### Endpoints
```
POST /api/v1/verify
- Input: license_key, domain, product_id
- Output: { valid: bool, expires: date, features: [] }
POST /api/v1/activate
- Input: license_key, domain
- Output: { activation_id, sites_used, sites_limit }
POST /api/v1/deactivate
- Input: activation_id
- Output: { success: bool }
GET /api/v1/status
- Input: license_key
- Output: { active: bool, sites: [], expires: date }
```
#### Security Measures
- License key hashed with SHA-256 before storage
- Domain binding prevents key sharing
- Activation limit enforcement
- Automatic deactivation on payment failure
- IP-based rate limiting on verification
---
## Migration Path
### Upgrading from Free to Pro
```
┌──────────────────────────────────────────────────────────┐
│ Step 1: User purchases Pro license │
│ └── Receives license key via email │
│ │
│ Step 2: User installs Pro Addon │
│ └── Upload via WordPress admin │
│ └── Activates alongside free plugin │
│ │
│ Step 3: User enters license key │
│ └── Addon validates against license server │
│ └── Activates on current domain │
│ │
│ Step 4: Pro features unlocked │
│ └── UI shows Pro indicators │
│ └── New tabs/options become visible │
│ └── Settings synced from free version │
│ │
│ Step 5: Deactivate/reactivate │
│ └── Can transfer license to new domain │
│ └── Previous site features disabled │
└──────────────────────────────────────────────────────────┘
```
### Data Migration
- Settings stored in `wp_options` - shared between free and pro
- Pro settings prefixed with `wpaw_pro_`
- Cost tracking uses unified table structure
- No data loss during upgrade
---
## File Structure
### Free Plugin (WordPress.org)
```
wp-agentic-writer/
├── wp-agentic-writer.php # Main plugin file
├── readme.txt # WordPress.org readme
├── uninstall.php # Clean uninstall
├── includes/
│ ├── class-plugin.php # Core plugin class
│ ├── class-settings.php # Settings page
│ ├── class-gutenberg-sidebar.php # Sidebar UI
│ ├── providers/
│ │ └── class-openrouter-provider.php
│ └── helpers/
│ └── class-context-manager.php
├── assets/
│ ├── css/
│ │ ├── agentic-variables.css
│ │ ├── agentic-components.css
│ │ └── agentic-workflow.css
│ └── js/
│ └── sidebar.js
├── views/
│ └── settings/
└── lang/
└── wp-agentic-writer.pot
```
### Pro Addon
```
wp-agentic-writer-pro/
├── wp-agentic-writer-pro.php # Main addon file
├── includes/
│ ├── class-license-manager.php # License verification
│ ├── class-pro-features.php # Feature toggles
│ ├── providers/
│ │ ├── class-brave-search.php
│ │ └── class-image-generator.php
│ ├── refinement/
│ │ └── class-multi-pass-refinement.php
│ └── analytics/
│ └── class-pro-analytics.php
└── admin/
└── class-pro-admin.php # Pro settings UI
```
---
## Testing Checklist
### Pre-Release Validation
#### Free Version
- [ ] Works with WordPress 6.0+ (latest stable)
- [ ] Works with PHP 7.4+ (minimum) and 8.x (recommended)
- [ ] No PHP errors/warnings in debug mode
- [ ] All hooks documented and functional
- [ ] Settings page renders correctly
- [ ] Sidebar works in Gutenberg and Classic
- [ ] Uninstall removes all plugin data
- [ ] Internationalization (i18n) complete
#### Pro Addon
- [ ] Gracefully fails without license
- [ ] Shows upgrade prompts for locked features
- [ ] License verification works offline (cached)
- [ ] Reactivation works correctly
- [ ] No errors when free plugin inactive
- [ ] License expiry handled gracefully
---
## Rollout Strategy
### Phase 1: Preparation (Week 1-2)
1. Finalize Pro feature set
2. Set up license server infrastructure
3. Create Pro addon codebase
4. Prepare marketing copy
### Phase 2: Soft Launch (Week 3)
1. Release free plugin to limited beta
2. Test with 10-20 trusted users
3. Gather feedback and fix critical issues
### Phase 3: WordPress.org Submission (Week 4)
1. Prepare WordPress.org assets (banner, icons)
2. Write compliant readme.txt
3. Submit for review
4. Address review feedback (typically 1-2 weeks)
### Phase 4: Pro Launch (Week 6-8)
1. Launch license server
2. Create sales page
3. Set up payment processing
4. Launch Pro addon
### Phase 5: Marketing (Ongoing)
1. Blog posts on AI writing tools
2. Tutorial videos on YouTube
3. Guest posts on WordPress blogs
4. Community forum engagement
---
## Pricing Considerations
### Factors for Pricing
| Factor | Consideration |
|--------|---------------|
| Competition | Compare to AI writing plugins ($49-$299/year) |
| Value Delivered | Pro features save X hours/month |
| Market Position | Mid-tier vs premium |
| Support Costs | Personal vs team tier |
### Recommended Pricing
| Tier | Price | Rationale |
|------|-------|-----------|
| Personal | $49/year | ~$4/month - impulse purchase |
| Professional | $99/year | ~$8/month - small business |
| Agency | $199/year | ~$8/site/year - good value |
---
## Risk Mitigation
### Technical Risks
| Risk | Mitigation |
|------|------------|
| License server downtime | Cache verification locally (7 days) |
| Key sharing | Domain binding + monitoring |
| WordPress.org policy violation | Clear separation of free/pro |
| Competition | Focus on unique value props |
### Business Risks
| Risk | Mitigation |
|------|------------|
| Low adoption | Start with strong free feature set |
| Support overload | Tiered support, clear documentation |
| Piracy | Regular audits, IP monitoring |
| Negative reviews | Proactive beta testing |
---
## Success Metrics
### Free Version
| Metric | Target |
|--------|--------|
| WordPress.org downloads (6 months) | 5,000+ |
| Active installations | 2,000+ |
| 5-star rating | 4.5+ |
| Support forum engagement | <10% of installs |
### Pro Version
| Metric | Target |
|--------|--------|
| Conversion rate (free→pro) | 2-5% |
| Monthly revenue (year 1) | $500-$1,000 |
| License renewals | 60%+ |
| Customer satisfaction | 4.0+ |
---
**Document Version:** 1.0
**Last Updated:** 2026-05-17
**Author:** Claude (AI Assistant)

View File

@@ -0,0 +1,238 @@
# MEMANTO Context Keeper - Pricing Strategy
**Version:** 1.0
**Date:** 2026-06-07
**Status:** Planning
---
## Executive Summary
MEMANTO is an external memory service (powered by Moorcheh SDK) that provides persistent, semantic memory for the WP Agentic Writer plugin. It is sold as a separate subscription from the plugin itself. Users who purchase MEMANTO get a dedicated instance URL and configure it in the plugin settings alongside their own Moorcheh API key.
**Core Value Proposition:** The plugin works perfectly without MEMANTO using the built-in Context Builder. MEMANTO enhances the experience with cross-session memory, semantic recall, and elimination of context loss.
---
## Product Structure
### What the User Purchases
| Item | Description |
|---|---|
| **WP Agentic Writer Plugin** | Sold separately. Lifetime or own subscription model. Works standalone. |
| **MEMANTO Context Keeper** | Separate subscription. User receives a MEMANTO instance URL. |
| **Moorcheh API Key** | User brings their own. Free tier available (10K vectors/month). Billed to user's own Moorcheh account. |
### MEMANTO Instance Per Subscription
- 1 subscription = 1 MEMANTO instance
- 1 MEMANTO instance can be used across up to 15 WordPress sites (1 plugin per site)
- 1 MEMANTO instance requires 1 Moorcheh API key
- Users needing isolated memory per site purchase additional MEMANTO subscriptions
---
## Infrastructure Costs
### Hosting Architecture
| Component | Specification | Cost | Capacity |
|---|---|---|---|
| Coolify VPS | 8 vCPU, 32GB RAM, 200GB storage | $15/month | ~150 MEMANTO instances |
| Subdomain | *.context.wpagentic.dev (wildcard) | $0 | Unlimited |
| Moorcheh API | User's own key | $0 | User's responsibility |
| **Cost per MEMANTO instance** | | **$0.10/month** | |
### Scaling Model
| Subscribers | VPS Nodes | Infra Cost | Revenue at $7/mo |
|---:|---:|---:|---:|
| 1150 | 1 | $15/mo | $1,050/mo |
| 151300 | 2 | $30/mo | $2,100/mo |
| 301450 | 3 | $45/mo | $3,150/mo |
| 1,000+ | 7 | $105/mo | $7,000/mo |
Each additional $15 VPS linearly adds capacity for 150 more subscribers.
---
## Value Delivered to Subscriber
### Cost Savings on AI Tokens
Using the recommended multi-model stack:
| Task | Model | Input/1M | Output/1M |
|---|---|---|---|
| Chat | google/gemini-2.5-flash | $0.30 | $2.50 |
| Planning | deepseek/deepseek-chat | $0.20 | $0.77 |
| Writing | deepseek/deepseek-chat | $0.20 | $0.77 |
| Refinement | meta-llama/llama-3.3-70b-instruct | $0.10 | $0.32 |
### Per-Article Cost Comparison
| Metric | Without MEMANTO | With MEMANTO | Savings |
|---|---:|---:|---:|
| AI calls per article | 35 | 22 | 37% |
| Input tokens | 43,900 | 16,450 | 63% |
| Output tokens | 20,800 | 18,900 | 9% |
| **Cost per article** | **$0.0377** | **$0.0259** | **31%** |
### Monthly Savings at Scale
| Articles/month | Without MEMANTO | With MEMANTO | Saved |
|---:|---:|---:|---:|
| 25 | $0.94 | $0.65 | $0.29 |
| 50 | $1.88 | $1.29 | $0.59 |
| 100 | $3.77 | $2.59 | $1.18 |
| 500 | $18.85 | $12.95 | $5.90 |
### Beyond Cost: Experience Quality
| Feature | Without MEMANTO | With MEMANTO |
|---|---|---|
| Context on mode switch | Can be lost | Preserved via semantic memory |
| Cross-session continuity | Each session starts fresh | AI remembers everything |
| User preference learning | Per-post only | Carries across all posts |
| Chat history management | Truncate to last 6 messages | Semantic recall of relevant context |
| Summarize-context calls | Required (4 per article) | Eliminated |
| Detect-intent calls | Required (10 per article) | Eliminated |
---
## Moorcheh Free Tier Analysis
Free tier provides 10,000 vectors per month.
| Memory Type | Avg per Article | Notes |
|---|---:|---|
| Instructions (user messages) | 10 | Key user intents |
| Decisions (plan approved, etc.) | 3 | Critical checkpoints |
| Corrections (rejections) | 2 | "Don't do X" memories |
| Artifacts (plan, section summaries) | 6 | Compact summaries |
| Preferences (config, tone) | 2 | Per-article settings |
| Context (session summaries) | 2 | End-of-session wrap |
| **Total memories per article** | **~25** | |
**10K vectors ≈ 400 articles/month** on free Moorcheh tier. Sufficient for most users. Power users exceeding this would upgrade their own Moorcheh plan.
---
## Pricing Recommendation
### Launch Pricing
| Plan | Monthly | Annual | Effective Monthly | Sites | Moorcheh |
|---|---:|---:|---:|---:|---|
| **Context Keeper** | $7/mo | $59/yr | $4.92/mo | Up to 15 | Bring own key |
### Pricing Rationale
| Factor | Analysis |
|---|---|
| Infrastructure cost | $0.10/subscriber — margin is ~98% |
| Cost savings delivered | ~$0.012/article; self-funding at 25+ articles/month |
| Psychological threshold | $7 is below $10 impulse-buy barrier |
| Competitive positioning | No comparable WordPress AI memory product exists |
| Plugin dependency | MEMANTO is optional; plugin works without it |
| User acquisition | Low entry price drives adoption and plugin stickiness |
### Revenue Projections
| Subscribers | Monthly Revenue | Annual Revenue | Infra Cost | Net Profit |
|---:|---:|---:|---:|---:|
| 25 | $175 | $2,100 | $15 | $160/mo |
| 50 | $350 | $4,200 | $15 | $335/mo |
| 100 | $700 | $8,400 | $15 | $685/mo |
| 150 | $1,050 | $12,600 | $15 | $1,035/mo |
| 300 | $2,100 | $25,200 | $30 | $2,070/mo |
| 1,000 | $7,000 | $84,000 | $105 | $6,895/mo |
### Pricing Evolution Roadmap
**Phase 1: Launch (Months 16)**
- Single tier at $7/mo or $59/yr
- Focus on user acquisition and feedback
- Monitor Moorcheh free tier usage patterns
**Phase 2: Growth (Months 612)**
- Evaluate raising to $9/mo ($79/yr) based on demand
- Introduce Pro tier at $15/mo for agencies (multi-MEMANTO)
- Add managed Moorcheh option (include API key, absorb cost)
**Phase 3: Scale (12+ Months)**
- Usage-based add-ons if needed
- Enterprise licensing for WordPress VIP / managed hosts
- Reseller program for agencies white-labeling the service
### When to Raise Price
Raise from $7 to $9 when **any** of these conditions are met:
- 50+ active subscribers
- Users volunteer that the price feels too low
- Feature set has grown (file upload, conflict resolution UI, memory browser)
- Churn is below 5% monthly
### Grandfathering Policy
When price increases:
- Existing subscribers keep their original price for 6 months
- Annual subscribers locked in until renewal
- 30-day advance notice before any price change
---
## Billing and Delivery
### Subscriber Onboarding Flow
1. User purchases MEMANTO subscription via payment platform
2. System provisions a MEMANTO instance on Coolify
3. User receives:
- MEMANTO instance URL (e.g., `https://abc123.context.wpagentic.dev`)
- Configuration instructions
4. User inputs in WP Agentic Writer settings:
- MEMANTO URL
- Their own Moorcheh API key
5. Plugin validates connection and activates MEMANTO features
### Provisioning Architecture
Each MEMANTO instance:
- Runs as a Docker container on Coolify
- Uses a unique subdomain under *.context.wpagentic.dev
- Isolates data per subscriber (separate agent namespaces)
- User's Moorcheh API key connects to their own vector store
---
## Risks and Mitigations
| Risk | Likelihood | Impact | Mitigation |
|---|---|---|---|
| Users hit Moorcheh free tier limit | Medium | Low | Clear documentation on limits; prompt to upgrade their Moorcheh plan |
| MEMANTO instance downtime | Low | High | Coolify health checks, auto-restart, user-facing status indicator |
| User doesn't understand "bring own Moorcheh key" | Medium | Medium | Step-by-step onboarding guide; one-click Moorcheh signup link |
| Subscriber churn after trial | Medium | Medium | Deliver clear value early (show "memories recalled" indicator in plugin) |
| Infrastructure cost spike | Low | Low | Cost is fixed $15/node; scales linearly with revenue |
| Plugin works fine without MEMANTO | Expected | None | That's by design. MEMANTO is enhancement, not requirement |
---
## Summary
| Decision | Recommendation |
|---|---|
| **Launch price** | $7/month or $59/year |
| **Cost per subscriber** | $0.10/month |
| **Margin** | ~98% |
| **Break-even** | 3 subscribers cover 1 VPS node |
| **Upsell path** | $7 → $9 → $15 Pro tier |
| **Key constraint** | User must provide own Moorcheh API key |
| **Key advantage** | No comparable product in WordPress ecosystem |
---
**Document Date:** June 7, 2026
**Status:** Draft — Pending validation with first 10 beta subscribers

View File

@@ -1,556 +0,0 @@
# Local Backend + Codex Provider System with Cloud Fallback
Implement a provider system allowing text generation via Local Backend (Claude CLI proxy) and Codex API, while keeping image generation on OpenRouter's cloud API.
## Architecture Overview (Based on local-backend-feature.md)
**Current State:**
- Plugin uses `WP_Agentic_Writer_OpenRouter_Provider` for all AI tasks
- All requests go to cloud APIs (OpenRouter)
- Costs per token, rate limits apply
- 23+ files directly call provider singleton
**New State:**
- **Local Backend**: User runs Node.js proxy on their machine (Claude CLI)
- **Codex Provider**: Direct integration with OpenAI Codex API
- **OpenRouter**: Fallback + image generation only
- **Provider Manager**: Routes tasks to appropriate provider
**Flow:**
```
WordPress Plugin → Provider Manager → Local Backend (http://user-ip:8080)
→ Codex API (https://api.openai.com)
→ OpenRouter (images + fallback)
```
## Provider Architecture
### 1. Provider Interface (Common Contract)
```php
interface WP_Agentic_Writer_AI_Provider_Interface {
public function chat($messages, $options, $type);
public function chat_stream($messages, $options, $type, $callback);
public function generate_image($prompt, $model, $options);
public function is_configured();
public function test_connection();
public function supports_task_type($type);
}
```
### 2. Provider Manager (Router)
```php
class WP_Agentic_Writer_Provider_Manager {
public static function get_provider_for_task($type) {
$settings = get_option('wp_agentic_writer_settings');
$task_providers = $settings['task_providers'] ?? [];
$provider_name = $task_providers[$type] ?? 'openrouter';
switch ($provider_name) {
case 'local_backend':
return new WP_Agentic_Writer_Local_Backend_Provider();
case 'codex':
return new WP_Agentic_Writer_Codex_Provider();
case 'openrouter':
default:
return WP_Agentic_Writer_OpenRouter_Provider::get_instance();
}
}
}
```
### 3. Provider Implementations
**A. Local Backend Provider** (Primary for text tasks)
- **File**: `includes/class-local-backend-provider.php`
- **Endpoint**: `http://192.168.x.x:8080` (user's machine)
- **Protocol**: HTTP POST to `/v1/messages` (OpenAI-compatible)
- **Backend**: Node.js proxy → Claude CLI
- **Supports**: `chat`, `clarity`, `planning`, `writing`, `refinement`
- **Cost**: $0 (uses user's Claude CLI + Z.ai/Anthropic)
**B. Codex Provider** (Alternative text provider)
- **File**: `includes/class-codex-provider.php`
- **Endpoint**: `https://api.openai.com/v1/chat/completions`
- **Protocol**: Standard OpenAI API
- **Supports**: `chat`, `clarity`, `planning`, `writing`, `refinement`
- **Cost**: Per OpenAI pricing
**C. OpenRouter Provider** (Existing, for images + fallback)
- **File**: `includes/class-openrouter-provider.php` (existing)
- **Endpoint**: `https://openrouter.ai/api/v1/chat/completions`
- **Supports**: ALL task types (fallback when local unavailable)
- **Primary use**: `image` generation only in hybrid mode
### Configuration Strategy
#### Settings Structure
```php
'wp_agentic_writer_settings' => [
// Provider routing
'provider_mode' => 'hybrid', // 'cloud', 'local', 'hybrid'
'task_providers' => [
'chat' => 'local_backend',
'clarity' => 'local_backend',
'planning' => 'local_backend',
'writing' => 'local_backend',
'refinement' => 'codex', // Or local_backend
'image' => 'openrouter' // Always OpenRouter
],
// Local Backend settings
'local_backend_url' => 'http://192.168.1.105:8080',
'local_backend_key' => 'dummy',
'local_backend_model' => 'claude-via-cli',
'local_backend_enabled' => true,
// Codex settings
'codex_api_key' => 'sk-...',
'codex_model' => 'gpt-4',
'codex_enabled' => true,
// OpenRouter (existing)
'openrouter_api_key' => 'sk-or-...',
'image_model' => 'black-forest-labs/flux-1.1-pro',
]
```
#### Recommended Configuration
**Optimal Hybrid Setup:**
```
chat → Local Backend (free, private, fast)
clarity → Local Backend (free, fast)
planning → Local Backend (free, fast)
writing → Local Backend (free, unlimited)
refinement → Codex (cloud quality when needed)
image → OpenRouter (only option for FLUX/Recraft)
```
**Benefits:**
- 80%+ requests via Local Backend = $0 cost
- Privacy for all text content
- Codex as quality alternative
- Images via best models (OpenRouter)
## Implementation Components
### 1. Local Backend Package (Separate Distribution)
**Package:** `agentic-writer-local-backend.zip`
**Contents:**
```
agentic-writer-local-backend/
├── claude-proxy.js # Node.js HTTP server
├── start-proxy.sh # Launch with IP detection
├── stop-proxy.sh # Clean shutdown
├── test-connection.sh # Verify proxy works
├── get-local-ip.sh # Find machine IP
├── package.json # Express dependency
├── README.md # Setup guide
└── TROUBLESHOOTING.md # Common issues
```
**Proxy Server (`claude-proxy.js`):**
- Spawns user's Claude CLI for each request
- OpenAI-compatible `/v1/messages` endpoint
- Health check `/ping` endpoint
- Binds to `0.0.0.0:8080` for LAN access
- Logs requests for debugging
**User Flow:**
1. Download ZIP from plugin settings
2. Extract and run `./start-proxy.sh`
3. Copy displayed Base URL (e.g., `http://192.168.1.105:8080`)
4. Paste into plugin settings
5. Test connection → generate content
### 2. Plugin Integration Files
**New Files:**
```
includes/class-local-backend-provider.php
includes/class-codex-provider.php
includes/class-provider-manager.php
includes/interface-ai-provider.php
views/settings/tab-local-backend.php
admin/js/test-local-backend.js
downloads/agentic-writer-local-backend.zip
```
**Modified Files:**
```
includes/class-openrouter-provider.php
→ Implement WP_Agentic_Writer_AI_Provider_Interface
→ No behavior changes
includes/class-gutenberg-sidebar.php
→ Replace: WP_Agentic_Writer_OpenRouter_Provider::get_instance()
→ With: WP_Agentic_Writer_Provider_Manager::get_provider_for_task($type)
+ 20 other files with provider calls
```
### 3. Settings UI
**New Tab:** "Local Backend"
- Download local backend package
- Base URL input
- API Key input (dummy)
- Model selector
- "Test Connection" button
- Connection status indicator
- Troubleshooting guide
**Per-Task Routing (Advanced):**
- Simple mode: Enable/Disable Local Backend (uses for all text)
- Advanced mode: Task routing matrix
### 4. Migration & Backwards Compatibility
**Phase 1: Abstraction (Non-Breaking)**
- Create `interface-ai-provider.php`
- Create `class-provider-manager.php`
- OpenRouter implements interface
- All calls route through manager → defaults to OpenRouter
- **100% backwards compatible, no settings changes**
**Phase 2: Local Backend Provider**
- Implement `class-local-backend-provider.php`
- Create proxy package (claude-proxy.js + scripts)
- Add "Local Backend" settings tab
- Implement connection test handler
- Test with user's local setup
**Phase 3: Codex Provider**
- Implement `class-codex-provider.php`
- Add Codex API key to settings
- Add Codex as task routing option
- Test Codex integration
**Phase 4: Update All Provider Calls**
- Update 23+ files to use Provider Manager
- Test all task types (chat, clarity, planning, writing, refinement, image)
- Ensure streaming works with all providers
- Verify cost tracking
## Key Technical Decisions
### Local Backend Protocol
**Why OpenAI-compatible format:**
- Plugin already uses message-based format
- Easy to proxy to Claude CLI
- Future-proof for other local models
**Request Format:**
```json
POST http://192.168.1.105:8080/v1/messages
{
"messages": [
{"role": "user", "content": "Write about AI"}
]
}
```
**Response Format:**
```json
{
"id": "local-1234567890",
"object": "chat.completion",
"model": "claude-local",
"choices": [{
"message": {
"role": "assistant",
"content": "Article content..."
},
"finish_reason": "stop"
}]
}
```
### Codex Integration
**Direct API Calls:**
- Use OpenAI PHP library or `wp_remote_post`
- Standard chat completions endpoint
- Same format as OpenRouter
**Why Codex:**
- High quality for coding/technical content
- Alternative to Local Backend
- Cloud-based when user's machine offline
## Cost Tracking Integration
**Challenge:** Local Backend = $0, Codex/OpenRouter = cost
**Solution:**
```php
// Provider returns cost data
$result = $provider->chat($messages, $options, $type);
$cost = $result['cost'] ?? 0;
if ($cost > 0 && $post_id > 0) {
do_action('wp_aw_after_api_request',
$post_id,
$result['model'] ?? 'unknown',
$type,
$result['input_tokens'] ?? 0,
$result['output_tokens'] ?? 0,
$cost
);
}
```
**Dashboard Display:**
```
Session Cost: $0.15
- Local Backend: 12 requests (free)
- Codex: 3 requests ($0.10)
- OpenRouter: 2 images ($0.05)
Today: $2.40
Month: $45.00
```
## Error Handling & Fallbacks
### Local Backend Unreachable
```php
$local_provider = new WP_Agentic_Writer_Local_Backend_Provider();
if (!$local_provider->is_available()) {
// Fallback to OpenRouter
error_log('Local Backend unavailable, using OpenRouter fallback');
return WP_Agentic_Writer_OpenRouter_Provider::get_instance();
}
```
**Admin Notice:**
"⚠️ Local Backend unreachable. Using OpenRouter fallback. Check proxy: `./start-proxy.sh`"
### Connection Test Results
```
✅ Connected! Proxy responding correctly.
❌ Connection timeout. Is proxy running? Check: ps aux | grep claude-proxy
❌ Connection refused. Start proxy: ./start-proxy.sh
❌ Wrong IP. Find correct IP: ./get-local-ip.sh
❌ Claude CLI not responding. Test: echo "test" | claude
```
## UI/UX Considerations
### Settings Page Flow
1. **Tab: Local Backend**
- Big download button for proxy package
- Prerequisites checklist
- Base URL input (pre-filled from clipboard?)
- Test connection button
- Status: 🟢 Connected / 🔴 Offline
2. **Tab: Providers**
- Simple mode: "Use Local Backend" toggle
- Advanced mode: Task routing matrix
- Provider status indicators
3. **Tab: Models** (existing)
- Add Codex models
- Show provider per model
### Sidebar Indicators
**Provider Badge:**
```
🏠 Local (Free)
🔗 Codex ($0.02)
☁️ OpenRouter ($0.05)
```
**Connection Status:**
```
🟢 Local Backend: Connected
🔴 Local Backend: Offline (using OpenRouter)
```
## Testing Strategy
**Test Cases:**
1. Cloud-only mode (existing behavior)
2. Local-only mode (Ollama for all text)
3. Hybrid mode (recommended config)
4. Fallback when Ollama unavailable
5. Streaming works with both providers
6. Cost tracking accurate
7. Model selection per provider
## Performance Implications
**Local Backend:**
- **Latency**: ~50-200ms LAN vs ~500-2000ms cloud
- **Throughput**: Limited by Claude CLI (~20-30 tokens/sec)
- **Concurrency**: One request at a time (spawn per request)
- **Quality**: Same as cloud Claude (uses same models)
**Codex:**
- **Latency**: Standard OpenAI API latency
- **Quality**: High for technical/coding content
- **Cost**: Per-token pricing
**OpenRouter:**
- **Image Generation**: Only option for FLUX/Recraft
- **Fallback**: When local backend offline
- **Cost**: Per-token pricing
## Deployment Scenarios
### Scenario 1: Local Development (User's Machine)
**Setup:**
- WordPress on Local by Flywheel (bricks.local)
- Node.js proxy on same machine (localhost:8080)
- Claude CLI configured with Z.ai
**Config:**
```
Local Backend URL: http://localhost:8080
All text tasks: Local Backend
Images: OpenRouter
Cost: ~$0 for text, ~$0.05/image
```
### Scenario 2: Local Dev + Cloud Production
**Dev:**
- Use Local Backend for free development
- Test with real Claude quality
**Production:**
- Auto-switch to OpenRouter when local unavailable
- Seamless fallback
### Scenario 3: Agency with Shared Local Backend
**Setup:**
- One machine runs proxy on LAN
- Multiple WordPress sites connect to it
- All sites share one Z.ai account
**Config:**
```
Local Backend URL: http://192.168.1.50:8080
Cost: Free for entire team
```
## Implementation Phases
### Phase 1: Core Infrastructure (Week 1)
- [ ] Create provider interface
- [ ] Create provider manager
- [ ] OpenRouter implements interface
- [ ] Update 3-5 files to use manager (test)
- [ ] Verify backwards compatibility
### Phase 2: Local Backend Package (Week 1)
- [ ] Create `claude-proxy.js` with `/v1/messages` endpoint
- [ ] Create startup/shutdown scripts
- [ ] Test with actual Claude CLI
- [ ] Package as ZIP
- [ ] Write README with setup guide
### Phase 3: Local Backend Provider (Week 2)
- [ ] Implement `class-local-backend-provider.php`
- [ ] Add settings tab UI
- [ ] Implement connection test
- [ ] Add ZIP download from settings
- [ ] Test end-to-end flow
### Phase 4: Codex Provider (Week 2)
- [ ] Implement `class-codex-provider.php`
- [ ] Add Codex API key to settings
- [ ] Test Codex integration
- [ ] Add to task routing options
### Phase 5: Full Rollout (Week 3)
- [ ] Update all 23+ files to use provider manager
- [ ] Test all task types
- [ ] Verify streaming works
- [ ] Test cost tracking
- [ ] Documentation
### Phase 6: Polish (Week 3)
- [ ] Connection status widget
- [ ] Auto-fallback logic
- [ ] Error messages with actionable guidance
- [ ] Video tutorial
- [ ] Troubleshooting guide
## Implementation Estimate
**Phase 1 (Infrastructure):** 4-5 hours
- Provider interface, manager, OpenRouter refactor
- Test with 3-5 files
**Phase 2 (Local Backend Package):** 6-8 hours
- Node.js proxy development
- Scripts (start, stop, test)
- ZIP packaging
- Documentation
**Phase 3 (Local Backend Integration):** 8-10 hours
- Provider class
- Settings UI
- Connection test
- End-to-end testing
**Phase 4 (Codex):** 4-6 hours
- Provider implementation
- Settings integration
- Testing
**Phase 5 (Full Rollout):** 8-10 hours
- Update 23+ files
- Test all scenarios
- Cost tracking
- Documentation
**Phase 6 (Polish):** 4-6 hours
- UI improvements
- Error handling
- Video tutorial
- Troubleshooting docs
**Total:** 34-45 hours (~1-1.5 weeks)
## Success Criteria
✅ User can download local backend package
✅ User can start proxy on their machine
✅ Plugin connects to local backend successfully
✅ All text tasks work via local backend ($0 cost)
✅ Images work via OpenRouter
✅ Codex works as alternative provider
✅ Automatic fallback to OpenRouter when local offline
✅ Cost tracking shows local = $0, cloud = actual cost
✅ Streaming works with all providers
✅ 100% backwards compatible (defaults to OpenRouter)
## Ready to Implement
This plan matches `local-backend-feature.md` requirements:
- ✅ Claude CLI proxy via Node.js
- ✅ HTTP-based local backend
- ✅ Codex integration
- ✅ OpenRouter for images
- ✅ Provider abstraction system
- ✅ Fallback logic
- ✅ Complete UI/UX flow
Confirm to proceed with implementation.